向画布添加透明度/alpha覆盖现有颜色



我正在尝试用画布创建一个月亮形状。为此,我创建了两个圆:一个用我的颜色填充,另一个用globalCompositionOperation: "destination-out"减去。

const moonCanvas = createCanvas(WIDTH, HEIGHT);
const moonCtx = canvas.getContext("2d");
moonCtx.beginPath();
moonCtx.arc(WIDTH / 2, HEIGHT / 2, HEIGHT / 4, 0, 2 * Math.PI);
moonCtx.fill();
moonCtx.globalCompositeOperation = "destination-out";
moonCtx.beginPath();
moonCtx.arc(WIDTH / 2 + 30, HEIGHT / 2, HEIGHT / 4, 0, 2 * Math.PI);
moonCtx.fill();

这是一把最小复制的小提琴:https://jsfiddle.net/h2qbytzn/

现在的问题是;明确的";通过此操作添加到画布的透明度。每当我想把月亮添加到另一个画布上时,它也包括透明部分,从而覆盖画布上已经存在的内容。

有没有一种方法可以在忽略透明部分的情况下导入画布内容?

现在对我有效的是创建第二个画布,在那里绘制我的对象,并使用drawImage:将它们合并到原始画布中

const c2 = createCanvas(WIDTH, HEIGHT);
const ctx2 = c2.getContext("2d");
ctx2.fillStyle = "yellow";
ctx2.beginPath();
ctx2.arc(WIDTH / 2, HEIGHT / 2, HEIGHT / 4, 0, 2 * Math.PI);
ctx2.fill();
ctx2.globalCompositeOperation = "destination-out";
ctx2.beginPath();
ctx2.arc(WIDTH / 2 + 30, HEIGHT / 2 - 15, HEIGHT / 4, 0, 2 * Math.PI);
ctx2.fill();
ctx.drawImage(c2, 0, 0); // merging the canvas, not its context!

最新更新