gpt4 book ai didi

javascript - 不影响前面层的 HTML Canvas globalCompositeOperation

转载 作者:行者123 更新时间:2023-11-30 20:41:23 29 4
gpt4 key购买 nike

我有这 4 个

enter image description here

我想做的是将 redblue 层放入一个 mask 中。但我不希望 purpleorange 层受到此掩码的影响(只有 redblue).我设法让它适用于 orange 但不适用于 purple

查看我的代码

var canvas = document.querySelector('canvas');
canvas.height = window.innerHeight
canvas.width = window.innerWidth
var ctx = canvas.getContext('2d');


//this should'nt be affected by the mask
ctx.beginPath()
ctx.fillStyle = 'purple';
ctx.rect(0, 50, 100, 100);
ctx.fill()

//this is the mask
ctx.beginPath()
ctx.rect(10, 10, 70, 70);
ctx.fillStyle = 'green';
ctx.fill()

ctx.globalCompositeOperation = 'source-atop';

//this need to be inside the mask
ctx.beginPath()
ctx.fillStyle = 'blue';
ctx.rect(10, 10, 100, 100);
ctx.fill()

//this need to be inside the mask
ctx.beginPath()
ctx.fillStyle = 'red';
ctx.rect(50, 40, 100, 100);
ctx.fill()


ctx.globalCompositeOperation = 'source-over'; //reset

//this should'nt be affected by the mask
ctx.beginPath()
ctx.fillStyle = 'orange';
ctx.rect(200, 40, 100, 100);
ctx.fill()

还有 fiddle https://jsfiddle.net/ws3b4q95/4/

最佳答案

Canvas 不知道形状是对象,它只关心像素。所以紫色矩形不能从您的蒙版中排除,因为 Canvas 上已经绘制的所有内容都将成为蒙版的一部分。

相反,您应该在应用蒙版后绘制矩形,并使用 destination-over 操作:

//this need to be inside the mask
ctx.beginPath()
ctx.fillStyle = 'red';
ctx.rect(50, 40, 100, 100);
ctx.fill()

//this should'nt be affected by the mask
ctx.globalCompositeOperation = 'destination-over';
ctx.beginPath()
ctx.fillStyle = 'purple';
ctx.rect(0, 40, 100, 100);
ctx.fill()

这是来自 Mozilla 的关于复合操作的精彩总结:MDN web docs: CanvasRenderingContext2D.global .CompositeOperation

关于javascript - 不影响前面层的 HTML Canvas globalCompositeOperation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49220341/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com