I am new to metro style programming so I am following a tutorial here http://www.sitepoint.com/creating-a-simple-windows-8-game-with-javascript-game-basics-createjseaseljs/ for games using createJS. Here the code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>game</title>
<!-- WinJS references -->
<link href="//Microsoft.WinJS.1.0.RC/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0.RC/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0.RC/js/ui.js"></script>
<!-- game references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
<script src="/js/CreateJS/easeljs-0.5.0.min.js"></script>
<script src="/js/CreateJS/preloadjs-0.2.0.min.js"></script>
</head>
<body>
<canvas id="gameCanvas"></canvas>
</body>
</html>
and here's javascript code
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
"use strict";
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
WinJS.strictProcessing();
function initialize() {
canvas = document.getElementById("gameCanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context = canvas.getContext("2d");
preload = new PreloadJS();
preload.onComplete = prepareGame;
var manifest = [
{ id: "screenImage", src: "images/Backgrounds/gameplay_screen.png" },
{ id: "redImage", src: "images/Catapults/Red/redIdle/redIdle.png" },
{ id: "blueImage", src: "images/Catapults/Blue/blueIdle/blueIdle.png" },
{ id: "ammoImage", src: "images/Ammo/rock_ammo.png" },
{ id: "winImage", src: "images/Backgrounds/victory.png" },
{ id: "loseImage", src: "images/Backgrounds/defeat.png" },
{ id: "blueFire", src: "images/Catapults/Blue/blueFire/blueCatapult_fire.png" },
{ id: "redFire", src: "images/Catapults/Red/redFire/redCatapult_fire.png" },
];
preload.loadManifest(manifest);
stage = new Stage(canvas);
}
function prepareGame() {
bgImage = preload.getResult("screenImage").result;
bgBitmap = new Bitmap(bgImage);
bgBitmap.scaleX = SCALE_X;
bgBitmap.scaleY = SCALE_Y;
stage.addChild(bgBitmap);
stage.update();
}
function gameLoop() {
}
function update() {
}
function draw() {
}
var canvas, context, stage;
var bgImage, p1Image, p2Image, ammoImage, p1lives, p2lives, title, endGameImage;
var bgBitmap, p1Bitmap, p2Bitmap, ammoBitmap;
var preload;
// Current Display Factor. Because the orignal assumed a 800x480 screen
var SCALE_X = window.innerWidth / 800;
var SCALE_Y = window.innerHeight / 480;
var MARGIN = 25;
var GROUND_Y = 390 * SCALE_Y;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// TODO: This application has been newly launched. Initialize
// your application here.
} else {
// TODO: This application has been reactivated from suspension.
// Restore application state here.
}
args.setPromise(WinJS.UI.processAll());
}
};
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state
// that needs to persist across suspensions here. You might use the
// WinJS.Application.sessionState object, which is automatically
// saved and restored across suspension. If you need to complete an
// asynchronous operation before your application is suspended, call
// args.setPromise().
};
document.addEventListener("DOMContentLoaded", initialize, false);
app.start();
})();
Now the problem is that whenever I try to compile the code it gives me the Preload is undefined error. I do not understand the reason I have included the script in HTML and file in my project. Would somebody please help this problem has been killing me for the last hour and I just want to make a simple game.
The reason for this is that the libraries have been placed under the "createjs" namespace. In order to instantiate the PreloadJS object, please do the following:
var preload = new createjs.PreloadJS();
That should get you back to happy path.
(Tried on Feb 2013, after PreloadJS 0.3.0 released)
I just tried the tutorial from sitepoint.com (http://www.sitepoint.com/creating-a-simple-windows-8-game-with-javascript-game-basics-createjseaseljs/), using the latest versions of EaselJS and PreloadJS, but I couldn't get the code to run without errors at first.
The new version of PreloadJS (v0.3.0) has renamed the old PreloadJS class to LoadQueue.
See the documentation at the links below:
http://www.createjs.com/Docs/PreloadJS/classes/PreloadJS.html
http://www.createjs.com/Docs/PreloadJS/classes/LoadQueue.html
But simply using the new class while using v0.3.0 doesn't fix the project. The newer version has additional incompatibilities (e.g. image.width is not valid) which can probably be fixed by trial and error.
I had to download the older PreloadJS v0.2.0:
https://github.com/CreateJS/PreloadJS/tags
IN A NUTSHELL: If I use the SitePoint tutorial, I have to stick with PreloadJS v0.2.0 and also use the createjs namespace.
NOTE: The sample project mentioned in a previous response doesn't work either, because its WinJS references are invalid. Adding the reference manually doesn't seem to work either.
https://github.com/dave-pointbypoint/CatapultGame
Move your default.js in the HTML to be after the preloadjs & easel code.
This is because the order of inclusion is important to JavaScript
Related
I'm just starting to use Laravel (v 8.x) Mix in a project, and am finding it frustrating to implement Javascript from node modules.
To begin, I have this in my webpack.mix.js:
mix.js('node_modules/mxgraph/javascript/mxClient.min.js', 'public/js');
mix.js('resources/js/*.js', 'public/js').postCss('resources/css/app.css', 'public/css', [
require('postcss-import'),
require('tailwindcss'),
require('autoprefixer'),
]).version();
Next, my app.js contains the following:
import Canvas from './canvas';
require('mxgraph');
const canvas = new Canvas();
...which imports canvas.js:
export default class Canvas {
constructor() {
this.container = document.getElementById('graphContainer');
if (!mxClient.isBrowserSupported())
{
// Displays an error message if the browser is not supported.
alert('Browser is not supported!');
}
.
.
.
}
}
...and in the Scripts section of my Blade layout:
<script src="{{ mix('js/mxClient.min.js') }}" defer></script>
<script src="{{ mix('js/app.js') }}" defer></script>
When I load the page, I get the following error in the console:
Uncaught ReferenceError: mxClient is not defined
at new Canvas (app.js:3866)
at Module../resources/js/app.js (app.js:3813)
at __webpack_require__ (app.js:114081)
at app.js:114143
at app.js:114149
var mxClient is definitely present in mxClient.min.js, and the reference to it in Canvas occurs after it's loaded.
I've tried a bunch of variations, and nothing seems to work. Any guidance would be greatly appreciated.
After a lot more poking and searching around, I found a method that works. It was based on what I found here:
https://www.programmersought.com/article/85491421858/
My implementation seems a bit clunky, but it does work, and I can now continue the project I'm trying to develop with mxGraph.
Thus, I no longer pull in mxgraph explicitly in webpack.mix.js, so it now reverts to the Laravel default:
mix.js('resources/js/*.js', 'public/js').postCss('resources/css/app.css', 'public/css', [
require('postcss-import'),
require('tailwindcss'),
require('autoprefixer'),
]).version();
I've also removed require('mxgraph'); from app.js, so it just looks like this:
import Canvas from './canvas';
const canvas = new Canvas();
My canvas.js now looks like this:
import mx from 'mxgraph';
const mxgraph = mx({
mxImageBasePath: './src/images',
mxBasePath: './src'
});
window.mxGraph = mxgraph.mxGraph;
window.mxGraphModel = mxgraph.mxGraphModel;
window.mxEvent = mxgraph.mxEvent;
window.mxEditor = mxgraph.mxEditor;
window.mxGeometry = mxgraph.mxGeometry;
window.mxRubberband = mxgraph.mxRubberband;
window.mxDefaultKeyHandler = mxgraph.mxDefaultKeyHandler;
window.mxDefaultPopupMenu = mxgraph.mxDefaultPopupMenu;
window.mxStylesheet = mxgraph.mxStylesheet;
window.mxDefaultToolbar = mxgraph.mxDefaultToolbar;
const {mxGraph, mxClient, mxEvent, mxCodec, mxUtils, mxConstants, mxPerimeter, mxRubberband} = mxgraph;
export default class Canvas {
constructor() {
let container = document.getElementById('graphContainer');
if (typeof(mxClient) !== 'undefined') {
this.draw(container);
}
}
draw (container) {
if (! mxClient.isBrowserSupported())
{
// Displays an error message if the browser is not supported.
mxUtils.error('Browser is not supported!', 200, false);
}
else
{
// Disables the built-in context menu
mxEvent.disableContextMenu(container);
// Creates the graph inside the given container
var graph = new mxGraph(container);
// Enables rubberband selection
new mxRubberband(graph);
// Gets the default parent for inserting new cells. This
// is normally the first child of the root (ie. layer 0).
var parent = graph.getDefaultParent();
// Adds cells to the model in a single step
graph.getModel().beginUpdate();
try
{
var v1 = graph.insertVertex(parent, null, 'Hello,', 20, 20, 80, 30);
var v2 = graph.insertVertex(parent, null, 'World!', 200, 150, 80, 30);
var e1 = graph.insertEdge(parent, null, '', v1, v2);
}
finally
{
// Updates the display
graph.getModel().endUpdate();
}
}
}
}
Most of the code in the draw() method is taken from an mxGraph "Hello World" demo (https://jgraph.github.io/mxgraph/docs/manual.html).
Many thanks to #codedge for the time you spent helping me!
So, after playing around I found what you can do.
Assemble one file
Put mxClient.min.js and app.js into one file by doing
mix.js(
[
"resources/js/app.js",
"node_modules/mxgraph/javascript/mxClient.min.js",
],
"public/js"
).postCss('resources/css/app.css', 'public/css', [
require('postcss-import'),
require('tailwindcss'),
require('autoprefixer'),
]).version();
Import mxGraph and Canvas
In your app.js you can put that
import "./canvas";
require("mxgraph");
const canvas = new Canvas();
and npm run dev runs without issues.
Update
I found a (maybe easier) option. Don't include mxClient in your webpack.mix.js, only your app.js is needed.
// app.js
window.mxClient = new require("mxgraph")().mxClient;
let isBrowserSupported = mxClient.isBrowserSupported();
console.log(isBrowserSupported);
I am building a chrome extension using Javascript which gets URLs of the opened tabs and saves the html file, but the problem with html is that it does not render images on webpages fully. So i changed my code to loop each URLs of the tabs and then save each html pages as image file automatically in one click on the download icon of the chrome extension. I have been researching for more than 2 days but nothing happened. Please see my code files and guide me. I know there is library in nodejs but i want to perform html to jpeg/png maker using chrome extension only.
Only icons i have not attached which i have used in this extension, all code i have and the text in popup.js which is commented i have tried.
Current output of the attached code
Updated popup.js
File popup.js - This file has functions which gets all the URLs of the opened tabs in the browser window
// script for popup.html
window.onload = () => {
// var html2obj = html2canvas(document.body);
// var queue = html2obj.parse();
// var canvas = html2obj.render(queue);
// var img = canvas.toDataURL("image/png");
let btn = document.querySelector("#btnDL");
btn.innerHTML = "Download";
function display(){
// alert('Click button is pressed')
window.open("image/url");
}
btn.addEventListener('click', display);
}
chrome.windows.getAll({populate:true}, getAllOpenWindows);
function getAllOpenWindows(winData) {
var tabs = [];
for (var i in winData) {
if (winData[i].focused === true) {
var winTabs = winData[i].tabs;
var totTabs = winTabs.length;
console.log("Number of opened tabs: "+ totTabs);
for (var j=0; j<totTabs;j++) {
tabs.push(winTabs[j].url);
// Get the HTML string in the tab_html_string
tab_html_string = get_html_string(winTabs[j].url)
// get the HTML document of each tab
tab_document = get_html_document(tab_html_string)
console.log(tab_document)
let canvasref = document.querySelector("#capture");
canvasref.appendChild(tab_document.body);
html2canvas(document.querySelector("#capture")).then(canvasref => {
document.body.appendChild(canvasref)
var img = canvasref.toDataURL("image/png");
window.open(img)
});
}
}
}
console.log(tabs);
}
function get_html_document(tab_html_string){
/**
* Convert a template string into HTML DOM nodes
*/
var parser = new DOMParser();
var doc = parser.parseFromString(tab_html_string, 'text/html');
return doc;
}
function get_html_string(URL_string){
/**
* Convert a URL into HTML string
*/
let xhr = new XMLHttpRequest();
xhr.open('GET', URL_string, false);
try {
xhr.send();
if (xhr.status != 200) {
alert(`Error ${xhr.status}: ${xhr.statusText}`);
} else {
return xhr.response
}
} catch(err) {
// instead of onerror
alert("Request failed");
}
}
File popup.html - This file represent icon and click functionality on the chrome browser search bar
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
<script src= './html2canvas.min.js'></script>
<script src= './jquery.min.js'></script>
<script src='./popup.js'></script>
<title>Capture extension</title>
<!--
- JavaScript and HTML must be in separate files: see our Content Security
- Policy documentation[1] for details and explanation.
-
- [1]: http://developer.chrome.com/extensions/contentSecurityPolicy.html
-->
</head>
<body>
<button id="btnDL"></button>
</body>
</html>
File manifest.json - This file is used by the chrome browser to execute the chrome extension
{
"manifest_version": 2,
"name": "CIP screen capture",
"description": "One-click download for files from open tabs",
"version": "1.4.0.2",
"browser_action": {
"default_popup": "popup.html"
},
"permissions": [
"downloads", "tabs", "<all_urls>"
],
"options_page": "options.html"
}
You can use the library html2canvas which renders any html element, particularly the body element, and from the resulted canvas you can have your image
<script type="text/javascript" src="https://github.com/niklasvh/html2canvas/releases/download/v1.0.0-rc.7/html2canvas.min.js"></script>
<script>
html2canvas(document.body).then(
(canvas) => {
var img = canvas.toDataURL("image/png");
}
);
</script>
You can get html2canvas from any public CDN, like this one. You don't need nodeJS. Or perhaps directly from the original git repo
<script type="text/javascript" src="https://github.com/niklasvh/html2canvas/releases/download/v1.0.0-rc.7/html2canvas.min.js"></script>
You can also save canvas as a blob
html2canvas(document.body).then(function(canvas) {
// Export canvas as a blob
canvas.toBlob(function(blob) {
// Generate file download
window.saveAs(blob, "yourwebsite_screenshot.png");
});
});
It's possible with vanilla JS, I guess vanilla is more likely to be used on a extension, the drawback is the end result, when a 3rd party library my already fixed the issues you will encounter with fonts and style (html2canvas or whatever).
So, vanilla js, for some reason stack overflow snippet does not permit window.open, demo here: https://jsfiddle.net/j67nqsme/
Few words on how it was implemented:
using html to svg transformation, a 3rd party library can be used here
using canvas to transform svg into pdg or jpg
example can export html or page to svg, png, jpg
it is not bullet proof - rendering can suffer, style, fonts, ratios, media query
Disclaimer: I won't help you debug or find solution of your problem, it is an answer to your question using vanilla js, from there on is your decision what you are using or how you are using it.
Source code bellow:
<html>
<body>
<script>
function export1() {
const html = '<div style="color:red">this is <br> sparta </div>';
renderHtmlToImage(html, 800, 600, "image/png");
}
function export2() {
renderDocumentToImage(window.document, 800, 600, "image/png");
}
// format is: image/jpeg, image/png, image/svg+xml
function exportImage(base64data, width, height, format) {
var img = new Image();
img.onload = function () {
if ("image/svg+xml" == format) {
var w = window.open("");
w.document.write(img.outerHTML);
w.document.close();
}
else {
const canvas = document.createElement("Canvas");
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0);
var exportImage = new Image();
exportImage.onload = function () {
var w = window.open("");
w.document.write(exportImage.outerHTML);
w.document.close();
}
exportImage.src = canvas.toDataURL(format);
}
}
img.src = base64data;
}
// format is: image/jpeg, image/png, image/svg+xml
function renderHtmlToImage(html, width, height, format) {
var svgData = '<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '">'
+ '<foreignObject width="100%" height="100%">'
+ html2SvgXml(html)
+ '</foreignObject>'
+ '</svg>';
var base64data = "data:image/svg+xml;base64," + btoa(svgData);
exportImage(base64data, width, height, format);
}
function renderDocumentToImage(doc, width, height, format) {
var svgData = '<svg xmlns="http://www.w3.org/2000/svg" width="' + width + '" height="' + height + '">'
+ '<foreignObject width="100%" height="100%">'
+ document2SvgXml(doc)
+ '</foreignObject>'
+ '</svg>';
var base64data = "data:image/svg+xml;base64," + btoa(svgData);
exportImage(base64data, width, height, format);
}
// plain html to svgXml
function html2SvgXml(html) {
var htmlDoc = document.implementation.createHTMLDocument('');
htmlDoc.write(html);
// process document
return document2SvgXml(htmlDoc);
}
// htmlDocument to
function document2SvgXml(htmlDoc) {
// Set the xmlns namespace
htmlDoc.documentElement.setAttribute('xmlns', htmlDoc.documentElement.namespaceURI);
// Get XML
var svcXml = (new XMLSerializer()).serializeToString(htmlDoc.body);
return svcXml;
}
</script>
<div>
<h3 style="color:blue">My Title</h3>
<div style="color:red">
My Text
</div>
<button onclick="export1()">Export Plain Html</button>
<button onclick="export2()">Export Entire Document</button>
</div>
</body>
</html>
There are 3 ways this could be approached:
Render this in client javascript using an API like HTML2Canvas. It's isolated, runs in the browser, but relies on a re-render that could get details of the captured page wrong (see most issues with H2C). That might be fine if you just want a small preview and don't mind the odd difference. Also be careful as the render is slow and somewhat heavyweight - background renders of large pages may be noticeable by users, but so will waits for the images to render.
Use a service that runs Chrome to visit the page and then screenshot it. You could write this or buy in a service like Site-Shot to do it for you. This requires a service which will have a cost, but can guarantee the render is accurate and ensures the load on the users' machines is minimal.
Use the Chrome tab capture API to screenshot the tab. This is probably the best option for an extension, but currently you can only capture the current active tab. captureOffscreenTab is coming soon, but currently only in Canary behind a flag.
I'd recommend option 3, as by the time you have finished the component you could have access to the new features. If you need to release soon you could use 1 or 2 as a short term solution.
I have some webfonts that get loaded via Webfontloader load like this ...
<script src="//ajax.googleapis.com/ajax/libs/webfont/1.5.10/webfont.js"></script>
<script>
WebFont.load({
custom: {
families: ['BlenderProBook', 'BlenderProMedium']
}
});
</script>
And it works great when first loading the page ... Problems is, when refreshing the page it only retrieves the cached fonts when requested in html and not before my ReactJS app runs (when the Webfontloader normally gets them). This is too late for me, because I'm using them in pre-generated SVG.
Is there a way to force it to get the uncached fonts each time? Or better, load the cached fonts at the correct time.
I found a solution to this, which I will take as my answer if no-one else can supply a better one.
My font is being used extensively in the app to calculate text widths and therefore layout ... (which is why it needs to be loaded before the app runs), so I decided to use the text width code as a test to block the app from running.
Here's the code
var testFont = require('./components/svgText.js');
var timer = setInterval(function () {
var test = (testFont('TEST', 'BlenderProBook', 20).width === 39.75);
if (test) {
clearInterval(timer);
Router.run(routes, function (Handler) {
React.render(<Handler/>, document.body);
});
}
}, 50);
where svgTest.js uses Raphael SVG to generate SVG text and retrieve the measurements like this:-
renderedTextSize = function (string, font, fontSize) {
var paper = Raphael(0, 0, 0, 0);
paper.canvas.style.visibility = 'hidden';
var el = paper.text(0, 0, string);
el.attr('font-family', font);
el.attr('font-size', fontSize);
var bBox = el.getBBox();
paper.remove();
return {
width: bBox.width,
height: bBox.height
};
};
module.exports = renderedTextSize;
This seems to work quite nicely, even though it feels a bit hacky to be testing against a magic number (width).
I work on an JS application which use canvas to manipulate a picture (i.e and convert to png/base64 with .toBlob() and .toDataURL().
I would use .transferControlToProxy() to let a worker do the job and get a smooth GUI.
But it seems to be unsupported... as they said on Mozilla devs
Some of you have other information ?
Maybe a workaround ?
Whatwg.org has a javascript sample of using canvas.transferControlToProxy() at https://developers.whatwg.org/the-canvas-element.html#dom-canvas-transfercontroltoproxy, but it does not seem to work in any browser, even not in bleeding edge versions (Chrome Canary or Opera Next).
Even turning "Enable experimental canvas features" at chrome://flags has no effect in Chrome Canary.
Test live: http://jsbin.com/bocoti/5/edit?html,output
It says: "TypeError: canvas.transferControlToProxy is not a function".
This would be a very fine addition. Think of drawing everything on canvas in a worker and make a blob/arraybuffer/dataurl of canvas and transfer this to main thread using Transferable objects. Nowadays if you want to draw something on canvas using canvas functions (fill(), drawImage() etc.), you have to do it in main thread...
<!DOCTYPE html><html><head><meta charset="utf-8" /></head><body>
<div id="log"></div>
<canvas style="border:1px solid red"></canvas>
<script id="worker1" type="javascript/worker">
self.onmessage = function(e) {
var context = new CanvasRenderingContext2D();
e.data.setContext(context); // event.data is the CanvasProxy object
setInterval(function () {
context.clearRect(0, 0, context.width, context.height);
context.fillText(new Date(), 0, 100);
context.commit();
}, 1000);
}
</script>
<script>
var blob = new Blob([document.querySelector('#worker1').textContent]);
var worker = new Worker(window.URL.createObjectURL(blob));
worker.onmessage = function(e) {
//document.querySelector("#log").innerHTML = "Received: " + e.data;
}
var canvas = document.getElementsByTagName('canvas')[0];
try { var proxy = canvas.transferControlToProxy();
worker.postMessage(proxy, [proxy]);}
catch(e) { document.querySelector("#log").innerHTML = e; }
</script>
<br>
From: https://developers.whatwg.org/the-canvas-element.html#the-canvas-element
</body></html>
I'm trying to do this tutorial:
http://www.sitepoint.com/creating-a-simple-windows-8-game-with-javascript-game-basics-createjseaseljs/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>CatapultGame</title>
<!-- WinJS references -->
<link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
<!-- CatapultGame references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
<script src="js/CreateJS/easeljs-0.6.0.min.js"></script>
<script src="js/CreateJS/preloadjs-0.2.0.min.js"></script>
</head>
<body>
<canvas id="gameCanvas"></canvas>
</body>
</html>
and there is JS file
// For an introduction to the Blank template, see the following documentation:
// http://go.microsoft.com/fwlink/?LinkId=232509
(function () {
"use strict";
WinJS.Binding.optimizeBindingReferences = true;
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
WinJS.strictProcessing();
var canvas, context, stage;
var bgImage, p1Image, p2Image, ammoImage, p1lives, p2lives, title, endGameImage;
var bgBitmap, p1Bitmap, p2Bitmap, ammoBitmap;
var preload;
// Current Display Factor. Because the orignal assumed a 800x480 screen
var SCALE_X = window.innerWidth / 800;
var SCALE_Y = window.innerHeight / 480;
var MARGIN = 25;
var GROUND_Y = 390 * SCALE_Y;
function initialize() {
canvas = document.getElementById("gameCanvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
context = canvas.getContext("2d");
preload = new createjs.PreloadJS();
preload.onComplete = prepareGame;
var manifest = [
{ id: "screenImage", src: "images/Backgrounds/gameplay_screen.png" },
{ id: "redImage", src: "images/Catapults/Red/redIdle/redIdle.png" },
{ id: "blueImage", src: "images/Catapults/Blue/blueIdle/blueIdle.png" },
{ id: "ammoImage", src: "images/Ammo/rock_ammo.png" },
{ id: "winImage", src: "images/Backgrounds/victory.png" },
{ id: "loseImage", src: "images/Backgrounds/defeat.png" },
{ id: "blueFire", src: "images/Catapults/Blue/blueFire/blueCatapult_fire.png" },
{ id: "redFire", src: "images/Catapults/Red/redFire/redCatapult_fire.png" },
];
preload.loadManifest(manifest);
stage = new Stage(canvas); <<<--------
}
function prepareGame() {
bgImage = preload.getResult("screenImage").result;
bgBitmap = new Bitmap(bgImage);
bgBitmap.scaleX = SCALE_X;
bgBitmap.scaleY = SCALE_Y;
stage.addChild(bgBitmap);
stage.update();
}
function gameLoop() {
}
function update() {
}
function draw() {
}
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
// TODO: This application has been newly launched. Initialize
// your application here.
} else {
// TODO: This application has been reactivated from suspension.
// Restore application state here.
}
args.setPromise(WinJS.UI.processAll());
}
};
app.oncheckpoint = function (args) {
// TODO: This application is about to be suspended. Save any state
// that needs to persist across suspensions here. You might use the
// WinJS.Application.sessionState object, which is automatically
// saved and restored across suspension. If you need to complete an
// asynchronous operation before your application is suspended, call
// args.setPromise().
};
document.addEventListener("DOMContentLoaded", initialize, false);
app.start();
})();
But When I'm trying to run the project, I get and error saying "0x800a1391 - JavaScript runtime error: 'Stage' is undefined", in the marked place in my code.
What I did wrong?
If you are using a newer version of EaselJS (3.1 is the current version), some things need to change. The most common is that the EaselJS and PreloadJS objects are now wrapped in the createjs namespace. So the line from the tutorial:
stage = new Stage(canvas);
becomes
stage = new createjs.Stage(canvas);
and the line
bgBitmap = new Bitmap(bgImage);
becomes
bgBitmap = new createjs.Bitmap(bgImage);
I hope that Stage class is defined in your application, that why you getting error on line stage = new Stage(canvas);
please have cross check whether "Stage" class has been defined in any of your JS files(which is included in HTML)
that may be the problem !!!!
Thanks.