html5 canvas 笔记五(合成与裁剪)
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 }
 
                    
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号