问题描述
如何使用 alpha = 0
绘制HTML5画布?想象一下,我正在制作一个photoshop克隆,我有一层坚固的红色。我选择橡皮擦工具并绘制。它绘制了 rgba(0,0,0,0)
让我看到后台。如何在HTML5 Canvas中执行此操作?
How do you draw with alpha = 0
to an HTML5 Canvas? Imagine I'm making a photoshop clone, I have a layer that's solid red. I pick the eraser tool and draw with. It draws in rgba(0,0,0,0)
letting me see through to the background. How do I do this in HTML5 Canvas?
以下是一些代码。
var rand = function(v) {
return Math.random() * v;
};
var canvas = document.getElementsByTagName("canvas")[0];
var ctx = canvas.getContext("2d");
// fill the canvas with black
ctx.fillStyle = "red";
ctx.fillRect(0, 0, canvas.width, canvas.height);
// Erase some circles (draw them in 0,0,0,0);
ctx.fillStyle = "rgba(0,0,0,0)";
ctx.globalCompositeOperation = "copy";
for (var ii = 0; ii < 5; ++ii) {
ctx.beginPath();
ctx.arc(rand(canvas.width), rand(canvas.height),
rand(50) + 20, 0, 360, false);
ctx.fill();
}
/*
source-over
source-in
source-out
source-atop
destination-over
destination-in
destination-out
destination-atop
lighter
darker
copy
xor
*/
canvas {
margin: 10px;
border: 1px solid black;
background-color: yellow;
}
<div>Want red with yellow circles</div>
<canvas></canvas>
这不起作用。所有画布操作都被认为是无限大的,这意味着用 globalCompositeOperation
绘制每个圆(弧)有效地擦除每个圆圈之外的所有内容。
This doesn't work. All canvas operations are considered to be infinitely large which means drawing each circle (arc) with globalCompositeOperation
set to "copy" effectively erases everything outside of each circle.
我可能能够设置剪裁以匹配圆圈,但理想情况下我希望能够使用消除锯齿的圆圈进行擦除,就像使用Photoshop笔刷一样。
I might be able to setup clipping to match the circle but ideally I'd like to be able to erase with an anti-aliased circle, same as a photoshop brush.
推荐答案
您将要使用:
ctx.fillStyle = "rgba(0,0,0,1)"; // (Drawing with 0 alpha pretty much means doing nothing)
ctx.globalCompositeOperation = "destination-out";
Working Example
请记住保存以前的 globalCompositeOperation
并恢复它,或透明度将无法正常工作,以后。
Keep in mind to save the previous globalCompositeOperation
and restore it, or transparency won't work properly, later on.
问题是使用绘图alpha = 0 默认情况下,画布上的code>只是覆盖了一层不可见的墨水。
The problem is that "Drawing with alpha=0
on a canvas just overlays a invisible layer of "ink", by default.
这篇关于如何在html5画布中使用alpha = 0绘制“擦除”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!