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

简单点讲,在Canvas中,把图像源和目标图像,通过Canvas中的
globalCompositeOperation 操作,可以得到不同的效果,比如下图:
正如上图,红苹果和黑色的圆,通过
globalCompositeOperation 的
destination-out 就变成了被咬了一口的红苹果。也就是说,在Canvas中通过图像的合成,我们可以实现一些与众不同的效果,比如我们要制作一个刮刮卡抽奖的效果。 今天我们就来了解Canvas中的图像合成怎么使用。图像合成 globalCompositeOperation 类型
在Canvas中
globalCompositeOperation 属性的值总共有 26 种类型,每种类型都将前生不一样的效果,当然你可能看到效果都将不样,甚至有一些效果在浏览器中并不能正常的渲染。不过不要紧,我们简单的了解这26种类型其代表的含意以及产生的效果。
ctx.save();
ctx.translate(w / 2, h / 2);
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(-40, 20, 80, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();上面的代码将在Canvas画布上绘制一个半径为
80px 的红色圆形,在这里把它称为图像源。
ctx.fillStyle = 'orange';
ctx.beginPath();
ctx.arc(40, 20, 80, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.restore();这段代码将在Canvas画布上绘制一个半径为
80px 的橙色圆形,在这里把它称为图像目标。在图像源和目标图像之间设置
globalCompositeOperation 的值,就可以完成图像的合成操作:
ctx.save();
ctx.translate(w / 2, h / 2);
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(-40, 20, 80, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.globalCompositeOperation = 'source-in';
ctx.fillStyle = 'orange';
ctx.beginPath();
ctx.arc(40, 20, 80, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.restore();此时得到的效果如下:

source-over
source-over









