Can't create text in easeljs - javascript

currelty working on a small matching puzzle game. Currently it displays text for the time remaining and the number of tiles that have been macthes. I'm trying to create on for best completion time as well (How fast the person finishes the game) however have been running into a lot of problems. for two variables that I created "txt" and "matchesFoundText" when I type them the autocomplete box will popup and ".text" is displayed as one of the options so i would get something like "txt.text. however I'm not getting that option at all for "bestTimeTxt" and I have no idea as to why this is happening. I did all three variables the same way so I'm at a loss as to why Text is not available to select from for "bestTimeTxt". Here is my entire script.
<!DOCTYPE html>
<html>
<head>
<title>Recipe: Drawing a square</title>
<script src="easel.js"></script>
<script type="text/javascript">
var canvas;
var stage;
var squareSide = 70;
var squareOutline = 5;
var max_rgb_color_value = 255;
var gray = Graphics.getRGB(20, 20, 20);
var placementArray = [];
var tileClicked;
var timeAllowable;
var totalMatchesPossible;
var matchesFound;
var txt;
var bestTime;
var bestTimeTxt;
var matchesFoundText;
var squares;
function init() {
var rows = 5;
var columns = 6;
var squarePadding = 10;
canvas = document.getElementById('myCanvas');
stage = new Stage(canvas);
var numberOfTiles = rows*columns;
matchesFound = 0;
timeAllowable = 5;
bestTime = 0;
txt = new Text(timeAllowable, "30px Monospace", "#000");
txt.textBaseline = "top"; // draw text relative to the top of the em box.
txt.x = 500;
txt.y = 0;
bestTimeTxt = new Text(bestTime, "30px Monospace", "#000");
bestTimeTxt.textBaseLine = "top";
bestTimeTxt.x = 500;
bestTimeTxt.y = 80;
stage.addChild(txt);
stage.addChild(bestTimeTxt);
squares = [];
totalMatchesPossible = numberOfTiles/2;
Ticker.init();
Ticker.addListener(window);
Ticker.setPaused(false);
matchesFoundText = new Text("Pairs Found: "+matchesFound+"/"+totalMatchesPossible, "30px Monospace", "#000");
matchesFoundText.textBaseline = "top"; // draw text relative to the top of the em box.
matchesFoundText.x = 500;
matchesFoundText.y = 40;
stage.addChild(matchesFoundText);
setPlacementArray(numberOfTiles);
for(var i=0;i<numberOfTiles;i++){
var placement = getRandomPlacement(placementArray);
if (i % 2 === 0){
var color = randomColor();
}
var square = drawSquare(gray);
square.color = color;
square.x = (squareSide+squarePadding) * (placement % columns);
square.y = (squareSide+squarePadding) * Math.floor(placement / columns);
squares.push(square);
stage.addChild(square);
square.cache(0, 0, squareSide + squarePadding, squareSide + squarePadding);
square.onPress = handleOnPress;
stage.update();
};
}
function drawSquare(color) {
var shape = new Shape();
var graphics = shape.graphics;
graphics.setStrokeStyle(squareOutline);
graphics.beginStroke(gray);
graphics.beginFill(color);
graphics.rect(squareOutline, squareOutline, squareSide, squareSide);
return shape;
}
function randomColor(){
var color = Math.floor(Math.random()*255);
var color2 = Math.floor(Math.random()*255);
var color3 = Math.floor(Math.random()*255);
return Graphics.getRGB(color, color2, color3)
}
function setPlacementArray(numberOfTiles){
for(var i = 0;i< numberOfTiles;i++){
placementArray.push(i);
}
}
function getRandomPlacement(placementArray){
randomNumber = Math.floor(Math.random()*placementArray.length);
return placementArray.splice(randomNumber, 1)[0];
}
function handleOnPress(event){
var tile = event.target;
tile.graphics.beginFill(tile.color).rect(squareOutline, squareOutline, squareSide, squareSide);
if(!!tileClicked === false || tileClicked === tile){
tileClicked = tile;
tileClicked.updateCache("source-overlay");
}else{
if(tileClicked.color === tile.color && tileClicked !== tile){
tileClicked.visible = false;
tile.visible = false;
matchesFound++;
matchesFoundText.text = "Pairs Found: "+matchesFound+"/"+totalMatchesPossible;
if (matchesFound===totalMatchesPossible){
gameOver(true);
}
}else{
tileClicked.graphics.beginFill(gray).rect(squareOutline, squareOutline, squareSide, squareSide);
}
tileClicked.updateCache("source-overlay");
tile.updateCache("source-overlay");
tileClicked = tile;
}
stage.update();
}
function tick() {
secondsLeft = Math.floor((timeAllowable-Ticker.getTime()/1000));
txt.text = secondsLeft;
;
if (secondsLeft <= 0){
gameOver(false);
}
stage.update();
}
function gameOver(win){
Ticker.setPaused(true);
for(var i=0;i<squares.length;i++){
squares[i].graphics.beginFill(squares[i].color).rect(5, 5, 70, 70);
squares[i].onPress = null;
if (win === false){
squares[i].uncache();
}
}
var replayParagraph = document.getElementById("replay");
replayParagraph.innerHTML = "<a href='#' onClick='history.go(0);'>Play Again?</a>";
if (win === true){
matchesFoundText.text = "You win!"
}else{
txt.text = secondsLeft + "... Game Over";
}
}
function replay(){
init();
}
</script>
</head>
<body onload="init()">
<header id="header">
<p id="replay"></p>
</header>
<canvas id="myCanvas" width="960" height="400"></canvas>
</body>
</html>

