1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>canvas colorful ball</title>
<style> #canvas { margin: 0 auto; display: block; } </style> </head> <body> <canvas id="canvas">current browser is not support</canvas> <script> /*get canvas*/ const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); canvas.width = 1000; canvas.height = 600; canvas.style.backgroundColor = '#000';
/*Ball class*/ class Ball { constructor(x, y, color) { this.x = x; this.y = y; this.color = color; this.r = 30; }
/*render ball*/ render() { ctx.save(); ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2); ctx.fillStyle = this.color; ctx.fill(); ctx.restore(); }
}
/*move mouse action*/ class MoveBall extends Ball { constructor(x, y, color) { super(x, y, color);
this.dX = parseInt(Math.random() * 10 - 5); this.dY = parseInt(Math.random() * 10 - 5); this.dR = parseInt(Math.random() * 2 + 1); }
update() { this.x += this.dX; this.y += this.dY; this.r -= this.dR; if (this.r < 0) this.r = 0; } }
let ballArray = []; let colorArray = ['red', 'yellow', 'blue', 'purple', 'pink', 'orange'];
canvas.addEventListener('mousemove', function(e) { var e = e || event; var colorIndex = parseInt(Math.random() * 5); ballArray.push(new MoveBall(e.offsetX, e.offsetY, colorArray[colorIndex])); });
setInterval(function() { ctx.clearRect(0, 0, canvas.width, canvas.height); for(item of ballArray) { item.render(); item.update(); } }, 50); </script> </body> </html>
|