window.requestAnimationFrame()
方法告诉浏览器您希望执行动画并请求浏览器在下一次重绘之前调用指定的函数来更新动画。该方法使用一个回调函数作为参数,这个回调函数会在浏览器重绘之前调用。
例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>requestAnimationFrame</title>
<style>
* {
margin: 0;
padding: 0;
}
.box {
width: 500px;
height:500px;
border: 1px solid #ccc;
}
</style>
</head>
<body>
<div class="box">
<canvas></canvas>
</div>
<script>
(function() {
var oBox = document.querySelector(".box");
var canvas = document.querySelector("canvas");
canvas.width = oBox.offsetWidth;
canvas.height = oBox.offsetHeight;
ctx = canvas.getContext('2d');
function Ball(x,y,r) {
this.x = x;
this.y = y;
this.r = r;
this.vx = random(-2,2);
this.vy = random(-3,3);
this.colors = ['#FF69B4','#C71585','#FF00FF','#800080','#9400D3','#90EE90'];
this.color = this.colors[Math.floor(random(0,6))]
this.a = 1;
}
var ball = new Ball();
Ball.prototype = {
drawBall:function() {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.globalAlpha = this.a;
ctx.arc(this.x,this.y,this.r,0,2*Math.PI);
ctx.fill();
ctx.closePath();
this.updata();
},
updata: function() {
this.x += this.vx;
this.y += this.vy;
this.a -= 0.05;
}
}
function random(min,max) {
return min+(max-min)*Math.random();
}
var flag = false;
var ballList = [];
oBox.addEventListener("mousedown",function() {
flag = true;
})
oBox.addEventListener("mousemove",function(e) {
if(!flag) {
return;
}
var ball = new Ball(e.x,e.y,10);
ballList.push(ball);
})
oBox.addEventListener("mouseup",function() {
console.log(ballList)
flag = false;
})
function render() {
ctx.clearRect(0,0,oBox.offsetWidth,oBox.offsetWidth)
ballList.forEach(function(item,index) {
console.log(item.a)
if(item.a<0) {
ballList.splice(index,1);
return;
}
item.drawBall();
});
if(ballList.length>10) {
var s = ballList.length-100
ballList.splice(0,s);
}
requestAnimationFrame(render);
}
render();
})();
</script>
</body>
</html>