Reputation: 69
I am showing some images on the canvas using a for-loop in JavaScript. The code is working, but how do I clear / remove the previous images (the ones already drawn earlier in the loop) from the canvas before going to the next iteration. I have tried using clearRect() but it hasn't worked.
HTML Code:
<canvas id="myCanvas" height="720" width="1280" style="border:1px solid #000000;"></canvas>
JavaScript Code:
var canvasupdate = document.getElementById("myCanvas");
ctxupdate = canvasupdate.getContext("2d");
var imageobj = new Array();
for (var d=0;d<calloutImageArray.length;d++)
{
imageobj[d] = new Image();
(function(d)
{
imageobj[d].src = imagePath+"/"+calloutImageArray[d];
imageobj[d].onload = function()
{
ctxupdate.drawImage(imageobj[d], calloutImageArrayX[d], calloutImageArrayY[d],calloutImageArrayW[d], calloutImageArrayH[d]);
};
})(d);
}
Upvotes: 0
Views: 674
Reputation: 1725
What one have to remember is that everything that is drawn on the canvas in one loop is pretty much joined together in 1 image. Even though we can spot the different objects, for the canvas, it's just one big image.
In order to decide what goes on the canvas, you need to handle that in your code and never draw it in the next loop, it's not about erasing things on the canvas but in your code.
Having ctxupdate.clearRect(0, 0, canvasupdate.width, canvasupdate.height);
at the start of your drawing function will make sure the canvas is empty before you start putting things in.
So in this case, you need to remove stuff from calloutImageArray
array or tell the code, in some other way, which indicies of the array it should skip, only then will you be able to exclude it from being painted.
It all depends on how you intend your code to work. What decides if an image should be removed or not?
Upvotes: 1
Reputation: 2046
Canvas is typically similar to a paint space. So you can clear it by using the following code.
context.clearRect(0, 0, canvas.width, canvas.height);
where context corresponds to your ctxupdate and canvas corresponds to your canvasupdate (the canvas element)
Upvotes: 1