Okay so apparently the reason why I was having issues is because the x and y positions of the bestTimeTxt variable was causing it to be obscured by the position of everything else.

Related

Canvas: Drag and Drop Images

so I am relatively new to javascript. As a school project, we have to code a game with HTML, CSS, and Javascript.
So I want to make a cheap recreate of the game Sort or 'Splode' from New Super Mario Bros Ds.
I already programmed the random spawning of the bombs and animated the movement of the bombs. If they are too long in the middle sector (where they spawn) the explode.
But I didn't program the explosion yet. I want to program the drag and drop first. I just want to drag and drop a bomb. As simple as that, the rest I could do myself I guess.
I searched for a tutorial and found this webpage: https://html5.litten.com/how-to-drag-and-drop-on-an-html5-canvas/
I sort of recreated this in my game, but it is not working...
Sorry for my bad code. Could someone please explain to me how to do that?
Best,
Sebastian
enter image description here
<!DOCTYPE html>
<html>
<head>
<title>BOMB-Sorter</title>
<style>
canvas {
background-color:#fff;
border:7px solid #000;
border-radius: 5px;
display: inline;
background-image: url("img/background.jpg");
background-size: cover;
}
body{
display: flex;
justify-content: center;
align-items: center;
}
</style>
<script>
class GraphObj {
constructor(x, y, w, h, c, x_vel, y_vel, t, d) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.c = c;
this.x_vel = x_vel;
this.y_vel = y_vel;
this.t = t;
this.d = d;
}
info() {
return "\ngraphical object: x="+this.x + ", y="+this.y+", w="+this.w+", h="+this.h+", h="+this.c;
}
}
// Declaration of Lists
var bList = null; // List of Bombs
var xlist = null;
var ylist = null;
var ref_time=0; // Reference Time
var lives = 10;
var score = 0;
var dragok = false;
var c = document.getElementById("myCanvas");
function drawGrid(ele,ctx){ // declaration of a new function
ctx.globalAlpha = 0.5;
ctx.fillStyle = "#ff9999";
ctx.fillRect(0,0,ele.width/3,ele.height)
ctx.fillStyle = "#60615a";
ctx.fillRect(2* (ele.width/3),0,ele.width/3,ele.height)
ctx.globalAlpha = 1;
ctx.setLineDash([25, 15]);
ctx.moveTo(ele.width/3 +1,0);
ctx.lineTo(ele.width/3 +1, ele.height);
ctx.moveTo(2*(ele.width/3 -1),0);
ctx.lineTo(2*(ele.width/3 - 1), ele.height);
ctx.lineWidth = 10;
ctx.strokeStyle = "#f5f242";
ctx.stroke();
}
function drawAll()
{
var ele = document.getElementById("myCanvas");
var ctx = ele.getContext("2d");
ele.width = ele.width; // clear everything!
drawGrid(ele,ctx); // call the function ...
var bombb = document.getElementById("bombb");
var bombr = document.getElementById("bombr");
var bombr_step = document.getElementById("bombr_step");
var bombb_step = document.getElementById("bombb_step");
var bombw = document.getElementById("bombw");
// draw bombs
for (var i=0; i<bList.length; i++)
{
var o = bList[i];
if(o.c == 0 && o.t != 8 && o.t != 10 ){
ctx.drawImage(bombr, o.x,o.y,o.w,o.h);
draggable: true;
}
if(o.c == 1 && o.t != 8 && o.t != 10 ){
ctx.drawImage(bombb, o.x,o.y,o.w,o.h);
draggable: true;
}
if(o.c == 2 && o.t != 8 && o.t != 10 ){
ctx.drawImage(bombr_step, o.x,o.y,o.w,o.h);
draggable: true;
}
if(o.c == 3 && o.t != 8 && o.t != 10 ){
ctx.drawImage(bombb_step, o.x,o.y,o.w,o.h);
draggable: true;
}
if(o.t == 10 || o.t == 8){
ctx.drawImage(bombw, o.x,o.y,o.w,o.h);
draggable: true;
}
}
// draw lives
ctx.font = "normal small-caps 70px Minecraft";
ctx.fillStyle = "red";
ctx.fillText(+lives, ele.width - 105, 70);
// draw score
ctx.font = "normal small-caps 70px Minecraft";
ctx.fillStyle = "black";
ctx.fillText(+score, 20, 70);
}
function positionCheck(i, ele){
if(bList[i].x < ele.width/3){
bList[i].x_vel = bList[i].x_vel * (-1);
}
else if(bList[i].x > 2*(ele.width/3) -64){
bList[i].x_vel = bList[i].x_vel * (-1);
}
else if(bList[i].y < 0){
bList[i].y_vel = bList[i].y_vel * (-1);
}
else if(bList[i].y > ele.height -64){
bList[i].y_vel = bList[i].y_vel * (-1);
}
}
function animateStep(){
for(var i = 0;i < bList.length; i++){
if(bList[i].c == 0){
bList[i].c = 2;
bList[i].t++;
}
else if(bList[i].c == 1){
bList[i].c = 3;
bList[i].t++;
}
else if(bList[i].c == 2){
bList[i].c = 0;
}
else if(bList[i].c == 3){
bList[i].c = 1;
}
else if(bList[i].t == 8){
bList[i].c = 4;
}
else if(bList[i].t == 10){
bList[i].c = 4;
}
}
}
function functimer(){
var ele = document.getElementById("myCanvas");
// create new bomb every s
if (Date.now() - ref_time >= 1000)
{
// random number between 0 and ele.width
var pos_x = Math.floor(Math.random() * (ele.width/3 - 64)) + (ele.width/3 +1);
//random height
var pos_y = Math.floor(Math.random() * (ele.height - 70) -1);
//random color
var color = Math.round(Math.random());
//random x velocity
var x_vel = Math.ceil(Math.random() * 2) * (Math.round(Math.random()) ? 1 : -1);
//random y velocity
var y_vel = Math.ceil(Math.random() * 2) * (Math.round(Math.random()) ? 1 : -1);
var t = 0;
var o = new GraphObj(pos_x,pos_y,64,64, color, x_vel, y_vel, t); // create new bomb
bList.push(o);
animateStep();
ref_time = Date.now();
}
var xlist = null;
xlist = new Array();
var ylist = null;
ylist = new Array();
// move bombs
for (var i=0; i<bList.length; i++)
{
bList[i].y += bList[i].y_vel;
bList[i].x += bList[i].x_vel;
positionCheck(i, ele);
}
drawAll();
requestAnimationFrame(functimer); // draw everything BEFORE screen update
}
function myMove(i,e){
if(dragok == true){
bList[i].x = e.pageX - c.offsetLeft;
bList[i].y = e.pageY - c.offsetTop;
}
}
function myDown(e){
for(var i = 0; i < bList.lenght; i++){
if(e.pageX < bList[i].x + 64 + c.offsetLeft && e.pageX > bList[i].x + c.offsetLeft && e.pageY < bList[i].y + 64 + c.offsetTop && e.pageY > bList[i].y + c.offsetTop){
bList[i].x = e.pageX - c.offsetLeft;
bList[i].y = e.pageY - c.offsetTop;
bList[i].x_vele = 0;
bList[i].y_vel = 0;
dragok = true;
c.onmousemove = myMove(i,e);
}
}
}
function myUp(){
dragok = false;
}
function start() {
// create lists
bList = new Array();
var c = document.getElementById("myCanvas");
c.setAttribute('tabindex','0');
c.focus();
c.onmousedown = myDown;
c.onmouseup = myUp;
var xlist = null;
xlist = new Array();
var ylist = null;
ylist = new Array();
drawAll();
requestAnimationFrame(functimer); // draw everything BEFORE screen update
}
</script>
</head>
<body onload="start()">
<img id="bombb" src="img/bombb.png" alt="x" style="display: none;">
<img id="bombr" src="img/bombr.png" alt="y" style="display: none;">
<img id="bombr_step" src="img/bombr_step1.png" alt="y" style="display: none;">
<img id="bombb_step" src="img/bombb_step.png" alt="y" style="display: none;">
<img id="bombw" src="img/bombw.png" alt="y" style="display: none;">
<div>
<canvas id="myCanvas" width="1000" height="600"></canvas>
</div>
</body>
</html>
This is not a total answer because I do not know exactly what is required when dragging a bomb, but here are a few places to make changes to help further debugging:
the canvas element 'c' is declared in two places so when it comes to be used on mousedown etc it is undefined, the one with more local scope having been set up in the start function. I suggest removing the 'var' before the use of c in the start function so you pick up the one that has global scope.
In general, go through the code seeing where things are defined and if that is in the best position - look at the scope of all variables. The code in this respect is almost OK, for example you understand you cant draw an img on a canvas until it is downloaded, but a few things could do with tidying up.
There is a misspelling of 'length' (lenght) which means a function won't work.
In general use your browser's dev tools console to ensure you do not have anything undeclared or looking like null etc. Such Javascript errors will show there. Also use console.log at strategic points to make sure you understand the flow of the logic. Starting with console.log('at function xxx') at the beginning of the main functions might be useful. You can then see the order in which mousedown/up might happen on a bomb for example.
If you could describe further what should happen when a bomb is dragged that would be useful. Just for completeness here I reiterate what I said in a comment that the bombs are going to be treated like rectangles - so obscuring bombs behind them from the point of view of dragging - that may or may not matter to your application. There is a way round it if it is important, but it's probably better to get the basics sorted out first.

