--- title: CanvasRenderingContext2D.globalCompositeOperation slug: Web/API/CanvasRenderingContext2D/globalCompositeOperation tags: - Canvas - CanvasRenderingContext2D translation_of: Web/API/CanvasRenderingContext2D/globalCompositeOperation ---
Canvas 2D API的 CanvasRenderingContext2D
.globalCompositeOperation
属性设置要在绘制新形状时应用的合成操作的类型,其中type是用于标识要使用的合成或混合模式操作的字符串。
在 Canvas Tutorial 中查看 Compositing 章节。
ctx.globalCompositeOperation = type;
{{EmbedLiveSample("合成示例", 750, 6750, "" ,"Web/API/Canvas_API/Tutorial/Compositing/Example")}}
globalCompositeOperation
属性这是一段使用 globalCompositeOperation
属性的简单的代码片段,绘制了2个矩形在重叠时相互排斥的情况。
<canvas id="canvas"></canvas>
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 的变化:
<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);
{{ EmbedLiveSample('Playable_code', 700, 380) }}
Specification | Status | Comment |
---|---|---|
{{SpecName('HTML WHATWG', "scripting.html#dom-context-2d-globalcompositeoperation", "CanvasRenderingContext2D.globalCompositeOperation")}} | {{Spec2('HTML WHATWG')}} | |
{{SpecName('Compositing')}} | {{Spec2('Compositing')}} |
{{Compat("api.CanvasRenderingContext2D.globalCompositeOperation")}}
ctx.setCompositeOperation()
。