Witam serdecznie
Staram się ruszyć zielony kwadrat na canvasie jednak js nie zapamiętuje utworzonych obiektów, jaka jest metoda aby temu zaradzić?
/**
* Klasa prezentująca blok
*
*/
function Block(canvas, x, y, height, width)
{
this.height = height;
this.width = width;
Object.call(this, canvas, x, y);
}
Block.prototype = new Object();
Block.prototype.constructor = Block;
Block.prototype.toString = function()
{
return "[Block]";
}
Block.prototype.draw = function()
{
this.canvas.context.beginPath();
this.canvas.context.rect(this.x, this.y, this.height, this.width);
this.canvas.context.fillStyle = 'green';
this.canvas.context.fill();
this.canvas.context.lineWidth = 1;
this.canvas.context.strokeStyle = 'black';
this.canvas.context.stroke();
}
Block.prototype.doKeyDown = function(evt)
{
/*this.canvas.clear();*/
switch (evt.keyCode)
{
case 87:
this.y -= 20;
break;
case 68:
this.y += 20;
break;
case 83:
this.x -= 20;
break;
case 65:
this.x += 20;
break;
}
this.draw();
}
/**
* Klasa prezentująca obiekt
*
*/
function Object(canvas, x, y)
{
this.canvas = canvas;
this.x = x;
this.y = y;
}
Object.prototype.toString = function()
{
return "[Object]";
}
/**
* Klasa Canvas
*
*/
function Canvas()
{
this.canvas = document.getElementById('myCanvas');
this.context = this.canvas.getContext('2d');
}
Canvas.prototype.toString = function()
{
return "[Canvas]";
}
Canvas.prototype.clear = function()
{
this.context.clearRect(0, 0, canvas.width, canvas.height);
}
Canvas.prototype.drawScreen = function()
{
for(var i = 0; i < 10; i++)
{
for(var j = 0; j < 10; j++)
{
this.context.beginPath();
this.context.rect(10 + i*20 + i * 5, 10 + j*20 + j * 5, 20, 20);
this.context.fillStyle = 'white';
this.context.fill();
this.context.lineWidth = 1;
this.context.strokeStyle = 'gray';
this.context.stroke();
}
}
}
window.onload = function()
{
var canvas = new Canvas();
canvas.drawScreen();
var b = new Block(canvas, 50, 50, 20, 20);
b.draw();
canvas.addEventListener('keydown', b.doKeyDown, true);
};
Z góry dziękują za pomoc