globalCompositeOperation
syntax:
globalCompositeOperation = type
注意:下面所有例子中,藍色方塊是先繪制的,即“已有的 canvas 內容”,紅色圓形是后面繪制,即“新圖形”。
source-over 這是默認設置,新圖形會覆蓋在原有內容之上。
destination-over 會在原有內容之下繪制新圖形。
source-in 新圖形會僅僅出現與原有內容重疊的部分。其它區域都變成透明的。
destination-in 原有內容中與新圖形重疊的部分會被保留,其它區域都變成透明的。
source-out 結果是只有新圖形中與原有內容不重疊的部分會被繪制出來。
destination-out 原有內容中與新圖形不重疊的部分會被保留。
source-atop 新圖形中與原有內容重疊的部分會被繪制,並覆蓋於原有內容之上。
destination-atop 原有內容中與新內容重疊的部分會被保留,並會在原有內容之下繪制新圖形
lighter 兩圖形中重疊部分作加色處理。
darker 兩圖形中重疊的部分作減色處理。
xor 重疊的部分會變成透明。
copy 只有新圖形會被保留,其它都被清除掉。
裁切路徑和普通的 canvas 圖形差不多,不同的是它的作用是遮罩,用來隱藏沒有遮罩的部分。
syntax
clip()
實例:
1 function draw() { 2 var ctx = document.getElementById('canvas').getContext('2d'); 3 ctx.fillRect(0,0,150,150); 4 ctx.translate(75,75); 5
6 // Create a circular clipping path
7 ctx.beginPath(); 8 ctx.arc(0,0,60,0,Math.PI*2,true); 9 ctx.clip(); 10
11 // draw background
12 var lingrad = ctx.createLinearGradient(0,-75,0,75); 13 lingrad.addColorStop(0, '#232256'); 14 lingrad.addColorStop(1, '#143778'); 15
16 ctx.fillStyle = lingrad; 17 ctx.fillRect(-75,-75,150,150); 18
19 // draw stars
20 for (var j=1;j<50;j++){ 21 ctx.save(); 22 ctx.fillStyle = '#fff'; 23 ctx.translate(75-Math.floor(Math.random()*150), 24 75-Math.floor(Math.random()*150)); 25 drawStar(ctx,Math.floor(Math.random()*4)+2); 26 ctx.restore(); 27 } 28
29 } 30 function drawStar(ctx,r){ 31 ctx.save(); 32 ctx.beginPath() 33 ctx.moveTo(r,0); 34 for (var i=0;i<9;i++){ 35 ctx.rotate(Math.PI/5);
36 if(i%2 == 0) { 37 ctx.lineTo((r/0.525731)*0.200811,0);
38 } else { 39 ctx.lineTo(r,0); 40 } 41 } 42 ctx.closePath(); 43 ctx.fill(); 44 ctx.restore(); 45 }