简体   繁体   中英

Erasing a png image drawn by a canvas

I'm working on a html5 app for the ipad. I would like to display an image in the canvas element with a background image underneath. When the user wipes their finger over the image in the canvas it should erase to reveal the background image. Here is the code I am starting with. Right now I am just trying to draw a transparent line to reveal the background image. I will worry about the touch events later. Any ideas?

        function draw() {
            var ctx = document.getElementById('canvas').getContext('2d');
            var img = new Image();
            img.src = 'Lord-of-Bones.png';
            img.onload = function(){
                ctx.drawImage(img,0,0);
                ctx.globalCompositeOperation = "copy";
                ctx.strokeStyle = "rgba(0,0,0,0)";
                ctx.beginPath();
                ctx.moveTo(30,96);
                ctx.lineTo(70,66);
                ctx.lineTo(103,76);
                ctx.lineTo(170,15);
                ctx.stroke();
            }
        } 

This is what ended up working for me.

var imageData = context.getImageData(x,y,50,50);
var data = imageData.data;
for (var i = 0; i < data.length; i+=4) {
    data[i] = 0; //red
    data[i+1] = 0; //green
    data[i+2] = 0; //blue
    data[i+3] = 0; //alpha
}
context.putImageData(imageData, x, y);

I think the composite operation should be something else than copy - maybe destination-out.

https://developer.mozilla.org/samples/canvas-tutorial/6_1_canvas_composite.html

The other way to get such working could be to clear the pixel data directly from context's ImageData.

您可以在一个画布上绘制图像,在另一个具有较高z索引的画布上绘制要擦除的蒙版。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM