javascript - 骑行星空动画

标签 javascript animation canvas

我用 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/

相关文章:

javascript - 附加到元素的脚本标记会在 .append() 之后的下一行之前运行吗?

html - 为容器内的 div 绝对位置设置动画的有效方法

javascript - 按背景颜色剪辑文本

python - 如何使 tkinter Canvas 背景透明?

android - 如何为 TextView 的每个字符设置阴影/发光效果

javascript - 在路径表面外绘制轮廓

javascript - 如何使用 ramda 获取对象中的所有值

iphone - 通过第一响应者更改保持 iPhone 键盘对齐的工具栏可见?

java - 不断收到错误 "Component must be displayable"

javascript - 尝试将 getDate() 包含在 var 中