Answer the question
In order to leave comments, you need to log in
How to update the position of images on Canvas?
Hello. Wrote a function to assign image positions on the canvas.
app.js (game)
my_Doge = game.addSprite("Doge", "mydoggy", 0, 700, 100, 100);
this.addedSprites.push(spriteObj);
game.setPos(my_Doge, my_Doge.xcoord+=2, my_Doge.ycoord);
GameWindow.prototype.setPos = function(sprite, newX, newY)
{ // Set new sprite position
sprite.xcoord = newX;
sprite.ycoord = newY;
for(var i = 0; i < this.addedSprites.length; i++)
{
if(sprite.id == this.addedSprites[i].id)
{
this.addedSprites[i].xcoord = newX;
this.addedSprites[i].ycoord = newY;
}
}
this.render(sprite, sprite.width, sprite.height, sprite.xcoord, sprite.ycoord);
}
GameWindow.prototype.render = function(sprite, width, height, x, y)
{
ctx = this.ctx;
canvas.width=canvas.width;
ctx.drawImage(sprite, x, y, width, height);
}
game.setPos(my_Doge, my_Doge.xcoord+=2, my_Doge.ycoord);
(so that the dog does not move), you can see. that I added a cat before, but it disappears, and only the dog is updated. this.addedSprites
also drawn to the canvas by loopinggameWindow.prototype.render = function(sprite, width, height, x, y)
{
ctx = this.ctx;
canvas.width=canvas.width;
for(var i = 0; i < this.addedSprites.length; i++)
{
var w = new Image();
w.src = this.addedSprites[i].src;
ctx.drawImage(w, this.addedSprites[i].x,this.addedSprites[i].y,this.addedSprites[i].width,this.addedSprites[i].height);
}
ctx.drawImage(sprite, x, y, width, height);
}
game.setPos(my_Doge, my_Doge.xcoord+=2, my_Doge.ycoord);
game.setPos(my_Cat, my_Cat.xcoord+=2, my_Cat.ycoord);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question