Difficulty implementing handleOnPress function

I am trying to implement the handleOnPress function, the code is provided by the textbook which is confusing because it doesn't seem to be working as expected, in fact it does nothing.
The function is supposed to allow me to click the squares in the memory game, if the squares are the same color both of the chosen squares disappear, if you click on the same square twice the function resets and if you match two that aren't the same the function resets.
It would be really appreciated if anyone can take a look and point out any errors they see, thank you!
<!DOCTYPE html>
<html>
<head>
<title>Recipe: Drawing a square</title>
<script src="easel.js"></script>
<script type="text/javascript">
var canvas;
var stage;
var squareSide = 70;
var squareOutline = 5;
var max_rgb_color_number = 255;
var gray = createjs.Graphics.getRGB(20, 20, 20);
var placementArray = [];
var highlight = createjs.Graphics.getRGB(255, 255, 0);
var tileClicked;
function init() {
var rows = 6;
var columns = 6;
var squarePadding = 10;
canvas = document.getElementById('myCanvas');
stage = new createjs.Stage(canvas);
var numberOfTiles = rows*columns;
setPlacementArray(numberOfTiles);
for(var i=0;i<numberOfTiles;i++){
var placement = getRandomPlacement(placementArray);
if(i % 2 === 0){
var color = randomColor();
}
square = drawSquare(color);
square.color = color;
square.x = (squareSide+squarePadding) * (placement%columns);
square.y = (squareSide+squarePadding) * Math.floor(placement/columns);
stage.addChild(square);
square.onPress = handleOnPress;
stage.update();
}
}
function drawSquare(color) {
var shape = new createjs.Shape();
var graphics = shape.graphics;
graphics.setStrokeStyle(squareOutline);
graphics.beginStroke(gray);
graphics.beginFill(color);
graphics.rect(squareOutline, squareOutline, squareSide, squareSide);
return shape;
}
function randomColor(){
var color = Math.floor(Math.random()*max_rgb_color_number);
var color2 = Math.floor(Math.random()*max_rgb_color_number);
var color3 = Math.floor(Math.random()*max_rgb_color_number);
return createjs.Graphics.getRGB(color, color2, color3);
}
function setPlacementArray(numberOfTiles){
for(var i=0;i<numberOfTiles;i++){
placementArray.push(i);
}
}
function getRandomPlacement(placementArray){
randomNumber = Math.floor(Math.random()*placementArray.length);
return placementArray.splice(randomNumber, 1)[0];
}
function handleOnPress(event){
var tile = event.target;
if(!!tileClicked === false){
tile.graphics.setStrokeStyle(squareOutline).beginStroke(highlight)
.rect(squareOutline, squareOutline, squareSide, squareSide);
tileClicked = tile;
}
else{
if(tileClicked.color === tile.color && tileClicked !== tile){
tileClicked.visible = false;
tile.visible = false;
}
else{
tileClicked.graphics.setStrokeStyle(squareOutline).beginStroke(gray)
.rect(squareOutline, squareOutline, squareSide, squareSide);
}
tileClicked = null;
}
stage.update();
}
</script>
</head>
<body onload="init()">
<canvas id="myCanvas" width="960" height="600"></canvas>
</body>
</html>
The onEvent-style handlers (onClick, onMouseDown, etc) were deprecated and removed a long time ago (Version 0.7.0, September 25, 2013).
Instead, use events, such as
square.addEventListener("mousedown", handleOnPress);
or the shortcut on() method:
square.on("mousedown", handleOnPress);
Note also there is no "press" event. There is a "mousedown" event, as well as "pressmove"/"pressup" events for drag and drop-style events.
Here is a listing of events on all display objects: https://createjs.com/docs/easeljs/classes/DisplayObject.html#event_mousedown
I don't know if this will solve everything, but it should get your click handlers firing.

