|
| 1 | +var canvas = document.getElementById("canvas"); |
| 2 | +var context = canvas.getContext("2d"); |
| 3 | + |
| 4 | +// frames per second |
| 5 | +const FPS = 30; |
| 6 | +// size of dots (in pixels) |
| 7 | +const DOTSIZE = 20; |
| 8 | +// number of dots to add |
| 9 | +const DOTCOUNT = 100; |
| 10 | + |
| 11 | +// list of all the dots in the canvas |
| 12 | +var dots = []; |
| 13 | + |
| 14 | +// set the size of the canvas to the viewport width |
| 15 | +// and height |
| 16 | +function setSize() { |
| 17 | + console.log("setting the canvas size"); |
| 18 | + canvas.width = window.innerWidth; |
| 19 | + context.canvas.width = window.innerWidth; |
| 20 | + canvas.height = window.innerHeight; |
| 21 | + context.canvas.height = window.innerHeight; |
| 22 | +} |
| 23 | + |
| 24 | +window.addEventListener("resize", (_) => setSize()); |
| 25 | +setSize(); |
| 26 | + |
| 27 | +function getRandomPos(max) { |
| 28 | + return Math.floor(Math.random() * max); |
| 29 | +} |
| 30 | + |
| 31 | +function getRandomVel() { |
| 32 | + var positive = Math.random(); |
| 33 | + if (positive >= 0.5) { |
| 34 | + return Math.random(); |
| 35 | + } else { |
| 36 | + return Math.random() * -1; |
| 37 | + } |
| 38 | +} |
| 39 | + |
| 40 | +function animate() { |
| 41 | + setTimeout(function () { |
| 42 | + requestAnimationFrame(animate); |
| 43 | + console.log("animate"); |
| 44 | + |
| 45 | + if (dots.length === 0) { |
| 46 | + for (let i = 0; i < DOTCOUNT; i++) { |
| 47 | + dots.push({ |
| 48 | + x: getRandomPos(context.canvas.width - DOTSIZE), |
| 49 | + y: getRandomPos(context.canvas.height - DOTSIZE), |
| 50 | + vx: getRandomVel(), |
| 51 | + vy: getRandomVel(), |
| 52 | + }); |
| 53 | + } |
| 54 | + console.log(dots); |
| 55 | + } else { |
| 56 | + context.fillStyle = "white"; |
| 57 | + context.strokeStyle = "white"; |
| 58 | + context.lineWidth = 0.5; |
| 59 | + context.clearRect(0, 0, context.canvas.width, context.canvas.height); |
| 60 | + |
| 61 | + for (let i = 0; i < DOTCOUNT; i++) { |
| 62 | + dots[i].x += dots[i].vx; |
| 63 | + dots[i].y += dots[i].vy; |
| 64 | + |
| 65 | + context.fillRect(dots[i].x, dots[i].y, DOTSIZE, DOTSIZE); |
| 66 | + } |
| 67 | + } |
| 68 | + }, 1000 / FPS); |
| 69 | +} |
| 70 | + |
| 71 | +requestAnimationFrame(animate); |
0 commit comments