var canvas = document.getElementsByTagName('canvas')[0];const ctx = canvas.getContext('2d');var arrBall = [];const Ball = class { constructor({ x, y, r }) { this.x = x; this.y = y; this.r = r; this.color = this.randomColor(); this.dx = parseInt(Math.random() * 10) - 5; //随机数-5~5 this.dy = parseInt(Math.random() * 10) - 5; //随机数-5~5 arrBall.push(this); } update() { this.x += this.dx; this.y += this.dy; this.r -= 3; if (this.r <= 0) { this.r = 0; arrBall.shift(); } } render() { ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2); ctx.fillStyle = this.color; ctx.fill(); } randomColor() { const type = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 'a', 'b', 'c', 'd', 'e', 'f']; let color = '#'; for (let i = 0; i < 6; i++) { let random = parseInt(Math.random() * 16); color += type[random]; } return color; }}; (function () { function init() { bindEvent(); } function bindEvent() { canvas.addEventListener('mousemove', function (e) { new Ball({ x: e.offsetX, y: e.offsetY, r: 20 }); console.log(arrBall) }, false) } setInterval(function () { ctx.clearRect(0, 0, canvas.width, canvas.height); for (i = 0; i < arrBall.length; i++) { arrBall[i].update(); if(arrBall[i]){ arrBall[i].render(); } } }, 20); init();})();