javascripthtmlhtml5-canvashtml5-animation

copy non transparent pixels only to HTML5 canvas


I am writing a colouring game for small children, where I have a black and white image shown on a canvas initially, and as the user moves the drawing tool (mouse) over the canvas, the black and white surface gets over-painted with the colour information from the corresponding coloured image.

In particular, on every mouse move I need to copy a circular area from the coloured image to my canvas. The edge of the circle should be a little blurry to better immitate the qualities of a real drawing tool.

The question is how to accomplish this?

One way I see is to use a clipping region, but this approach does not let me have blurry edges. Or does it?

So I was thinking about using an alpha mask to do that and copy only pixels that correspond to the pixels in the mask that have non zero alpha. Is it feasible?


Solution

  • My suggestion is to have your drawable canvas in front of the coloured image you wish to reveal. (You could use your coloured image as a CSS background image for the canvas.)

    Initially have the canvas containing the black and white image with 100% opacity. Then, when you draw, actually erase the contents of the canvas to show the image behind.

    Like this:

    var pos_x, pos_y, circle_radius;  // initialise these appropriately
    
    context.globalCompositeOperation = 'destination-out';
    context.fillStyle = "rgba(0,0,0, 1.0)";
    
    // And "draw" a circle (actually erase it to reveal the background image)
    context.beginPath();
    context.arc(pos_x, pos_y, circle_radius, 0, Math.PI*2);
    context.fill();