Having to get output from using create.js in my html file? - html

*I tried to create circle using createjs for initial html game development
Here in this code the drawing API or create.js allow object draw dynamically
*
enter code here
<html>
<head>
<title>HTML5 Course</title>
<script src="https://code.createjs.com/1.0.0/createjs.min.js"></script>
</head>
<body onload="init();">
<canvas id="testCanvas" width="500" height="500"></canvas>
<script>
function init()
{
var stage = new createjs.stage("testCanvas");
var circle = new createjs.Shape();
circle.graphics.beginFill("Red").dreawCircle(0,0,90);**
circle.x=250;**changing x axis**
circle.y=250;**changing y axis**
stage.addChild(circle); **Placing X,Y on the stage**
stage.update();
}
</script>
</body>
</html>

I don't exactly understand what you mean. If you are trying to capture console output, here is a simple example:
var output = [];
var saved = console.log;
console.log = function(arg) {
output.push(arg);
saved(arg);
};
console.log('Hello, world!');
What this does is replace the inbuilt console.log method with a new one that captures console output.
Why we have a variable called saved is a backup of the old console.log before we relaced it, so it'll still be able to write to the console.

Related

exporting .txt files in html, and then importing it afterwards

So im making a website, and one of its core features I need to get working is getting the web page to export a mundane .txt file containing all the content from the forms I have.
Once that works, I also need to figure out how to import that same file back into the website and have it automatically fill in the text boxes.
How can I go about doing this?
Your question is kind of broad and doesn't show much research effort on your part. It's good form to have a go and then come here when you run into a problem, rather than just ask us to solve your problem for you. Despite that, I'll try to give you some pointers. :)
I recently had a requirement to make a button to download the contents of a div. I made a gist for future reference. You can probably adapt it to your purpose.
Basically what I did was assign a click handler to a HTML button marked 'Download'. When the button is clicked, I create a temporary anchor element on the page and set its href to the contents of the div and then programmatically click on the anchor to fire the download and finally removing the temporary anchor from the page. There's a fallback for Internet Explorer with a different method. I adapted this code from an SO answer some time ago.
var downloadButton = document.getElementById('downloadButton');
downloadButton.addEventListener('click', function () {
//get the contents of the div
var contents = document.getElementById('someDiv').innerHTML;
if (contents.length = 0) {
return;
}
var filename = 'some-filename.txt';
if (navigator.msSaveBlob) { // IE
navigator.msSaveBlob(new Blob([contents], { type: 'text/plain;charset=utf-8;' }), filename);
} else {
var link = document.createElement('a');
link.setAttribute('download', filename);
link.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(contents));
document.body.append(link);
link.click();
document.body.removeChild(link);
}
});
As for your next requirement, upload the file and importing the data, I'll direct you to the HTML5 Rocks - file handling tutorial.
I just had a crack at a quick file uploader and I have it dumping the file contents to the console. You could, instead, parse the file contents and add the data back to your form elements as required. Here's my test code:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Test Page</title>
<script>
function handleFileSelect(evt) {
var files = evt.target.files; // FileList object
// Loop through the FileList
for (var i = 0; i < files.length; i++) {
var reader = new FileReader();
// when the file has been read, print the contents to the console
reader.onloadend = function (evt) {
if (evt.target.readyState == FileReader.DONE) {
console.log(evt.target.result);
}
};
var text = reader.readAsText(files[i]);
}
}
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('files').addEventListener('change', handleFileSelect, false);
});
</script>
</head>
<body>
<input type="file" id="files" name="files[]" multiple />
</body>
</html>

HTML from Adobe Animate (formerly Flash) - Sprite Sheet causes problems in specific browsers

