views:

309

answers:

2

Hi, there's an example, which loads 2 images:

    canvas = document.getElementById("canvas");
    ctx = canvas.getContext("2d");

    var img1 = new Image();
    img.src = "/path/to/image/img1.png";
    img.onload = function() {
      ctx.drawImage(img, 0, 0);
    };

    var img2 = new Image();
    img2.src = "/path/to/image/img2.png";
    img2.onload = function() {
      ctx.drawImage(img2, 100, 100);
    };

I need to remove(replace) img2 from canvas. What is the best way to do it?

+2  A: 
Pointy
if I got right, there's no way to say "remove that img object from canvas". You should rewrite it, right?
Alex Ivasyuv
Yes - you can't "take pixels away", as far as I know.
Pointy
+3  A: 

I think maybe you misunderstand what a Canvas is.

A canvas is essentially a 2 dimensional grid of pixels along an 'X' axis and a 'Y' axis. You use the API to draw pixels onto that canvas, so when you draw an image you're basically drawing the pixels that make up that image onto your canvas. The reason there is NO method that lets you just remove an image, is because the Canvas doesn't know there's an image there in the first place, it just see pixels.

This is unlike the HTML DOM (Document Object Model) where everything is a HTML element, or an actual 'thing' you can interact with, hook-up script events to etc. this isn't the case with stuff you draw onto a Canvas. When draw a 'thing' onto a Canvas, that thing doesn't become something you can target or hook into, it's just pixels. To get a 'thing' you need to represent your 'thing' in some way such as a JavaScript object, and maintain a collection of these JS objects somewhere. This how how Canvas games work. This lack of a DOM-like structure for Canvas makes rendering very fast, but can be a pain for implementing UI elements that you can easily hook into and interact with, remove etc. For that you might want to try SVG.

To answer your question, simply paint a rectangle onto your Canvas that covers up your image by using the same X/Y coords and dimensions you used for your original image, or try Pointy's solution. 'Cover-up' is probably the wrong terminology, since you're actually replacing the pixels (there are no layers in Canvas).

Sunday Ironfoot
Thanks for explain!
Alex Ivasyuv