简体   繁体   English

有没有办法在画布中将不透明度设置为 0 而不是用颜色绘制?

[英]Is there a way to set opacity to 0 in a canvas instead of drawing with a color?

I have the following function:我有以下功能:

function draw(event) {
        context.beginPath();
        context.lineWidth = 20;
        context.lineCap = 'round';
        context.strokeStyle = 'rgb(255, 255, 255)';
        context.moveTo(coord.x, coord.y);
        reposition(event);
        context.lineTo(coord.x, coord.y);
        context.stroke();
    }

And I would like to know if it's possible to, instead of having a color in the strokeStyle, to just reduce the opacity to 0 so that I am essentially "erasing" the canvas element and show the element that is behind it.而且我想知道是否有可能,而不是在 strokeStyle 中使用颜色,而只是将不透明度降低到 0,以便我基本上“擦除”画布元素并显示它背后的元素。

I am sorry if this has been asked before, I couldn't find any answer to this anywhere.很抱歉,如果以前有人问过这个问题,我在任何地方都找不到任何答案。

To do this, you need to set the globalCompositeOperation to an operation type that removes the existing colors when something is drawn to the canvas.为此,您需要将 globalCompositeOperation 设置为一种在画布上绘制内容时移除现有颜色的操作类型。 I've made a fiddle that demonstrates this: https://jsfiddle.net/twc1xern/我做了一个小提琴来证明这一点: https ://jsfiddle.net/twc1xern/

It has two canvases, one in front of the other.它有两张画布,一张在另一张前面。 The front canvas is filled with red and the back canvas is set to blue.前面的画布用红色填充,后面的画布设置为蓝色。 When the operation is set:设置操作时:

foreground.globalCompositeOperation = 'destination-out'

Drawing a line removes the color data from the foreground canvas, showing the blue canvas underneath.绘制一条线会从前景画布中删除颜色数据,显示下方的蓝色画布。

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

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