loop
函数中的相关说明
1、 requestAnimationFrame(loop);
让函数每隔一段时间运行一次
2、如何让小球避免长蛇轨迹,并稍微有一点之前的运动轨迹?
可以在下一次小球出现的时候重绘画布,让他变为黑色,再给一点透明度,就可以显示之前的一点运动轨迹了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>弹跳小球</title>
</head>
<body>
<!-- 1、利用canvas画布画画布 -->
<canvas></canvas>
<script>
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
const width = canvas.width = window.innerWidth;
const height = canvas.height = window.innerHeight;
const balls = [];
function random(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function randomColor() {
return 'rgb(' + random(0, 255) + ', ' + random(0, 255) + ', ' + random(0, 255) + ')';
}
function bbb(x, y, r, color, vx, vy) {
this.x = x;
this.y = y;
this.r = r;
this.color = color;
this.vx = vx;
this.vy = vy;
}
bbb.prototype.draw = function () {
ctx.beginPath();
ctx.fillStyle = this.color;
ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI);
ctx.fill();
};
bbb.prototype.run = function () {
if ((this.x + this.r) >= width) {
this.vx = -(this.vx);
}
if ((this.x - this.r) <= 0) {
this.vx = -(this.vx);
}
if ((this.y + this.r) >= height) {
this.vy = -(this.vy);
}
if ((this.y - this.r) <= 0) {
this.vy = -(this.vy);
}
this.x += this.vx;
this.y += this.vy;
};
bbb.prototype.click=function (){
for(var i=0;i<balls.length;i++){
if(!(this===balls[i])){
var dx=this.x-balls[i].x;
var dy=this.y-balls[i].y;
var l=Math.sqrt(dx*dx+dy*dy);
if(l=this.r+balls[i].r){
balls[i].color=this.color=randomColor();
}
}
}
};
function loop() {
ctx.fillStyle = 'rgba(0, 0, 0, 0.24)';
ctx.fillRect(0, 0, width, height);
while (balls.length < 25) {
const r = random(10,20);
const ball = new bbb(
random(r, width - r),
random(r, height - r),
r,
randomColor(),
random(-7, 7),
random(-7, 7));
balls.push(ball);
};
for (let i = 0; i < balls.length; i++) {
balls[i].draw();
balls[i].run();
balls[i].click();
}
requestAnimationFrame(loop);
}
loop();
</script>
</body>
</html>