Serge Bazanski | 717aad4 | 2021-07-11 16:03:43 +0000 | [diff] [blame] | 1 | import { animations } from "./animations.js"; |
| 2 | |
| 3 | class CanvasRenderer { |
| 4 | static WIDTH = 1024; |
| 5 | static HEIGHT = 1024; |
| 6 | |
| 7 | constructor() { |
| 8 | const ledDiv = document.querySelector("#leds"); |
| 9 | let canvas = document.createElement("canvas"); |
| 10 | canvas.style.width = "100%"; |
| 11 | canvas.style.height = "100%"; |
| 12 | canvas.width = CanvasRenderer.WIDTH; |
| 13 | canvas.height = CanvasRenderer.HEIGHT; |
| 14 | ledDiv.appendChild(canvas); |
| 15 | ledDiv.style.backgroundColor = "#00000000"; |
| 16 | let context = canvas.getContext('2d'); |
| 17 | |
| 18 | this.canvas = canvas; |
| 19 | this.context = context; |
| 20 | } |
| 21 | |
| 22 | render(animation) { |
| 23 | const canvas = this.canvas; |
| 24 | const context = this.context; |
| 25 | const leds = animation.leds; |
| 26 | const nx = animation.nx; |
| 27 | const ny = animation.ny; |
| 28 | |
| 29 | const xoff = CanvasRenderer.WIDTH / (nx + 1); |
| 30 | const yoff = CanvasRenderer.HEIGHT / (ny + 1); |
| 31 | const d = xoff * 0.7; |
| 32 | |
| 33 | context.clearRect(0, 0, canvas.width, canvas.height); |
| 34 | for (let x = 0; x < nx; x++) { |
| 35 | for (let y = 0; y < ny; y++) { |
| 36 | const cx = (x + 1) * xoff |
| 37 | const cy = (y + 1) * yoff |
| 38 | |
| 39 | const rgb = leds[x][y]; |
| 40 | const r = Math.max(rgb[0] * 256, 0x1a); |
| 41 | const g = Math.max(rgb[1] * 256, 0x16); |
| 42 | const b = Math.max(rgb[2] * 256, 0x22); |
| 43 | const color = `rgba(${r}, ${g}, ${b})`; |
| 44 | |
| 45 | context.beginPath(); |
| 46 | context.arc(cx, cy, d/2, 0, 2 * Math.PI, false); |
| 47 | context.fillStyle = color; |
| 48 | context.fill(); |
| 49 | } |
| 50 | } |
| 51 | } |
| 52 | } |
| 53 | |
| 54 | window.addEventListener("load", () => { |
| 55 | const animationClass = animations[Math.floor(Math.random() * animations.length)]; |
| 56 | console.log(`Picked LED animation: ${animationClass.name}`); |
| 57 | |
| 58 | let renderer = new CanvasRenderer(); |
| 59 | let animation = new animationClass(16, 16); |
| 60 | |
| 61 | let step = (hrts) => { |
| 62 | // Run animation logic. |
| 63 | animation.draw(hrts / 1000); |
| 64 | |
| 65 | // Draw LEDs. |
| 66 | renderer.render(animation); |
| 67 | |
| 68 | // Schedule next frame. |
| 69 | window.requestAnimationFrame(step); |
| 70 | } |
| 71 | window.requestAnimationFrame(step); |
| 72 | }); |