canvas練習-炫彩小球
阿新 • • 發佈:2021-02-03
<html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> </head> <body> <canvas id="myCanvas" width="600" height="400"></canvas> <script> var myCanvas = document.getElementById("myCanvas"); var ctx = myCanvas.getContext("2d"); var circleList = new Map(); var uid = 0; class Circle { constructor(x, y) { this.x = x; this.y = y; this.uid = uid; this.color = this.getRandomColor(); this.r = Math.ceil(Math.random() * 20); let dx = parseInt(Math.random() * 10); let dy = parseInt(Math.random() * 10); this.dx = Math.random() > 0.5 ? -dx : dx; this.dy = Math.random() > 0.5 ? -dy : dy; circleList.set(uid, this); uid++; } getRandomColor() { return `rgba(${Math.round(Math.random() * 255)},${Math.round( Math.random() * 255 )},${Math.round(Math.random() * 255)}, ${Math.random().toFixed(2)})`; } update() { this.x += this.dx; this.y += this.dy; this.r -= 0.2; } render() { if (this.r < 0) { return; } ctx.beginPath(); ctx.fillStyle = this.color; try { ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false); } catch (e) { debugger; } ctx.fill(); ctx.closePath(); } } myCanvas.addEventListener("mousemove", function (e) { let { offsetX, offsetY } = e; new Circle(offsetX, offsetY); }); setInterval(function () { ctx.clearRect(0, 0, 600, 400); for (let [key, value] of circleList) { if (value.r > 0) { value.update(); value.render(); } else { circleList.delete(key); } } }, 30); </script> </body> </html>