akonsu
akonsu

Reputation: 29586

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?

Upvotes: 0

Views: 934

Answers (3)

andrewmu
andrewmu

Reputation: 14554

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

Upvotes: 2

I would probably use multiple clipping regions with varying alpha (one dab for each) to mimic the effect you are after. Render the low opacity one first (paste using drawImage) and render the rest after that till you reach alpha=1.0.

Upvotes: 1

J. K.
J. K.

Reputation: 8368

Have you considered using radial gradients that go from an opaque color to a fully transparent one?

Here is a demo from Mozilla. The circles are drawn the way you need. - https://developer.mozilla.org/samples/canvas-tutorial/4_10_canvas_radialgradient.html

Upvotes: 0

Related Questions