html5 canvas 筆記五(合成與裁剪)


組合 Compositing

globalCompositeOperation

syntax:

 
        
globalCompositeOperation = type
 
        

注意:下面所有例子中,藍色方塊是先繪制的,即“已有的 canvas 內容”,紅色圓形是后面繪制,即“新圖形”。

source-over  這是默認設置,新圖形會覆蓋在原有內容之上。

Image:Canvas_composite_srcovr.png

destination-over  會在原有內容之下繪制新圖形。

Image:Canvas_composite_destovr.png

source-in  新圖形會僅僅出現與原有內容重疊的部分。其它區域都變成透明的。

Image:Canvas_composite_srcin.png

destination-in  原有內容中與新圖形重疊的部分會被保留,其它區域都變成透明的。

Image:Canvas_composite_destin.png

source-out  結果是只有新圖形中與原有內容不重疊的部分會被繪制出來。

Image:Canvas_composite_srcout.png

destination-out  原有內容中與新圖形不重疊的部分會被保留。

Image:Canvas_composite_destout.png

source-atop  新圖形中與原有內容重疊的部分會被繪制,並覆蓋於原有內容之上。

Image:Canvas_composite_srcatop.png

destination-atop  原有內容中與新內容重疊的部分會被保留,並會在原有內容之下繪制新圖形

Image:Canvas_composite_destatop.png

lighter  兩圖形中重疊部分作加色處理。

Image:Canvas_composite_lighten.png

darker  兩圖形中重疊的部分作減色處理。

Image:Canvas_composite_darken.png

xor  重疊的部分會變成透明。

Image:Canvas_composite_xor.png

copy  只有新圖形會被保留,其它都被清除掉。

Image:Canvas_composite_copy.png

裁切路徑 Clipping paths

裁切路徑和普通的 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 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM