CanvasRenderingContext2D.globalCompositeOperation
Canvas 2D API的 CanvasRenderingContext2D
.globalCompositeOperation
属性设置要在绘制新形状时应用的合成操作的类型,其中type是用于标识要使用的合成或混合模式操作的字符串。
在 Canvas Tutorial 中查看 Compositing 章节。
语法
ctx.globalCompositeOperation = type;
类型
示例
使用 globalCompositeOperation
属性
这是一段使用 globalCompositeOperation
属性的简单的代码片段,绘制了2个矩形在重叠时相互排斥的情况。
HTML
<canvas id="canvas"></canvas>
JavaScript
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
ctx.globalCompositeOperation = "xor";
ctx.fillStyle = "blue";
ctx.fillRect(10, 10, 100, 100);
ctx.fillStyle = "red";
ctx.fillRect(50, 50, 100, 100);
修改下面的代码并在线查看 canvas 的变化:
规范描述
Specification | Status | Comment |
---|---|---|
HTML Living Standard CanvasRenderingContext2D.globalCompositeOperation |
Living Standard | |
Compositing and Blending Level 1 | Candidate Recommendation |
浏览器兼容性
BCD tables only load in the browser
WebKit/Blink-specific 注解
- 在基于 WebKit- 和 Blink- 的浏览器中,除了此属性外,还实现了一个不标准的并且不赞成使用的方法
ctx.setCompositeOperation()
。
Gecko-specific 注解
- 早起的规范草案指定了 "darker"值。 然而, Firefox 在第4个版本(bug 571532)移除了对 "darker"的支持。参见 这篇文章 建议如何使用不同的值实现和"darker"类似的效果。