all! Experienced animator, but very new to programming, so every baby step is an exciting new roadblock. I've been hired to create/animate some HTML web banners, and am using Adobe Animate.
In order to keep my file sizes down, I have my publishing settings set to combine images into a sprite sheet. This seems to work fine when I test the HTML in Firefox, but when I test it in any other browser, I just see a blank background. Forgoing the sprite sheet solves the problem, but bloats my k-weight. I've tried setting the sprite sheet to PNG-8, PNG-24, and PNG-32, and the error persists.
I'm not sure if this additional info makes a difference, but clicking in the blank background doesn't activate the link, so the images aren't simply "invisible".
Thank you in advance, everyone!
Edit 1: Here is the code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>File_Camper2_size300x250_v6</title>
<!-- write your code here -->
<script src="https://code.createjs.com/createjs-2015.11.26.min.js"></script>
<script src="File_Camper2_size300x250_v6.js?1466448165331"></script>
<script>
var canvas, stage, exportRoot;
function init() {
// --- write your JS code here ---
canvas = document.getElementById("canvas");
images = images||{};
ss = ss||{};
var loader = new createjs.LoadQueue(false);
loader.addEventListener("fileload", handleFileLoad);
loader.addEventListener("complete", handleComplete);
loader.loadFile({src:"images/File_Camper2_size300x250_v6_atlas_.json?1466448165331", type:"spritesheet", id:"File_Camper2_size300x250_v6_atlas_"}, true);
loader.loadManifest(lib.properties.manifest);
}
function handleFileLoad(evt) {
if (evt.item.type == "image") { images[evt.item.id] = evt.result; }
}
function handleComplete(evt) {
var queue = evt.target;
ss["File_Camper2_size300x250_v6_atlas_"] = queue.getResult("File_Camper2_size300x250_v6_atlas_");
exportRoot = new lib.File_Camper2_size300x250_v6();
stage = new createjs.Stage(canvas);
stage.addChild(exportRoot);
stage.update();
stage.enableMouseOver();
createjs.Ticker.setFPS(lib.properties.fps);
createjs.Ticker.addEventListener("tick", stage);
}
</script>
<!-- write your code here -->
</head>
<body onload="init();" style="background-color:#D4D4D4;margin:0px;">
<canvas id="canvas" width="300" height="250" style="background-color:#FFFFFF"></canvas>
</body>
</html>
Edit 2: The following console errors appear in Google Chrome, indicating the json error mentioned below.
XMLHttpRequest cannot load file:///Users/jonron2000/Documents/Company%20Name/Ice%20Cream%20Summer/Revamped/v6/images/File_size300x250_v6_atlas_.json?1466448165331. Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https, chrome-extension-resource.b.load # createjs-2015.11.26.min.js:15
createjs-2015.11.26.min.js:13
Uncaught TypeError: Cannot read property 'getNumFrames' of undefinedb.load # createjs-2015.11.26.min.js:15

populating a DataTable with a JSON file directly, or querying a local spreadsheet (google visualization)

I am looking for the easiest way to populate a data table in google visualizations using either a json file or a local spreadsheet(.xlsx).
heres my code:
<!DOCTYPE html>
<html>
<head>
<!--Load the AJAX API-->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.load('visualization', '1', {'packages':['corechart']});
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable.fromJSON(sampleData.json,0.6);
// Instantiate and draw our chart, passing in some options.
var chart = new google.visualization.PieChart(document.getElementById('chart_div'));
chart.draw(data, {width: 400, height: 240});
}
</script>
</head>
<body>
<!--Div that will hold the pie chart-->
<div id="chart_div"></div>
</body>
</html>
Heres my json file:
{
"cols": [
{"id":"","label":"Topping","pattern":"","type":"string"},
{"id":"","label":"Slices","pattern":"","type":"number"}
],
"rows": [
{"c":[{"v":"Mushrooms","f":null},{"v":3,"f":null}]},
{"c":[{"v":"Onions","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Olives","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Zucchini","f":null},{"v":1,"f":null}]},
{"c":[{"v":"Pepperoni","f":null},{"v":2,"f":null}]}
]
}
When I run my code in my browser, I get
"Uncaught ReferenceError: sampleData is not defined"
Anyone know how I can make this work?
Thanks in advance
You COULD simply place the contents of your JSON file right inline there in your HTML where the string "sampleData.JSON" is. That is, take out "sampleData.JSON" and replace it with the entire contents of your JSON file. I'm pretty sure you'll make some progress if you do this.
Try putting sampleData.json in quotes, assuming that the filename is sampleData.json and is in the same folder as your HTML.
var data = new google.visualization.DataTable.fromJSON('sampleData.json',0.6);

Google App Scripts : Javascript code inside the HTML file not functioning

