1

Is it possible to use clearRect to delete part of a png image drawn to the canvas using drawImage?

I'm trying something like this and its not working:

<canvas id="canvas"></canvas>
<img id="pngimg" src="" alt="" />

[...]

canvas = document.getElementById("canvas");
pngimg = document.getElementById("pngimg");

[...]

pngimg.src = canvas.toDataURL();
context.drawImage(pngimg, 0, 0, canvas.width, canvas.height);

[...]

Then using clearRect to erase with the mouse. The erase works on the strokes that were added to the canvas using drawLine but not for images using drawImage. It must be clearRect instead of drawing a solid color because the background isn't solid. Is it possible to do this?

2 Answers2

0

Where are you loading the image from?

you can't use canvas.toDataURL() if the image on the canvas originated from a different domain. see here: Why does canvas.toDataURL() throw a security exception?

In a same domain situation this should work:

Original Image: <img id="pngimg" src="http://www.domain.com/image.png" /><br/>

Canvas With Clear:
<canvas width="160" height="80" id="canvas"></canvas><br/>

Altered Image:
<img id="newImg" src="" />

and the script:

canvas = document.getElementById("canvas");
pngimg = document.getElementById("pngimg");
newImg = document.getElementById("newImg");

var context = canvas.getContext("2d");
context.drawImage(pngimg, 0, 0, canvas.width, canvas.height);
context.clearRect(125,0,35,25);

newImg.src = canvas.toDataURL("image/png");
Community
  • 1
  • 1
Variant
  • 17,279
  • 4
  • 40
  • 65
  • I found I just had a typo of sorts and got the image to both draw to the canvas and erase now. Thanks for your reply though, I didn't know that about images hosted on a different domain. My image was on the same domain and generated dynamically from the canvas content. – ArtisticAbode Jul 21 '11 at 23:15
0

As you haven't shared complete code I am not sure, but from the description I doubt that it is the same issue I came across earlier today. Please visit this thread.

On a canvas, difference between drawImage with png vs create a drawing using strokes?

Community
  • 1
  • 1
Diode
  • 24,570
  • 8
  • 40
  • 51