ZetCode

HTML5 Canvas 合成

最后修改于 2023 年 7 月 17 日

在本篇 HTML5 Canvas 教程中,我们将学习合成操作。

合成是将来自不同来源的视觉元素组合成单个图像。它们用于创造一种所有这些元素都属于同一场景的幻觉。合成在电影业中被广泛用于创造人群、全新的世界,而这些世界在其他方面会非常昂贵或不可能创造。

本教程“形状”章节中的“三个圆”示例使用了 destination-out 合成操作来创建新形状。

合成操作

developer.mozilla.org 的“合成与裁剪”章节列出了二十六种不同的合成操作。我们在下一个代码示例中展示了其中一些。

假设我们要在一个画布上绘制两个对象。第一个绘制的对象称为目标,第二个称为源。画布上下文的 globalCompositeOperation 属性决定了这两个对象如何混合在一起。例如,在 source-over 规则中,这是默认的合成操作,新形状绘制在现有形状的顶部。

compositing.html
<!DOCTYPE html>
<html>
<head>
<title>HTML5 Canvas compositing operations</title>  
<style>
    canvas {border: 1px solid brown}
    select {vertical-align:top}
</style>  
<script>
    var canvas;
    var ctx;
    var value = 'source-over';
    var operations = ['source-over', 'source-in', 'source-out',
        'source-atop', 'destination-over', 'destination-in', 'destination-out',
        'destination-atop', 'lighter', 'copy', 'xor'];

    function init() {

        canvas = document.getElementById('myCanvas');
        ctx = canvas.getContext('2d');
        draw();    
    }

    function getOperation(sel) {
        
        value = operations[sel.value];
        draw();
    }

    function draw() {
    
      ctx.save();
      ctx.clearRect(0, 0, canvas.width, canvas.height);
      ctx.fillStyle = 'blue';
      ctx.fillRect(20, 20, 40, 40);
      
      ctx.globalCompositeOperation = value; 
      
      ctx.fillStyle = 'green';
      ctx.fillRect(25, 25, 40, 40);
      ctx.restore();
    }    
</script>
</head>
    
<body onload="init();">

    <canvas id="myCanvas" width="150" height="100">
    </canvas>
    
    <select id="opers" onchange="getOperation(this)">
      <option value="0" selected="selected">source-over</option>
      <option value="1">source-in</option>
      <option value="2">source-out</option>
      <option value="3">source-atop</option>
      <option value="4">destination-over</option>
      <option value="5">destination-in</option>
      <option value="6">destination-out</option>
      <option value="7">destination-atop</option>
      <option value="8">lighter</option>
      <option value="9">copy</option>
      <option value="10">xor</option>
    </select> 
        
</body>
</html>

在示例中,我们有一个合成操作的下拉列表。选择的操作应用于两个重叠矩形的绘制。

var operations = ['source-over', 'source-in', 'source-out',
    'source-atop', 'destination-over', 'destination-in', 'destination-out',
    'destination-atop', 'lighter', 'copy', 'xor'];

operations 数组包含十一种合成操作。

function init() {

    canvas = document.getElementById('myCanvas');
    ctx = canvas.getContext('2d');
    draw();    
}

init 函数内部,我们获取了画布对象及其绘制上下文的引用。

ctx.save();
...
ctx.restore();

每次从下拉列表中选择一个选项时,画布都会用新的合成操作进行重绘。为了获得正确的结果,我们必须将绘制代码放在 saverestore 方法之间。这样操作就可以彼此隔离。

ctx.clearRect(0, 0, canvas.width, canvas.height);

clearRect 方法清除之前的输出。

ctx.globalCompositeOperation = value; 

globalCompositeOperation 使用从下拉列表中选择的值进行设置。

Compositing
图:合成

上图显示了 xor 合成操作。在此规则中,当两个形状重叠时,重叠的部分会变得透明,其他部分则正常绘制。

在本篇 HTML5 Canvas 教程中,我们讨论了图像合成。