I have been trying to write a small Google App Script which has the Google+ badge as shown here. For this I have a plain HTML file where I have included the HTML as shown on that page. The HTML page is as follows :
<html>
<body>
<div class="g-plus" data-href="{Page-Link}" data-rel="publisher"></div>
<script type="text/javascript">
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
alert("Added Badge!");
})();
</script>
</body>
</html>
The result is a blank page. There is no badge added to the page . I assume this is because the javascript function is not being run( I added an alert and there wasnt any pop-up ).I am not able to figure out why the function is not being run.
Any help is appreciated.
Unfortunately I'm not too experienced with Javascript so I'm guessing here. I've programmed in coffeescript a while ago and its compiler automatically wraps the generated code in an anonimous function just as in your code. This function is called so:
(function() {//...}).call(this);
Maybe this works.
Alternatively you might want to move the alert test above the badge generation. This would show if the javascript is run at all. Maybe the error lies in your badge creation code.
My final idea would be to name your function and register it as a callback on body.onload . It's always a good idea to let the browser load the page before accessing the dom

Get chrome tabs and windows from localStorage

I am trying to access tabs and windows data inside a Google Chrome extension. I've apparently managed to get this info and loading it through localStorage but I don't know how to use the information, since I can't seem to parse the data back to arrays of objects through JSON parse.
Here's the code:
<html>
<head>
<script>
tabs = {};
tabIds = [];
focusedWindowId = undefined;
currentWindowId = undefined;
localStorage.windowsTabsArray = undefined;
function loadItUp() {
return arrays = chrome.windows.getAll({ populate: true }, function(windowList) {
tabs = {};
tabIds = [];
var groupsarr = new Array();
var tabsarr = new Array();
var groupstabs = new Array();
for (var i = 0; i < windowList.length; i++) {
windowList[i].current = (windowList[i].id == currentWindowId);
windowList[i].focused = (windowList[i].id == focusedWindowId);
groupsarr[windowList[i].id] = "Untitled"+i;
for (var j = 0; j < windowList[i].tabs.length; j++) {
tabsarr[windowList[i].tabs[j].id] = windowList[i].tabs[j];
groupstabs[windowList[i].id] = windowList[i].tabs;
}
}
localStorage.groupsArray = JSON.stringify(groupsarr);
localStorage.tabsArray = JSON.stringify(tabsarr);
localStorage.groupsTabsArray = JSON.stringify(groupstabs);
});
}
function addGroup() {
var name = prompt("NEW_GROUP_NAME");
var groupsarr = JSON.parse(localStorage.groupsArray);
groupsarr.push(name);
localStorage.groupsArray = JSON.stringify(groupsarr);
}
</script>
</head>
<body onload="loadItUp()">
WINDOW_QTY:
<script type="text/javascript">
var wArray = JSON.parse(localStorage.groupsArray);
document.write(wArray);
</script>
<br/>
TABS_QTY:
<script type="text/javascript">
var tArray = JSON.parse(localStorage.tabsArray)
document.write(tArray);
</script>
<br/>
WINDOWS_TABS_QTY:
<script type="text/javascript">
document.write(JSON.parse(localStorage.groupsTabsArray));
</script>
<br/>
</body>
</html>
1)
The page shows bunch of [object Object].
That's expected, objects are implicitly converted to string when you call document.write(tArray);; custom object without a custom toString implementation are converted to "[object Object]". It doesn't mean they're not "parsed".
To inspect the object you can use the Developer Tools. You can open the inspector for a background page from the Extensions page and if you get your page to open in a tab (e.g. if you use chrome_url_overrides) you can inspect it as you would inspect a regular web page.
If you replace the document.write calls with console.log(), you'll be able to inspect the objects in the Developer Tools' console.
2)
Do you realize that the document.write calls in tags run before loadItUp()?
Had no idea that the page code was being executed before loadItUp().
Scripts are executed at the moment they are inserted in the DOM by the parser (unless they are deferred or async) - see MDC documentation on <script>, - while various load events, in particular <body onload=...>, are executed after the page is finished parsing.
So right now your document.write calls print the values that were saved to localStorage the previous time the page was loaded, it's probably not what you wanted.
Instead of using document.write() from inline scripts, you should use element.innerHTML or element.textContent to update the page's text. There are many ways to get a reference to the element you need, document.getElementById() is one.
3)
Last, note that not every object can be saved to and then loaded from localStorage. For example, methods will not survive the round-trip, and the identity of the object is not preserved, meaning that the object you got from a Chrome API will not be the same object after you store it in localStorage and load it back.
You have not explained why you think you need localStorage - it's used when you want to preserve some data after the page is closed and reloaded - so maybe you don't really need it?