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>