前言

最近用canvas学做动画发现很多时候,需要给动画加上尾迹效果,但是没有加尾迹时用的 clearRect()
方法清除的指定元素,添加尾迹后用的是fillRect() 覆盖的元素 这时候就要再添加一个元素遮盖,且元素的填充色不能透明,
这样就做不到背景透明了,我们所能看见的背景色,就是覆盖的元素填充色。但好在canvas提供了 globalCompositeOperation 属性,这样我们可以用globalCompositeOperation属性提供的值
写出透明的背景且带尾迹的动画,这样的canvas在你网页的任何地方都不会遮盖你的内容!
比如我之前写过一个烟花特效,以后有机会整理后发出!

示例

下面就看看我的简单示例:

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
66
67
68
<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;"></canvas>

<script>
window.requestAnimFrame = (function(){
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(callback){
window.setTimeout(callback, 1000 / 60);
};
})();
var canvas = document.getElementById('myCanvas'),
ctx = canvas.getContext('2d'),
w = canvas.width,
h = canvas.height,
posX = 20,
posY = 20,
speedX = 2,//小球X轴速度
speedY = 2,//小球Y轴速度
startSpeedX = 2,//小球X轴初始速度
startSpeedY = 2,//小球Y轴初始速度
radius = 20;//小球半径

function ani(){
//ctx.clearRect(0, 0, canvas.width, canvas.height); // 特别注释让大家了解 原先不带尾迹是如何展示
ctx.globalCompositeOperation = 'destination-out'; // 在源图像外显示目标图像。只有源图像外的目标图像部分会被显示,源图像是透明的。
ctx.fillStyle = 'rgba(0, 0, 0, 0.1)'; // 背景透明度越低尾迹越长
ctx.fillRect(0, 0, canvas.width, canvas.height); // 添加一个 和canvas 大小一样的矩形填充
posX += speedX;
posY += speedY;

//小球碰壁反弹
if(posY > h - radius){
speedY*=-1;
}
if(posX > w - radius){
speedX*=-1;
}
if(posY < radius){
speedY = startSpeedY;
posY = radius;
}
if(posX < radius){
speedX = startSpeedX;
posX = radius;
}

ctx.beginPath();
ctx.globalCompositeOperation = 'lighter'; // 显示源图像 + 目标图像。
ctx.arc(posX,posY,radius,0,2*Math.PI);
ctx.fillStyle = 'red';
ctx.closePath();
ctx.fill();
requestAnimFrame(ani);
}

ani();
</script>

</body>
</html>

以上代码复制可直接运行。