我用 javascript 制作了这个星空动画。我只是不确定让它从另一边循环播放相同动画的最佳方法。我喜欢让星星从 Canvas 的一侧滚动到另一侧。
var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
stars = [];
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 500, 500);
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function getSpeed(depth) {
switch (depth / 2) {
case 0:
return 6;
case 1:
return 5;
case 2:
return 4;
case 3:
return 3;
case 4:
return 2;
case 5:
return 1;
}
}
var i;
for (i = 0; i < 2000; i++) {
var star = {
x: 0,
y: 0,
z: 0,
v: 0
};
star.x = getRandomInt(0, 500);
star.y = getRandomInt(0, 500);
star.z = getRandomInt(0, 5) * 2;
star.v = getSpeed(star.z);
stars.push(star);
}
function animation() {
//clears background
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 500, 500);
// populates space with stars
for (i = 0; i < 2000; i++) {
ctx.fillStyle = "rgb(" + (256 / stars[i].z) + "," + (256 / stars[i].z) + "," + (256 / stars[i].z) + ")";
ctx.fillRect(stars[i].x, stars[i].y, 2, 2);
stars[i].x += stars[i].v;
}
setTimeout(animation, 33);
}
animation();
<canvas id="myCanvas"></canvas>
最佳答案
当它降到零以下时,只需重置 x 值。
if (star.x < 0) star.x = canvasWidth;
我做了一些其他的改变,比较一下。
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function StarField(ctx, numStars, width, height) {
var stars = new Array(numStars).fill(null).map(getStar);
function getStar() {
var z = getRandomInt(0, 5),
c = (256 / z).toString(16);
return {
x: getRandomInt(0, width),
y: getRandomInt(0, height),
z: z * 2,
v: 6 - z,
c: "#" + c + c + c
};
}
this.animate = function () {
var i, s;
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, width, height);
for (i = 0; i < numStars; i++) {
s = stars[i];
ctx.fillStyle = s.c;
ctx.fillRect(s.x, s.y, 2, 2);
s.x -= s.v;
if (s.x < 0) s.x = width;
}
setTimeout(this.animate.bind(this), 32);
};
}
var canvas = document.getElementById("myCanvas");
var s = new StarField(canvas.getContext("2d"), 2000, 500, 500);
s.animate();
<canvas id="myCanvas"></canvas>
关于javascript - 骑行星空动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43165377/