0

I've been trying to get a start on creating a game with Javascript, but am currently stumped on how to get the animation going for a simple image. The image I am using is a black square png and when I use setInterval(), it duplicates the image and doesn't remove the image from its previous state. It draws another image at each pixel but doesn't get rid of the last frame so it looks like a black rectangle growing upwards. I want the block to move upwards and delete the last drawn frame. What am I doing wrong?

my js code:

var cvs = document.getElementById("game");
var ctx = cvs.getContext("2d");

var block = new Image();

block.src = "images/Solid_black.png";

var imgCount = 1;

var blockX = 10;
var blockY = 462;

var speed = 5;

window.onload = function() {
    setInterval(draw, 1);
}


function draw() {
    if (--imgCount > 0) { return; }

    console.log(cvs.clientWidth);
    ctx.drawImage(block, blockX, blockY, 50, 50);
    blockY--;
}
draw();

what it looks like

  • 1
    Why should it delete the prior image? You're not clearing the canvas before drawing the next image. – Scott Marcus Dec 26 '19 at 01:09
  • I had just assumed that when using `setInterval()` that it would take care of the animation of having a block move. I don't want to clear the entire canvas because there will be other elements on the canvas later. – tahzabbani Dec 26 '19 at 01:13
  • Does this answer your question? [How to clear the canvas for redrawing](https://stackoverflow.com/questions/2142535/how-to-clear-the-canvas-for-redrawing) – Simon Crane Dec 26 '19 at 01:14

2 Answers2

0

You must clear the canvas at the beginning of every loop:

ctx.clearRect(0, 0, canvas.width, canvas.height);

This is because your object is not technically moving, it is just being redrawn at different places. We wipe the previous drawing to give the impression of dynamic movement. It's a farce!

A.J. Uppal
  • 17,608
  • 6
  • 40
  • 70
0

I honestly don’t know if this is what you’re looking for, but:

The ctx.clearRect(x, y, width,height) function clears a rectangle on the canvas. For example:

ctx.clearRect(0, 0, canvas.width, canvas.height) 

will clear the whole canvas.

Put that before you draw every frame in the draw function. Basically, it clears the canvas first, draw the picture, then keeps repeating to make an animated effect.

sure
  • 83
  • 8