html5 Canvas 中的自定义 globalCompositeOperation

Custom globalCompositeOperation in html5 Canvas

我在这里查看所有不同类型的全局复合操作:

https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation

None 他们完全按照我的意愿行事。有没有办法定义自定义的 globalCompositeOperation?如果我可以创建一个着色器,然后每次我用 CanvasRenderingContext2D.draw 方法绘制东西时都使用它,那将是完美的。

具体来说,在每个像素的基础上,我希望 CanvasRenderingContext2D.draw 方法使用以下(伪代码)操作:

if the existing canvas color alpha is 0.0, 
    then draw the new shape's color and set alpha to 0.1
if the existing canvas color is the same as the new shape's color
    then increase the alpha, by 0.1
if the existing canvas color is different from the the new shape's color
    then decrease the alpha by 0.1

我的想法是否正确?我觉得我应该以某种方式使用 WebGLRenderingContext,但我对它们如何组合在一起有点犹豫。

答案大多是否定的。

无法使用 Canvas2D 定义您自己的 globalCompositeOperation

我脑海中浮现出 2 个解决方案

  1. 使用 2 个 canvases,一个 2d 一个和一个 WebGL

    for each shape
       clear the 2d canvas
       draw the shape into the 2d canvas
       upload the canvas to a webgl texture
       composite that texture with the previous results using a custom shader.
    

    此解决方案的问题是它会很慢,因为将 canvas 上传到纹理是一个相对较慢的操作。但是,这意味着您可以使用所有 canvas 函数,如 strokearc 以及渐变等来构建它的形状。

  2. 完全切换到 WebGL

    这里的问题是您无法访问 2D API 的所有功能,并且复制所有这些功能需要大量工作。

    另一方面,如果您只使用有限的一组,那么工作量可能不会太大。例如,如果您只使用 drawImagefillRectclear,也许 moveTolineTofillstroke那么在 WebGL 中重现就相对容易了。如果您使用了很多功能,例如遮罩、贝塞尔曲线、渐变或图案,它就会开始变得更加繁琐。

作为初学者 here's a tutorial that presents a certain kind of compositing or image processing 这是 WebGL 中 globalCompositeOperation 的基本技术。上面的两种解决方案都需要这种基本类型的解决方案来在每个 shape.

之后合成结果