CanvasRenderingContext2D.globalCompositeOperation 属性是 Canvas 2D API 用来绘制新的图形时,设置图形间组合操作的。 每种类型都是一种表示组合或合成方式的字符串。
在 Canvas Tutorial 中查看 Compositing 章节。
语法
ctx.globalCompositeOperation = type;
类型
译者注:引用 EmbedLiveSample("Compositing_example", 750, 7300, "" ,"Web/API/Canvas_API/Tutorial/Compositing/Example") 导致后台报错,拒绝显示引用的超链接内容。“X-Frame-Operation"属性值被设置成"DENY(拒绝)"。请查看下面页面的内容:英文原文;中文翻译。
示例
使用 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 的变化:
Playable code
<canvas id="canvas" width="400" height="200" class="playable-canvas"></canvas> <div class="playable-buttons"> <input id="edit" type="button" value="Edit" /> <input id="reset" type="button" value="Reset" /> </div> <textarea id="code" class="playable-code" style="height:120px;"> ctx.globalCompositeOperation = "xor"; ctx.fillStyle = "blue"; ctx.fillRect(10, 10, 100, 100); ctx.fillStyle = "red"; ctx.fillRect(50, 50, 100, 100);</textarea>
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var textarea = document.getElementById("code");
var reset = document.getElementById("reset");
var edit = document.getElementById("edit");
var code = textarea.value;
function drawCanvas() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
eval(textarea.value);
}
reset.addEventListener("click", function() {
textarea.value = code;
drawCanvas();
});
edit.addEventListener("click", function() {
textarea.focus();
})
textarea.addEventListener("input", drawCanvas);
window.addEventListener("load", drawCanvas);
规范描述
| Specification | Status | Comment |
|---|---|---|
| WHATWG HTML Living Standard CanvasRenderingContext2D.globalCompositeOperation |
Living Standard | |
| Compositing and blending Level 1 | Candidate Recommendation |
浏览器兼容性
| Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| Blend modes | ? | 20 (20) | ? | ? | ? |
| Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
|---|---|---|---|---|---|---|
| Basic support | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) | (Yes) |
| Blend modes | ? | ? | 20.0 (20) | ? | ? | ? |
WebKit/Blink-specific 注解
- 在基于 WebKit- 和 Blink- 的浏览器中,除了此属性外,还实现了一个不标准的并且不赞成使用的方法
ctx.setCompositeOperation()。
Gecko-specific 注解
- 早起的规范草案指定了 "darker"值。 然而, Firefox 在第4个版本(bug 571532)移除了对 "darker"的支持。参见 这篇文章 建议如何使用不同的值实现和"darker"类似的效果。