html5-canvas - html5 Canvas 中的自定义 globalCompositeOperation

标签 html5-canvas webgl globalcompositeoperation

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

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

他们都没有做我想做的事情。有没有办法定义自定义的 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 个 Canvas ,一个 2d Canvas 和一个 WebGL Canvas

    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,也许还有 moveTolineTo, fillstroke 然后在 WebGL 中重现会相对容易。如果您使用了很多功能,例如 mask 、贝塞尔曲线、渐变或图案,它就会开始变得更加繁琐。

作为首发here's a tutorial that presents a certain kind of compositing or image processing这是 WebGL 中 globalCompositeOperation 的基本技术。上述两种解决方案都需要这种基本类型的解决方案来在每个 shape 之后合成结果。

关于html5-canvas - html5 Canvas 中的自定义 globalCompositeOperation,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34562311/

相关文章:

javascript - Math.random() 未声明的标识符

javascript - 为什么我不能在 WebGL 中延迟 gl.drawArrays 函数?

javascript - 使用 requestAnim 或 TimeOut 在动画中滞后 FPS

javascript - html5 Canvas 填充文本具有特定的 alpha 和背景具有不同的 alpha

javascript - 如何使用 React 的上下文功能将 HTML5 Canvas 上下文传递给 this.props.children?

javascript - 剪辑通过 Canvas 运行的视频的最有效方法是什么

javascript - 在 html5 Canvas 中用鼠标旋转图像

html - 拖动时的 KineticJS 图层索引

javascript - 如何剪辑/使用 globalCompositeOperation = "desination-out"从我的 Canvas 中排除 2 个圆圈?

Canvas globalCompositeOperation 无法正常工作