Skip to content

Instantly share code, notes, and snippets.

@sun0225SUN
Created July 25, 2023 07:06
Show Gist options
  • Save sun0225SUN/8b840dd37238fa0c5fc05e3e44b71f6b to your computer and use it in GitHub Desktop.
Save sun0225SUN/8b840dd37238fa0c5fc05e3e44b71f6b to your computer and use it in GitHub Desktop.
Star Trail
<canvas></canvas>
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);
* {
margin: 0px;
padding: 0px;
overflow: hidden;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment