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 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
| <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> * { margin: 0; padding: 0; } </style> </head> <body>
<canvas></canvas>
</body>
</html> <script>
let canvas = document.querySelector("canvas"); let ctx = canvas.getContext("2d");
canvas.width = document.documentElement.clientWidth - 30; canvas.height = document.documentElement.clientHeight;
function Ball(x, y, r) { this.x = x; this.y = y; this.r = r; this.color = randomColor(); this.dx = parseInt(Math.random() * 20) - 10; this.dy = parseInt(Math.random() * 20) - 10; ballArr.push(this); }
function randomColor() { let allType = "0.1.2.3.4.5.6.7.8.9.a.b.c.d.e.f"; let allTypeArr = allType.split("."); let color = "#"; for (let i = 0; i < 6; i ++) { let randomType = parseInt(Math.random() * allTypeArr.length); color += allTypeArr[randomType]; } return color; }
Ball.prototype.render = function() { ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, Math.PI * 2, false); ctx.fillStyle = this.color; ctx.fill(); }
Ball.prototype.update = function() { this.x += this.dx; this.y += this.dy; this.r -= 3; if (this.r < 0) { this.remove(); } }
Ball.prototype.remove = function() { for (let i = 0; i < ballArr.length; i ++) { if (ballArr[i] == this) { ballArr.splice(i, 1) } } }
canvas.addEventListener("mousemove", function(event) { let e = event || window.event; new Ball(e.offsetX, e.offsetY, 30); });
let ballArr = [];
setInterval(function() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (let i = 0; i < ballArr.length; i ++) { ballArr[i].update(); if (ballArr[i]) { ballArr[i].render(); } } }, 60)
</script>
|