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.
Related
After trying to run some p5.js code in Visual Studio Code, I came upon this error. My HTML Code is below, and I copied and pasted it straight from the P5 editor:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/addons/p5.sound.min.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
<meta charset="utf-8" />
</head>
<body>
<script src="sketch.js"></script>
</body>
</html>
My javascript code is below, and when running in p5, no errors come up:
var numOfFood;
var foodList;
var numOfSlimes;
var slimesList;
function setup() {
createCanvas(400, 400);
numOfFood = prompt("Enter the amount of food that should be spawned: ");
numOfSlimes = prompt("Enter the amount of slimes to be spawned: ");
foodList = [];
slimesList = [];
background(220);
rect(25, 25, width - 50, height - 50);
spawnFood(numOfFood);
initializeSlimes(numOfSlimes);
}
// SLIME
Slime = function (x, y) {
this.x = x;
this.y = y;
}
Slime.prototype.draw = function () {
ellipse(this.x, this.y, 12, 12);
}
Slime.prototype.assignFood = function (index) {
this.food = foodList[index];
this.foodIndex = index;
}
// SLIME
// HAWK
Hawk = function (x, y) {
Slime.call(this, x, y);
this.type = "HAWK";
}
Hawk.prototype = Object.create(Slime.prototype);
//HAWK
// DOVE
Dove = function (x, y) {
Slime.call(this, x, y);
this.type = "DOVE";
}
Dove.prototype = Object.create(Slime.prototype);
// DOVE
// FOOD
Food = function (x, y) {
this.x = x;
this.y = y;
}
Food.prototype.draw = function () {
ellipse(this.x, this.y, 10, 10);
}
Food.prototype.assignSlime = function (firstSlime = null, secondSlime = null) {
this.firstSlime = firstSlime;
this.secondSlime = secondSlime;
}
// FOOD
spawnFood = function(food) {
fill(229, 246, 88);
var factors = []
var differences = []
for (let i = 1; i < food; i++) {
var value = food/i;
if (value != Math.floor(value)) {
continue;
}
factors.push([value, i]);
differences.push(abs(value - i));
}
var currentMinIndex = 0;
for (let i = 0; i < differences.length; i++) {
if (differences[i] < differences[currentMinIndex]) {
currentMinIndex = i;
}
}
for (let x = 50; x < 350; x += 300/factors[currentMinIndex][0]) {
for (let y = 50; y < 350; y += 300/factors[currentMinIndex][1]) {
var myFood = new Food(x, y);
foodList.push(myFood);
myFood.draw();
}
}
}
initializeSlimes = function (slimes) {
var tempx = 0;
var tempy = 0;
fill(67, 163, 235);
for (let i = 25; i < 375; i+= 375/(slimes / 4)) {
let mySlime = new Slime(i, 12.5); mySlime.draw(); slimesList.push(mySlime);
}
for (let i = 25; i < 375; i+= 375/(slimes / 4)) {
let mySlime = new Slime(i, 387.5); mySlime.draw(); slimesList.push(mySlime);
}
for (let i = 25; i < 375; i+= 375/(slimes / 4)) {
let mySlime = new Slime(12.5, i); mySlime.draw(); slimesList.push(mySlime);
}
for (let i = 25; i < 375; i+= 375/(slimes / 4)) {
let mySlime = new Slime(387.5, i); mySlime.draw(); slimesList.push(mySlime);
}
}
However, when I try to run this in VSCode, chrome opens to try and run the file, but then the window switches back to VSCode, and it shows me:
My error code (I don't have enough rep to embed a picture yet)
If anybody knew how to fix this, I would be extremely grateful. Is this a problem in my code, or is this a problem with the p5 library?
Could you show where the error appears in your javascript file rather than in the p5.js library itself?
Otherwise, I don't even see a call to Array.forEach() in your code snippit, did you make sure to paste all of the code you're running? Or since your p5.js file isn't even being loaded in your index.html, are you trying to run the p5.js file itself? That won't work, make sure you're running your index.html file.
I tried running your index.html using a copy of p5.js in the source folder and copied all of your code into a sketch.js file, and I was able to run it through VSCode. Let me know if this helps at all or if you have any other information that could help with fixing your problem!
I have been trying to add some html and javascript to my website so users can draw some shapes. I found a really good sample to work from on JS Fiddle. When I run the code on JSFiddle, it works perfectly, but when I ran it myself on my browser (I tried Edge, Firefox, and Chrome) it did not work.
When I ran it myself, I included all the scripts and css into one html file because thats the only way to add it to my Wix website. The scripts (local javascript, and external cdn libraries) where together in the body section of html. All the tutorials I found make it seem like it's OK to use the CDN libraries. I'm positive my issue has something to do with the connection to the CDN libraries, so how would I fix it?
Here is code:
var roof = null;
var roofPoints = [];
var lines = [];
var lineCounter = 0;
var drawingObject = {};
drawingObject.type = "";
drawingObject.background = "";
drawingObject.border = "";
function Point(x, y) {
this.x = x;
this.y = y;
}
$("#poly").click(function () {
if (drawingObject.type == "roof") {
drawingObject.type = "";
lines.forEach(function(value, index, ar){
canvas.remove(value);
});
//canvas.remove(lines[lineCounter - 1]);
roof = makeRoof(roofPoints);
canvas.add(roof);
canvas.renderAll();
} else {
drawingObject.type = "roof"; // roof type
}
});
// canvas Drawing
var canvas = new fabric.Canvas('canvas-tools');
var x = 0;
var y = 0;
fabric.util.addListener(window,'dblclick', function(){
drawingObject.type = "";
lines.forEach(function(value, index, ar){
canvas.remove(value);
});
//canvas.remove(lines[lineCounter - 1]);
roof = makeRoof(roofPoints);
canvas.add(roof);
canvas.renderAll();
console.log("double click");
//clear arrays
roofPoints = [];
lines = [];
lineCounter = 0;
});
canvas.on('mouse:down', function (options) {
if (drawingObject.type == "roof") {
canvas.selection = false;
setStartingPoint(options); // set x,y
roofPoints.push(new Point(x, y));
var points = [x, y, x, y];
lines.push(new fabric.Line(points, {
strokeWidth: 3,
selectable: false,
stroke: 'red'
}).setOriginX(x).setOriginY(y));
canvas.add(lines[lineCounter]);
lineCounter++;
canvas.on('mouse:up', function (options) {
canvas.selection = true;
});
}
});
canvas.on('mouse:move', function (options) {
if (lines[0] !== null && lines[0] !== undefined && drawingObject.type == "roof") {
setStartingPoint(options);
lines[lineCounter - 1].set({
x2: x,
y2: y
});
canvas.renderAll();
}
});
function setStartingPoint(options) {
var offset = $('#canvas-tools').offset();
x = options.e.pageX - offset.left;
y = options.e.pageY - offset.top;
}
function makeRoof(roofPoints) {
var left = findLeftPaddingForRoof(roofPoints);
var top = findTopPaddingForRoof(roofPoints);
roofPoints.push(new Point(roofPoints[0].x,roofPoints[0].y))
var roof = new fabric.Polyline(roofPoints, {
fill: 'rgba(0,0,0,0)',
stroke:'#58c'
});
roof.set({
left: left,
top: top,
});
return roof;
}
function findTopPaddingForRoof(roofPoints) {
var result = 999999;
for (var f = 0; f < lineCounter; f++) {
if (roofPoints[f].y < result) {
result = roofPoints[f].y;
}
}
return Math.abs(result);
}
function findLeftPaddingForRoof(roofPoints) {
var result = 999999;
for (var i = 0; i < lineCounter; i++) {
if (roofPoints[i].x < result) {
result = roofPoints[i].x;
}
}
return Math.abs(result);
}
.canvas {
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.4.0/fabric.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<button id="poly" title="Draw Polygon" ">Draw Polygon </button>
<label style="color:blue"><b>Press double click to close shape and stop</b></label>
<canvas id="canvas-tools" class="canvas" width="500" height="500"></canvas>
EDIT
So, in the html file I put everything inside the body tag. The libraries are also included before the javascript. I get the error "Unable to get property 'x' of undefined or null reference" when I double-click to close the shape. I'm positive its because no points are added when I click in the canvas
Wix does not allow using Cloudflare. The following link has more detail.
https://support.wix.com/en/article/request-cloudflare-support
Wix has some limited API to work with HTML elements
https://support.wix.com/en/article/corvid-working-with-the-html-element
if you want to run it on a separate page (not on wix) and scripts are loaded try to wrap your javascript code in :
<script>
$(function() {
//your code here
var roof = null;
var roofPoints = [];
var lines = [];
var lineCounter = 0;
var drawingObject = {};
...
...
});
</script>
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.
Ok, so me and my friends are trying to make a game with html and js. I'm the one that has to build the foundation for the program to display the blocks used on the map. For some reason though, it doesn't want to draw my images on the canvas at all. I need to display a 24x32 array of 32x32 pixel blocks whose images I need to be able to change. I've looked online, and everywhere it says to use the function drawImage() but my program doesn't see that that belongs to the canvas under the 2d context. Here is my code:
index.html:
<html lang="en">
<head>
</head>
<body>
<div class="canvas">
<canvas id="canvas" height="768" width="1024" style="border:1px solid black">
Your browser does not support canvas element.
</canvas>
<script type="text/javascript" src="Main.js"></script>
<script type="text/javascript" src="World Loader.js"></script>
</div>
</body>
</html>
Main.js:
var c = document.getElementById('canvas');
var ctx = c.getContext('2d');
ctx.font = "20px Arial";
var FPS = 60;
var Mode = 0;
function displayTick(){
Map.DisplayChunk(0,0);
}
function gameTick(){
}
Chunk.LoadNew();
window.setInterval(displayTick, 1000 / FPS);
window.setInterval(gameTick, 600);
and World_Loader.js:
var Block={
WalkThrough:true,
SeeThrough:true,
Interactable:false,
Occupied:false,
Sprite:Image,
Type:"",
X:0,
Y:0
};
var Chunk={
matrix:Block[32][24],
background:Image,
display:function(xindex, yindex){
ctx.drawImage(Background,0,0);
x=xindex;
y=yindex;
for(y=0; y<24; Y++){
for(x=0; x<32; x++){
ctx.drawImage(matrix[X][Y].sprite,X*32,Y*32);
};
};
},
loadNew:function(){
for(Y=0; Y<24; Y++){
for(X=0; X<32; X++){
block=new Block;
block.Sprite.src="test.png";
this.matrix[X][Y]=block;
};
};
}
};
var World={
matrix:Chunk[5][5],
indexX:0,
indexY:0
};
I'm still new to js and trying to teach myself so there's probably tons of errors and stuff. But can anyone see how it doesn't want to draw on the canvas?
There is some problem with your script(sintax errors, scope trouble and so on), you should start with something more simple, I suggest you to start to read this online book.
Anyway below you can see a simple script to fill and display a little grid of images on a canvas.
var Map = (function () {
var options = arguments[0] || {};
var _grid = [];
var _rNum = options.rowuUm || 10;
var _cNum = options.colNum || 10;
var _block = function (x, y) {
this.img = document.getElementById('on');
this.X = x;
this.Y = y;
};
return {
init: function () {
for (var i = 0; i < _rNum; i++) {
_grid[i] = [];
for (var j = 0; j < _cNum; j++) {
_grid[i][j] = new _block(i, j);
}
}
},
paint: function (canvasId) {
var cnv = document.getElementById(canvasId);
var ctx = cnv.getContext('2d');
var img = new Image();
img.src = 'on.jpg';
img.onload = function () {
for (var i = 0; i < _rNum; i++) {
for (var j = 0; j < _cNum; j++) {
ctx.drawImage(img, i * 32, j * 32);
}
}
};
},
}
})();
Map.init();
Map.paint('canvas');
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.