canvas中的合成------globalCompositeOperation
我们知道canvas其实就是一层一层的图层,后画的图案会覆盖到前面图案的上面,通过一层一层叠加的方式呈现到我们眼前,如下图所示
<body>
<canvas id='canvas' width="600" height="500"></canvas>
</body>
<script>
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
// 第一个圆
ctx.beginPath();
ctx.arc(150, 150, 100, 0, 2 * Math.PI, false);
ctx.fillStyle = 'pink'
ctx.fill();
// 第二个圆
ctx.beginPath();
ctx.arc(250, 150, 100, 0, 2 * Math.PI, false);
ctx.fillStyle = 'orange'
ctx.fill();
// 第三个圆
ctx.beginPath();
ctx.arc(200, 250, 100, 0, 2 * Math.PI, false);
ctx.fillStyle = 'yellow'
ctx.fill();
</script>
但是有时候这并不是我们最终想要的结果,我们希望的是合成这三个圆形,然后只展示其中一部分的图案,这个时候我们就可以利用globalCompositeOperation属性来达到我们想要得效果
其中globalCompositeOperation的取值有如下几种
value | description |
---|---|
source-over | 默认取值,新图像会覆盖在原有图像上 |
source-in | 仅仅会出现新图像与原来图像重叠的部分,其他区域都变成透明的。(包括其他的老图像区域也会透明) |
source-out | 仅仅显示新图像与老图像没有重叠的部分,其余部分全部透明。(老图像也不显示) |
source-atop | 新图像仅仅显示与老图像重叠区域。老图像仍然可以显示。 |
destination-over | 新图像会在老图像的下面。 |
destination-in | 仅仅新老图像重叠部分的老图像被显示,其他区域全部透明。 |
destination-out | 仅仅老图像与新图像没有重叠的部分。 注意显示的是老图像的部分区域。 |
destination-atop | 老图像仅仅显示重叠部分,新图像会显示在老图像的下面。 |
lighter | 新老图像都显示,但是重叠区域的颜色做加处理。 |
darken | 保留重叠部分最黑的像素。(每个颜色位进行比较,得到最小的) |
lighten | 保证重叠部分最量的像素。(每个颜色位进行比较,得到最大的) |
xor | 重叠部分会变成透明。 |
copy | 只有新图像会被保留,其余的全部被清除(边透明)。 |
为了更加直观的理解globalCompositeOperation,后面案列都以两个图案叠加来演示效果
- source-in
// 第一个圆 ctx.beginPath(); ctx.arc(150, 150, 100, 0, 2 * Math.PI, false); ctx.fillStyle = 'pink' ctx.fill(); ctx.globalCompositeOperation = 'source-in'; // 第二个圆 ctx.beginPath(); ctx.arc(250, 150, 100, 0, 2 * Math.PI, false); ctx.fillStyle = 'orange' ctx.fill();
- source-out
-
source-atop
-
destination-over
-
destination-in
-
destination-out
- destination-atop
-
lighter
-
darken
-
Pink: #FFC0CB;
-
orange: #FFA500
两个做取小运算得到:#FFA000(计算出来的这个颜色和orange极其相似,所以看起来重叠部分好像没啥特别,感兴趣的可与换颜色试一试)
-
-
lighten
-
Pink:#FFC0CB;
-
orange:#FFA500
两个做取大运算得到:#FFC5CB(计算出来的这个颜色和pink极其相似,所以看起来重叠部分好像没啥特别,感兴趣的可与换颜色试一试)
-
-
xor
- copy