如果多個效果都寫在一個畫布上,容易出現效果錯亂的問題,所以這個範例是使用畫一個存出來一個的方式執行。
參考網站:http://www.html5canvastutorials.com/advanced/html5-canvas-global-composite-operations-tutorial/
HTML
<!--Original source http://www.html5canvastutorials.com/advanced/html5-canvas-global-composite-operations-tutorial/--> <canvas id="tempCanvas" width="600" height="400" style="display:none;"></canvas> <canvas id="mainCanvas" width="600" height="400"></canvas>
JQuery 1.9.1
$(function(){
var tempCtx=$('#tempCanvas')[0].getContext('2d');//形成圖形相加效果的畫布
var temp=$('#tempCanvas');
var bCtx=$('#mainCanvas')[0].getContext('2d');//tempCtx圖形繪製出來後,擺放圖形的畫布
var bCtxW=$('#mainCanvas').width();//消除已經複製過的圖形時所需要使用的寬
var bCtxH=$('#mainCanvas').height();//消除已經複製過的圖形時所需要使用的高
var sW=50;//第一層的方形寬高
var cR=30;//第二層的圓形半徑
var offset=45;//兩個圖相疊時的差距
var operationOffset=140;//下一個圖形擺放的間距
var i=[];//放效果指令的陣列
//將所有的交疊效果放入i陣列中
i.push('source-atop');
i.push('source-in');
i.push('source-out');
i.push('source-over');
i.push('destination-atop');
i.push('destination-in');
i.push('destination-out');
i.push('destination-over');
i.push('lighter');
i.push('darker');
i.push('xor');
i.push('copy');
console.log(i);
for(var n=0; n < i.length; n++){
tempCtx.save();//將每次繪製圖前的空值狀態存下,以便繪製完成後恢復到空值狀態
tempCtx.clearRect(0,0,bCtxW,bCtxH);//清除tempCtx上的上一個交疊效果圖形
tempCtx.beginPath();//繪製上層的方形
tempCtx.rect(0,0,sW,sW);
tempCtx.fillStyle="#62EACB";
tempCtx.fill();
tempCtx.globalCompositeOperation=i[n];//把效果從陣列中取出放入驅動效果
console.log(i[n]);
tempCtx.beginPath();//繪製下層的圓形
tempCtx.arc(offset,offset,cR,0,2*Math.PI);
tempCtx.fillStyle='#E177EA';
tempCtx.fill();
tempCtx.restore();//回復到空值的狀態
tempCtx.font='14px arial';
tempCtx.fillStyle='#666';
tempCtx.fillText(i[n],0,sW+45);//把效果的名稱列在圖形下面
if(n > 0){
if(n % 4 === 0){//圖形寫入mainCanavs食,每4個一排
bCtx.translate(operationOffset*-3,operationOffset);//當遇到4能整除的那個就往下折行
}else{
bCtx.translate(operationOffset,0);//如果無法整除就直接往右增加
}
}
bCtx.drawImage(tempCanvas,0,0);//把tempCanvas用image的方式繪製到mainCanvas上面
}
});
主要使用function :
- clearRect() - 刪除畫布上的一個區域,clearRect(要刪除的起始點x軸,要刪除的起始點y軸,要刪除的寬度,要刪除的高度)。
- globalCompositeOperation - 控制兩個互相覆蓋的圖形使用何種覆蓋效果。
值 解說 source-over 預設值,正常順序的上下圖形覆蓋。 source-in 保留兩個圖形交疊的區域且保留上層圖形的樣式。 source-out 只保留非交疊的上層圖形的形狀與樣式。 source-atop 兩個圖形的樣式都保留但是只使用下層圖形的形狀。 destination-over 兩個圖形的上下層級互換。 destination-in 保留兩個圖形交疊的區域且保留下層圖形的樣式。 destination-out 只保留非交疊的下層圖形的形狀與樣式。 destination-atop 兩個圖形的樣式都保留但是只使用上層圖形的形狀。 lighter 兩個圖形交疊處的顏色由兩個圖形的色相加而成。 darker 已移除的值,兩個圖形交疊處的顏色由兩個圖形的色碼相減而成。 xor 兩個圖形交疊區為透明。 copy 移除其他圖形,只保留最上層的圖形。
Result
JSFiddle
https://jsfiddle.net/MickeyChen/krjLs085/

沒有留言:
張貼留言