Last active
December 31, 2023 13:20
-
-
Save duyixian1234/4fb58f3f4e9b60c64b99b4b24c7777ef to your computer and use it in GitHub Desktop.
firework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <meta charset="UTF-8" /> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0" /> | |
| <title>firework</title> | |
| <script src="script.js"></script> | |
| </head> | |
| <body> | |
| <canvas id="canvas"></canvas> | |
| </body> | |
| </html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // Get the canvas element | |
| const canvas = document.getElementById("canvas"); | |
| const ctx = canvas.getContext("2d"); | |
| // Set the canvas size | |
| canvas.width = window.innerWidth; | |
| canvas.height = window.innerHeight; | |
| // Function to create a firework | |
| function createFirework() { | |
| const firework = { | |
| x: Math.random() * canvas.width, | |
| y: canvas.height, | |
| color: `rgb(${Math.random() * 255}, ${Math.random() * 255}, ${ | |
| Math.random() * 255 | |
| })`, | |
| radius: Math.random() * 3 + 1, | |
| velocity: { | |
| x: Math.random() * 6 - 3, | |
| y: Math.random() * 3 + 1, | |
| }, | |
| gravity: 0.05, | |
| opacity: 1, | |
| }; | |
| // Update the firework | |
| firework.update = function () { | |
| firework.velocity.y += firework.gravity; | |
| firework.x += firework.velocity.x; | |
| firework.y += firework.velocity.y; | |
| firework.opacity -= 0.01; | |
| // Draw the firework | |
| ctx.beginPath(); | |
| ctx.arc(firework.x, firework.y, firework.radius, 0, Math.PI * 2); | |
| ctx.fillStyle = firework.color; | |
| ctx.globalAlpha = firework.opacity; | |
| ctx.fill(); | |
| }; | |
| return firework; | |
| } | |
| // Array to store the fireworks | |
| const fireworks = []; | |
| // Function to animate the fireworks | |
| function animate() { | |
| ctx.clearRect(0, 0, canvas.width, canvas.height); | |
| // Create new fireworks randomly | |
| if (Math.random() < 0.05) { | |
| fireworks.push(createFirework()); | |
| } | |
| // Update and draw the fireworks | |
| fireworks.forEach((firework, index) => { | |
| firework.update(); | |
| // Remove faded fireworks from the array | |
| if (firework.opacity <= 0) { | |
| fireworks.splice(index, 1); | |
| } | |
| }); | |
| requestAnimationFrame(animate); | |
| } | |
| // Start the animation | |
| animate(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment