在默认情况之下,如果在Canvas之中将某个物体(源)绘制在另一个物体(目标)之上,那么浏览器就会简单地把源特体的图像叠放在目标物体图像上面。

图像合成globalCompositeOperation类型

在Canvas中globalCompositeOperation属性的值总共有26种类型,每种类型都将前生不一样的效果,当然你可能看到效果都将不样,甚至有一些效果在浏览器中并不能正常的渲染。不过不要紧,我们简单的了解这26种类型其代表的含意以及产生的效果。

 

1 ctx.save(); 
2 ctx.translate(w / 2, h / 2);
3 ctx.fillStyle = \'red\'; 
4 ctx.beginPath(); 
5 ctx.arc(-40, 20, 80, 0, Math.PI * 2, true); 
6 ctx.closePath(); 
7 ctx.fill();

 

上面的代码将在Canvas画布上绘制一个半径为80px的红色圆形,在这里把它称为图像源。

1 ctx.fillStyle = \'orange\'; 
2 ctx.beginPath();
3 ctx.arc(40, 20, 80, 0, Math.PI * 2, true); 
4 ctx.closePath(); 
5 ctx.fill();
6 ctx.restore();

这段代码将在Canvas画布上绘制一个半径为80px的橙色圆形,在这里把它称为图像目标。在图像源和目标图像之间设置globalCompositeOperation的值,就可以完成图像的合成操作:

 

 1 ctx.save(); 
 2 ctx.translate(w / 2, h / 2); 
 3 ctx.fillStyle = \'red\'; 
 4 ctx.beginPath(); 
 5 ctx.arc(-40, 20, 80, 0, Math.PI * 2, true); 
 6 ctx.closePath(); 
 7 ctx.fill(); 
 8 ctx.globalCompositeOperation = \'source-in\'; 
 9 ctx.fillStyle = \'orange\'; 
10 ctx.beginPath(); 
11 ctx.arc(40, 20, 80, 0, Math.PI * 2, true); 
12 ctx.closePath(); 
13 ctx.fill(); 
14 ctx.restore();

 

收藏 打印