ferics2
ferics2

Reputation: 5432

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();
            }
        } 

Upvotes: 1

Views: 1159

Answers (3)

ferics2
ferics2

Reputation: 5432

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

Upvotes: 1

Jonathan
Jonathan

Reputation: 1507

You can draw the image on one canvas and the to-be-erased mask on another canvas with higher z-index.

Upvotes: 0

Petteri H
Petteri H

Reputation: 12192

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.

Upvotes: 0

Related Questions