Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

HTML5 Canvas 圖形合成:globalCompositeOperation 的 11 種玩法

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();
}

11 種模式怎麼記

把 source 當成「新圖形」、destination 當成「舊圖形」,命名規則就清楚了:source-* 系列以新圖形為主角,destination-* 系列則保留舊圖形為主體。

  • source-atop=新圖形中的(新∩舊)+舊圖形中(非交集)
  • source-in=只留新圖形中的交集部分
  • source-out=只留新圖形中「非交集」的部分
  • source-over(預設值)=舊圖形全部+新圖形全部,也就是最直覺的疊上去
  • destination-atop=舊圖形中的交集+新圖形中的非交集
  • destination-in=只留舊圖形中的交集
  • destination-out=只留舊圖形中的非交集
  • destination-over=舊圖形全部+新圖形的非交集,等於把新圖形塞到背後
  • lighter=兩圖形相加,顏色會往更亮的方向疊加
  • copy=只顯示新圖形
  • xor(對稱差)=兩圖形各自的非交集,重疊處反而消失

以下依序是各模式的實際輸出:

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 往往是最省事的做法,不必再回頭處理像素運算。

Copyright © Linux教程網 All Rights Reserved