How to link P5.js setup and draw with html canvas?

I am sure this is a very simple thing to do, but I am stuck here.
Here is the situation:
I have an HTML page with a div and a canvas element(not sure if I need this)
Also I have two javascript files using p5.js with setup and draw funtions where I draw my content on a canvas I create with createCanvas.
The other js file contains an object.
The problem is - I can get the animation to show on the HTML page, but not inside the div and/or canvas.
Image for a clearer picture:
HTML and JS comunication
HTML:
<html>
<head>
<meta charset="utf-8">
<title>Fractals</title>
<script language="javascript" type="text/javascript" src="libs/p5.js"></script>
<script language="javascript" src="libs/p5.dom.js"></script>
<script language="javascript" type="text/javascript" src="sketch.js"></script>
<script language="javascript" type="text/javascript" src="branch.js"></script>
<style>
body {
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<div>
<canvas id="fractal" height="197" width="333" style=" width:333;height:197;"></canvas>
</div>
</body>
</html>
JS sketch:
var tree = [];
var x;
var y;
function setup() {
createCanvas(333,197);
var a = createVector(width / 2, height);
var b = createVector(width / 2, height - 50);
var root = new Branch(a, b);
tree[0] = root;
for (var t = 0; t < 5; t++) {
for (var i = tree.length-1; i >= 0; i--) {
if (!tree[i].finished){
tree.push(tree[i].branchA());
tree.push(tree[i].branchB());
tree.push(tree[i].branchC());
}
tree[i].finished = true;
}
}
}
function draw() {
background(51);
x = mouseX;
y = mouseY;
for (var i = 0; i < tree.length; i++) {
tree[i].show();
tree[i].wind(x, y, tree[i].end.x, tree[i].end.y);
}
}
JS branch object:
function Branch(begin, end) {
this.begin = begin;
this.end = end;
this.finished = false;
this.origx = this.end.x;
this.origy = this.end.y;
this.show = function() {
stroke(255);
line(this.begin.x, this.begin.y, this.end.x, this.end.y);
}
this.branchA = function() {
var dir = p5.Vector.sub(this.end, this.begin);
dir.rotate(19.2);
dir.mult(0.67);
var newEnd = p5.Vector.add(this.end, dir);
var v = new Branch(this.end, newEnd);
return v;
}
this.branchB = function() {
var dir = p5.Vector.sub(this.end, this.begin);
dir.rotate(0);
dir.mult(0.67);
var newEnd = p5.Vector.add(this.end, dir);
var v = new Branch(this.end, newEnd);
return v;
}
this.branchC = function() {
var dir = p5.Vector.sub(this.end, this.begin);
dir.rotate(-19.2);
dir.mult(0.67);
var newEnd = p5.Vector.add(this.end, dir);
var v = new Branch(this.end, newEnd);
return v;
}
this.wind = function(mox,moy,treex,treey) {
var d = dist(mox,moy,treex,treey);
if (d < 20) {
this.end.x += random(-0.3, 0.3);
this.end.y += random(-0.3, 0.3);
}else{
this.end.x = this.origx;
this.end.y = this.origy;
}
}
}
P5 libraries : https://p5js.org/download/
From the docs:
https://github.com/processing/p5.js/wiki/Positioning-your-canvas
// sketch.js
function setup() {
var canvas = createCanvas(100, 100);
// Move the canvas so it's inside our <div id="sketch-holder">.
canvas.parent('sketch-holder');
background(255, 0, 200);
}
Create one instance of canvas with P5, then assigns its parent by dom id.

draw all leaflet tiles on canvas (transform3d)

Good day,
I try to draw all tiles, on cavas using leaflet.js as provider.
But, as it used translate3d transform
1 level - map Pane
2 level - overlay Pane(I also lokking for solution about SVG Pane. I use canVG to convert svg to canvas, but don't understand how to create canvas correctly)
How to draw tiles on canvas?
For example
1 level - transform: translate3d(-247px, 184px, 0px);
This is part of code:
var svgE = $(overlayPane).find('svg');
var xml;
var mapPane = $(".leaflet-map-pane")[0];
var mapTransform = mapPane.style.transform.split(",");
var mapX = parseFloat(mapTransform[0].split("(")[1].replace("px", ""));
var mapY = parseFloat(mapTransform[1].replace("px", ""));
var canvas = document.createElement("canvas");
canvas.className = "screenShotTempCanvas";
canvas.width = map.getSize().x;
canvas.height = map.getSize().y;
var ctx = canvas.getContext('2d');
$(canvas).insertBefore($(".leaflet-zoom-animated"));
if ($("img.leaflet-tile").length !== 0) {
var myTiles = $("img.leaflet-tile");
var tilesLeft = [];
var tilesTop = [];
var tileMethod = [];
for (var i = 0; i < myTiles.length; i++) {
if (myTiles[i].style.left != "") {
tilesLeft.push(parseFloat(myTiles[i].style.left.replace("px", "")));
tilesTop.push(parseFloat(myTiles[i].style.top.replace("px", "")));
tileMethod[i] = "left";
} else if (myTiles[i].style.transform != "") {
var tileTransform = myTiles[i].style.transform.split(",");
tilesLeft[i] = parseFloat(tileTransform[0].split("(")[1].replace("px", ""));
tilesTop[i] = parseFloat(tileTransform[1].replace("px", ""));
myTiles[i].style.transform = "";
tileMethod[i] = "transform";
} else {
tilesLeft[i] = 0;
tilesRight[i] = 0;
tileMethod[i] = "neither";
};
myTiles[i].setAttribute('crossOrigin', 'anonymous');
myTiles[i].style.left = (tilesLeft[i]) + "px";
myTiles[i].style.top = (tilesTop[i]) + "px";
ctx.drawImage(myTiles[i], tilesLeft[i], tilesTop[i])
};
}
setTimeout(function() {
var myImage = canvas.toDataURL("image/jpeg");
var link = document.createElement('a');
link.download = "test.jpeg";
link.href = myImage;
document.body.appendChild(link);
$(link).css("display", "none");
link.click();
document.body.removeChild(link);
console.log(sdfsdfgsdfg)
}, 10000)
Second question how to correctly create canvas for SVG?
if ($(map.getContainer()).find('svg').length !== undefined && $(map.getContainer()).find('svg').length !== 0) {
svgE.each(function() {
L.DomUtil.getPosition(svgE);
xml = new XMLSerializer().serializeToString(this);
canvg(canvas, xml);
$(canvas).insertBefore(this);
$(this).attr('class', 'tempHide').attr("id", "TempSvgToHide").hide();
});
}

WebKit Uncaught Error: INVALID_STATE_ERR: DOM Exception 11

I have this code and in Firefox is working well, but in Chrome I'am getting this error:
"Uncaught Error: INVALID_STATE_ERR: DOM Exception 11" at sprites.js:36
on that line is this code:
context.drawImage(
Context is a global variable in which contains 2d context of canvas. Here is full code:
index.html
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="sprites.js"></script>
<script type="text/javascript" src="game.js"></script>
<script type="text/javascript" src="prototypes.js"></script>
<script type="text/javascript" src="initialize.js"></script>
</head>
<body onload="initialize()">
</body>
</html>
sprites.js
function SpritePrototype(frames, width, height, type)
{
this.frames = frames;
this.type = type;
if (this.frames > 0) {
this.frameArray = new Array(this.frames);
for (var i = 0; i < this.frames; i++) {
this.frameArray[i] = document.createElement("canvas");
}
}
}
function Sprite()
{
this.id = 0;
this.prototype = 0;
this.next = 0;
this.prev = 0;
this.x = 0;
this.y = 0;
this.startFrame = 0;
this.currentFrame = 0;
}
Sprite.prototype.draw = function()
{
if (this.prototype == 0) {
return;
}
if (context.drawImage) {
if (this.prototype.frames > 0) {
context.drawImage(
this.prototype.frameArray[this.currentFrame],
Math.round(this.x),
Math.round(this.y)
);
}
}
}
game.js
function Game()
{
this.frameLength = 1000/30;
this.startTime = 0;
this.sprites = 0;
}
Game.prototype.resetTime = function()
{
var d = new Date();
this.startTime = d.getTime();
delete d;
}
Game.prototype.addSprite = function(prototype)
{
currentId++;
if (this.sprites == 0) { // if creating the first sprite
this.sprites = new Sprite();
this.sprites.id = currentId;
this.sprites.prototype = prototype;
} else {
var tempSprite = this.sprites; // temporarily store the first sprite
while (tempSprite.next != 0) { // while not the last sprite
tempSprite = tempSprite.next; // shift to next one
}
tempSprite.next = new Sprite(); // next sprite to the last sprite
tempSprite.next.id = currentId;
tempSprite.next.prototype = prototype;
tempSprite.next.next = 0; // the last sprite, or the last one in the space
tempSprite.next.prev = tempSprite;
}
}
Game.prototype.loop = function()
{
var tempSprite;
var currentTime;
var globalFrame;
var oldFrame;
var d = new Date();
currentTime = d.getTime();
delete d;
globalFrame = Math.floor((currentTime - this.startTime)/this.frameLength);
canvas.width = canvas.width;
tempSprite = this.sprites;
while (tempSprite != 0) {
if (tempSprite.frames > 0) {
oldFrame = tempSprite.currentFrame;
tempSprite.currentFrame = globalFrame;
}
tempSprite.draw();
tempSprite = tempSprite.next;
}
}
prototypes.js
var protoPlayer;
function createPrototypes()
{
var tempCtx;
var i;
protoPlayer = new SpritePrototype(5, 20, 30, "player");
for (i = 0; i < protoPlayer.frames; i++) {
protoPlayer.frameArray[i].width = protoPlayer.width;
protoPlayer.frameArray[i].height = protoPlayer.height;
tempCtx = protoPlayer.frameArray[i].getContext("2d");
tempCtx.strokeStyle = "rgb("+ i * 50 +", 0, 0)";
tempCtx.beginPath();
tempCtx.moveTo(0, 0);
tempCtx.lineTo(20, 30);
tempCtx.stroke();
}
}
initialize.js
var game;
var canvas;
var context;
var currentId;
function initialize()
{
canvas = document.createElement("canvas");
canvas.width = 640;
canvas.height = 480;
canvas.setAttribute("style", "background:#060606;");
document.body.appendChild(canvas);
context = canvas.getContext("2d");
createPrototypes();
currentId = 0;
game = new Game();
game.addSprite(protoPlayer);
game.loop();
}
Seems to me that that error is happening because you are calling drawImage with a HTMLCanvasObject who's height or width is zero. From the latest canvas 2d context spec:
If the image argument is an
HTMLCanvasElement object with either a
horizontal dimension or a vertical
dimension equal to zero, then the
implementation must raise an
INVALID_STATE_ERR exception.
http://dev.w3.org/html5/2dcontext/#images
Hope this helps.
Some time this error also occurred when we try to do document.getElemetnById('xx').innerHtml='htmlcode'; in this time 'htmlcode' should be proper formatted mean should use proper closing tags.

Categories

Resources