A Pen by Michelle Li on CodePen.
Created
July 25, 2023 07:06
-
-
Save sun0225SUN/8b840dd37238fa0c5fc05e3e44b71f6b to your computer and use it in GitHub Desktop.
Star Trail
This file contains 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
<canvas></canvas> |
This file contains 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
var canvas = document.querySelector('canvas'); | |
var width = canvas.width = window.innerWidth; | |
var height = canvas.height = window.innerHeight; | |
var ctx = canvas.getContext('2d'); | |
ctx.translate(width/2, height/2); | |
var gradient = ctx.createLinearGradient(0, 0, 0, height); | |
gradient.addColorStop(0, 'darkblue'); | |
gradient.addColorStop(1, 'orange'); | |
ctx.fillStyle = gradient; | |
ctx.fillRect(-(width/2), -(height/2), width, height); | |
function degToRad(degrees) { | |
return degrees * Math.PI / 180; | |
} | |
function rand(min, max) { | |
return Math.floor(Math.random() * (max-min+1)) + (min); | |
} | |
function Star(posX, posY, r, color) { | |
this.posX = posX; | |
this.posY = posY; | |
this.r = r; | |
this.color = color; | |
} | |
Star.prototype.draw = function() { | |
ctx.beginPath(); | |
ctx.fillStyle = this.color; | |
ctx.arc(this.posX, this.posY, this.r, degToRad(0), degToRad(360)); | |
ctx.fill(); | |
} | |
var stars = []; | |
var req; | |
function loop() { | |
while (stars.length < 2250) { | |
var star = new Star( | |
rand(-(width/2), width), | |
rand(-(height/2), height), | |
rand(0, 0.5), | |
'rgb(' + rand(179, 255) + ', ' + rand(100, 255) + ', ' + rand(100, 255) + ')' | |
); | |
stars.push(star); | |
} | |
for (var i = 0; i < stars.length; i++) { | |
stars[i].draw(); | |
} | |
ctx.rotate(degToRad(0.1)); | |
req = requestAnimationFrame(loop); | |
} | |
loop(); | |
//25秒後停止動畫 | |
setTimeout(function(){cancelAnimationFrame(req);}, 25000); |
This file contains 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
* { | |
margin: 0px; | |
padding: 0px; | |
overflow: hidden; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment