0

In my program I am drawing an image the canvas multiple times. My code looks something lik this:

<img id="image1" src="image1.png" width="200" height="100" hidden ="hidden">
<script type ="text/javascript">
        var canvas = document.getElementById("myCanvas");
        var ctx = canvas.getContext('2d');
        ctx.drawImage(image1, 50, 50, 200, 100);
        ctx.drawImage(image1, 100, 100, 200, 100);
<script/>

My questions is, is it possible to delete just one instance of this image? For instance just delete the image drawn at 100,100 and leave the one at 50,50?

1 Answers1

1

The moment you draw something to a canvas it stops being an independent object and becomes a bunch of pixels on a canvas. The information that these pixels together form a larger object is lost. You could remove it by using context.clearRect, but that will also erase anything else which is drawn on the same area, so it won't do what you want when the image overlaps with other content.

I would recommend you to clear the whole canvas and draw the whole scene again without the image.

Another option is to use multiple canvas'es as layers by placing them on top of each other using CSS positioning. That way any transparent pixels on the top canvas will show the content of the canvas below. This allows you to erase parts of one canvas without affecting the content of the canvas above or below it.

Philipp
  • 67,764
  • 9
  • 118
  • 153