Canvas 提供了 11 種圖形合成模式,只要把對應的關鍵字指派給 context.globalCompositeOperation,兩個圖形重疊的部分就會依規則重新計算。下面做了一個小工具,用下拉選單切換模式,即時看到差異。
<!-- 選擇合成方式,選完觸發 onchange 重畫 -->
<select id="selectCombineMethod" onchange="draw('canvas')">
<option>source-atop</option>
<option>source-in</option>
<option>source-out</option>
<option>source-over</option>
<option>destination-atop</option>
<option>destination-in</option>
<option>destination-out</option>
<option>destination-over</option>
<option>lighter</option>
<option>copy</option>
<option>xor</option>
</select>
<canvas id="canvas" width="1000" height="1000"></canvas>
先畫「舊圖形」(destination,這裡是藍色正方形),再把使用者選的模式寫進 context,然後畫「新圖形」(source,紅色圓)。關鍵就在設定與作畫的順序上。
function draw(id){
var selectComponent = document.getElementById("selectCombineMethod");
var selectedIndex = selectComponent.selectedIndex;
var strategy = selectComponent.options[selectedIndex].value;
var canvas = document.getElementById(id);
if (canvas == null) return false;
var context = canvas.getContext('2d');
// 1. 先畫舊圖形:藍色正方形
context.fillStyle = 'blue';
context.fillRect(40, 40, 60, 60);
// 2. 套用使用者挑的合成模式
context.globalCompositeOperation = strategy;
// 3. 再畫新圖形:紅色圓
context.fillStyle = 'red';
context.beginPath();
context.arc(40 + 60, 40 + 60, 30, 0, Math.PI * 2, false);
context.fill();
}
把 source 當成「新圖形」、destination 當成「舊圖形」,命名規則就清楚了:source-* 系列以新圖形為主角,destination-* 系列則保留舊圖形為主體。
以下依序是各模式的實際輸出:
650) this.width=650;" border=0>
650) this.width=650;" border=0>
650) this.width=650;" border=0>
650) this.width=650;" border=0>
650) this.width=650;" border=0>
650) this.width=650;" border=0>
650) this.width=650;" border=0>
650) this.width=650;" border=0>
650) this.width=650;" border=0>
650) this.width=650;" border=0>
650) this.width=650;" border=0>
實作遮罩、鏤空、影像合成這類需求時,destination-in 與 xor 往往是最省事的做法,不必再回頭處理像素運算。