karen @
henlo
Welcome to karen's Sandbox.
View Other Sites from karen
Toggle Full-Width
HTML
<canvas></canvas> <h3>Creating fireworks with your mouse click</h3> <input type='range' min='1' max='9' value='9' step='1' id='speed'>
JavaScript
const cvs = document.querySelector('canvas'); const ctx = cvs.getContext('2d'); let WIDTH = document.documentElement.clientWidth; let HEIGHT = document.documentElement.clientHeight; cvs.width = WIDTH; cvs.height = HEIGHT; fireworks = [] // empty array which will hold Firework objects class Firework { constructor(x, y) { this.x = x; this.y = y; this.r = 0; this.rStop = Math.random() * WIDTH / 8; } drawLine(angle, i) { ctx.beginPath(); ctx.moveTo(this.x + 1.5 * this.r * Math.cos(angle), this.y + 1.5 * this.r * Math.sin(angle)); ctx.lineTo(this.x + (3.5 + Math.pow(-1, i)) * this.r * Math.cos(angle), this.y + (3.5 + Math.pow(-1, i)) * this.r * Math.sin(angle)); ctx.stroke(); ctx.strokeStyle = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')'; } drawCircle(){ ctx.beginPath(); ctx.arc(this.x, this.y, this.r, 0, 2 * Math.PI); ctx.closePath(); ctx.fillStyle = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')'; ctx.fill(); } draw() { this.drawCircle(); var i = 0; for (var angle = 0; angle < 2 * Math.PI; angle += 1/10 * Math.PI) { i++; i %= 2; this.drawLine(angle, i); } } } cvs.onclick = function(e) { x = e.clientX; y = e.clientY; fireworks.push(new Firework(x, y)); } function expand() { ctx.clearRect(0, 0, WIDTH, HEIGHT); toRemove = []; // hold indices of fireworks to remove for (let i = 0; i < fireworks.length; i++) { let firework = fireworks[i]; if (firework.r < firework.rStop) { firework.r++; firework.draw(); } else { toRemove.push(i); } } for (var i = toRemove.length - 1; i >= 0; i--) { fireworks.splice(i, 1); } console.log(Math.pow(2, document.querySelector('#speed').value)); setTimeout(expand, Math.pow(2, document.querySelector('#speed').value)); } expand()
CSS
canvas { width: 100%; height: 100%; border: 5px solid black; box-sizing: border-box; background-color: rgb(0, 0, 0); }