ThinkChat🤖让你学习和工作更高效,注册即送10W Token,即刻开启你的AI之旅 广告
[TOC] ## 示例 <details> <summary>main.js</summary> ``` // 设置画布 // const canvas = document.querySelector('canvas'); // const ctx = canvas.getContext('2d'); // const width = canvas.width = window.innerWidth; // const height = canvas.height = window.innerHeight; // // 生成随机数的函数 // function random(min,max) { // const num = Math.floor(Math.random() * (max - min)) + min; // return num; // } const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); const width =canvas.width= window.innerWidth; const height =canvas.height= window.innerHeight; console.log(width); console.log(height); 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 Ball(x,y,valx,valy,color,size){ this.x=x this.y=y // x,y 标识圆心 this.valx=valx this.valy=valy // 水平,垂直的速度 this.color=color // 小球颜色 this.size=size // 小球的半径 } Ball.prototype.draw=function(){ ctx.beginPath() ctx.fillStyle=this.color ctx.arc(this.x,this.y,this.size,0,2*Math.PI); ctx.fill(); } Ball.prototype.collisionDetect = function() { for (let j = 0; j < balls.length; j++) { if (this !== balls[j]) { const dx = this.x - balls[j].x; const dy = this.y - balls[j].y; const distance = Math.sqrt(dx * dx + dy * dy); if (distance < this.size + balls[j].size) { balls[j].color = this.color = randomColor(); //两球反向 balls[j].valx=-balls[j].valx balls[j].valy=-balls[j].valy this.valx=-this.valx this.valy=-this.valy } } } } //检查小球的 x 坐标是否大于画布的宽度(小球会从右边缘离开)。 // 检查小球的 x 坐标是否小于0(小球会从左边缘离开)。 // 检查小球的 y 坐标是否大于画布的高度(小球会从下边缘离开)。 // 检查小球的 y 坐标是否小于0(小球会从上边缘离开)。 Ball.prototype.update=function(){ // 碰撞检测 if((this.x+this.size) >= width){ this.valx=-(this.valx) } if((this.x-this.size)<=0){ this.valx=-(this.valx) } // 碰撞检测 if((this.y+this.size) >= height){ this.valy=-(this.valy) } if((this.y-this.size)<=0){ this.valy=-(this.valy) } this.x+=this.valx this.y+=this.valy } let balls = []; while (balls.length < 25) { let size = random(10, 20); let ball = new Ball( // 为避免绘制错误,球至少离画布边缘球本身一倍宽度的距离 random(0 + size, width - size), random(0 + size, height - size), random(-7, 7), random(-7, 7), randomColor(), size ); balls.push(ball); } function loop() { ctx.fillStyle = 'rgba(0, 0, 0, 0.25)'; ctx.fillRect(0, 0, width, height); for (let i = 0; i < balls.length; i++) { balls[i].draw(); balls[i].update(); balls[i].collisionDetect(); } requestAnimationFrame(loop); } loop() ``` </details> <br />