开发者

Use clearRect to erase part of a png image drawn to canvas with drawImage

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开发者_StackOverflow社区");
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?


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");


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?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