HTML5 Canvas合成

将透明度与globalCompositeOperation属性结合使用,可以用来控制图形和文本在画布上绘制的方式,合成globalCompositeOperation允许的值有:
copydestination-atopdestination-indestination-indestination-overdestination-outlightersource-atopsource-insource-outsource-oversource-overxor
实例代码选自《HTML5权威指南》

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!DOCTYPE html>
<html>
<head>
<title></title>
<style type="text/css">
select {
border: #eee solid 0.5px;
background-color: transparent;
}

canvas {
border: #eee solid 1px;
}
</style>
</head>
<body>
<canvas id="canvas" width="300" height="120">

</canvas>

<label>Composition Value</label>
<select id="list">
<option>copy</option>
<option>destination-atop</option>
<option>destination-in</option>
<option>destination-over</option>
<option>destination-out</option>
<option>lighter</option>
<option>source-atop</option>
<option>source-in</option>
<option>source-out</option>
<option>source-over</option>
<option>xor</option>
</select>
<script type="text/javascript">
var ctx = document.getElementById("canvas").getContext("2d");
ctx.fillStyle = "lightgrey";
ctx.strokeStyle = "black";
ctx.lineWidth = 3;

var compVal = "copy";

document.getElementById("list").onchange = function(e) {
compVal = e.target.value;
draw();
}

draw();

function draw() {
ctx.clearRect(0, 0, 300, 120);
ctx.globAlpha = 1.0;
ctx.font = "100px sans-serif";
ctx.fillText("Hello", 10, 100);
ctx.strokeText("Hello", 10, 100);

ctx.globalCompositeOperation = compVal;

ctx.fillStyle = "red";
ctx.globalAlpha = 0.5;
ctx.fillRect(100, 10, 150, 100);
}
</script>
</body>
</html>

代码默认效果

  • copy 效果时将来源绘制在目标上,忽略一切透明度设置,类似直接覆盖的效果,即将
  • destination-atop 使用目标图像来代替原图像,也就时保留透明度并叠加可见部分
  • destination-in 来源图像和目标图像都不透明处显示来源图像,来源图像应用了透明度,Hello应用了透明度,只显示与目标图像交集的地方
  • destination-over 来源图像覆盖在目标图像上,即Hello覆盖在红色矩形上
  • lighter来源图像与目标图像的总和,可以看出来源图像和目标图像都有了透明效果
  • source-atop 目标图像图像颜色叠加到源图像Hello
  • source-in 来源图像与目标图像叠加处显示来源图像和目标图像色彩
  • source-out 来源图像与目标图像叠加部分,来源图像Hello不透明处使其透明显示,其他位置显示目标图像
  • source-over 目标图像个叠加到来源图像上
  • xor 叠加出图像执行异或运算

原文:大专栏  HTML5 Canvas合成


猜你喜欢

转载自www.cnblogs.com/dajunjun/p/11639491.html