前文
我们在用canvas绘图中,经常会碰到当俩个图形重叠时怎么办的问题,这篇文章介绍的就是一些关于俩个图形重叠时的样式的处理问题
1. 设置组合方式
我们可以通过globalCompositeOperation这个属性,我们可以来更改俩个图形重叠时的样式
如:是想让新图覆盖原始图,还是只保留重叠部分等等.
语法:
ctx.globalCompositeOperation = source-in
先来看看几个属性值:
source-over 默认属性,新图像会覆盖在原有图像
source-in 只保留当前图重叠的部分
source-out 绘制不重叠部分
source-atop 新图像仅仅显示与老图像重叠区域,老图像仍然可以显示
destination-over 原图覆盖新图
destination-in 绘制原图和新图重叠部分
destination-out 绘制原图和新图不重叠部分
destination-atop 绘制原图和新图重叠部分以及新图
lighten 绘制新图和原图,重叠部分加色处理
darken 保留重叠部分最黑的像素
lighter 保证重叠部分最量的像素
copy 绘制新图,覆盖原图
xor 重叠部分会变成透明
1.2 几种组合方式案例
例1:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#canvas1{
border:1px solid red;
}
</style>
</head>
<body>
<canvas id="canvas1" width="500" height="500"></canvas>
</body>
<script type="text/javascript">
var canvas = document.getElementById("canvas1");
var ctx = canvas.getContext("2d");
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(150, 150, 100, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
ctx.fillStyle = "green";
ctx.beginPath();
ctx.arc(250,150, 100, 0, Math.PI*2, true);
ctx.closePath();
ctx.fill();
</script>
</html>
上面的例子中,我没有对图片的重叠部分做任何的处理,效果就是和source-over一样,新图会覆盖原图:

在代码中加入globalCompositeOperation属性的时候,会呈现不同的效果
1.source-over(default)
新图像会覆盖在原有图像。(默认)

2.source-in
只保留当前图重叠的部分其他区域都变成透明的。(包括其他的老图像区域也会透明)
ctx.globalCompositeOperation = "source-in"

3.source-out
绘制不重叠部分
ctx.globalCompositeOperation = "source-out"

4.source-atop
新图像仅仅显示与老图像重叠区域。老图像仍然可以显示。

5.destination-over
原图覆盖新图
ctx.globalCompositeOperation = "destination-over"

6.destination-in
绘制原图和新图重叠部分
ctx.globalCompositeOperation = "destination-in"

7.destination-out
绘制原图和新图不重叠部分
ctx.globalCompositeOperation = "destination-out"

8.destination-atop
绘制原图和新图重叠部分以及新图
ctx.globalCompositeOperation = "destination-atop"

9.lighten
绘制新图和原图,重叠部分加色处理
ctx.globalCompositeOperation = "lighter"

10.darken
保留重叠部分最黑的像素。(每个颜色位进行比较,得到最小的)
blue: #0000ff
red: #ff0000
所以重叠部分的颜色:#000000
ctx.globalCompositeOperation = "darken"

11.lighter
保证重叠部分最量的像素。(每个颜色位进行比较,得到最大的)
blue: #0000ff
red: #ff0000
所以重叠部分的颜色:#ff00ff
ctx.globalCompositeOperation = "lighter"

12.copy
只有新图像会被保留,其余的全部被清除(变透明)
ctx.globalCompositeOperation = "copy"

13.xor
重叠部分会变成透明
ctx.globalCompositeOperation = "xor"

网友评论