简体   繁体   English

仅将非透明像素复制到HTML5画布

[英]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. 因此,我正在考虑使用Alpha蒙版进行此操作,并仅复制与蒙版中具有非零Alpha的像素相对应的像素。 Is it feasible? 可行吗

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.) (您可以将彩色图像用作画布的CSS背景图像。)

Initially have the canvas containing the black and white image with 100% opacity. 最初,画布包含不透明度为100%的黑白图像。 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();

I would probably use multiple clipping regions with varying alpha (one dab for each) to mimic the effect you are after. 我可能会使用具有不同alpha值的多个剪切区域(每个剪切区域一个)来模仿您想要的效果。 Render the low opacity one first (paste using drawImage) and render the rest after that till you reach alpha=1.0. 首先渲染低不透明度(使用drawImage粘贴),然后渲染其余部分,直到达到alpha = 1.0。

Have you considered using radial gradients that go from an opaque color to a fully transparent one? 您是否考虑过使用从不透明的颜色到完全透明的径向渐变?

Here is a demo from Mozilla. 这是Mozilla的演示。 The circles are drawn the way you need. 圆是按照您需要的方式绘制的。 - https://developer.mozilla.org/samples/canvas-tutorial/4_10_canvas_radialgradient.html -https://developer.mozilla.org/samples/canvas-tutorial/4_10_canvas_radialgradient.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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