基于滚动控制速度/深度(z轴)

时间:2019-01-29 18:43:25

标签: javascript html5-canvas

我正在开发一个CodePen,它可以生成从中心点向外弯曲的星星。我还有一些JS跟踪滚动速度,您可以在控制台中看到输出:https://codepen.io/steven-bell/pen/RvGKOR

/* THIS IS THE SCROLL CHECK CODE THAT PRINTS SCROLL SPEED IN CONSOLE */

$(window).on('scroll', function() {
    console.log( $(this).scrollTop() );
});

/* END OF SCROLL CHECK CODE */

var canvas = document.getElementById("canvas");
var flr = Math.floor;

canvas.width = canvas.offsetWidth;
canvas.height = canvas.offsetHeight;

var halfw = canvas.width / 2,
  halfh = canvas.height / 2,
  step = 2,
  warpZ = 12,
  speed = 0.025;

var ctx = canvas.getContext("2d");

ctx.fillStyle = "black";
ctx.fillRect(0, 0, canvas.width, canvas.height);

function rnd(num1, num2) {
  return flr(Math.random() * num2 * 2) + num1;
}

function getColor() {
  return "hsla(200,100%, " + rnd(50, 100) + "%, 1)";
}

var star = function() {
  var v = vec3.fromValues(
    rnd(0 - halfw, halfw),
    rnd(0 - halfh, halfh),
    rnd(1, warpZ)
  );

  this.x = v[0];
  this.y = v[1];
  this.z = v[2];
  this.color = getColor();

  this.reset = function() {
    v = vec3.fromValues(
      rnd(0 - halfw, halfw),
      rnd(0 - halfh, halfh),
      rnd(1, warpZ)
    );

    this.x = v[0];
    this.y = v[1];
    this.color = getColor();
    vel = this.calcVel();
  };

  this.calcVel = function() {
    return vec3.fromValues(0, 0, 0 - speed);
  };

  var vel = this.calcVel();

  this.draw = function() {
    vel = this.calcVel();
    v = vec3.add(vec3.create(), v, vel);
    var x = v[0] / v[2];
    var y = v[1] / v[2];
    var x2 = v[0] / (v[2] + speed * 0.5);
    var y2 = v[1] / (v[2] + speed * 0.5);

    ctx.strokeStyle = this.color;
    ctx.beginPath();
    ctx.moveTo(x, y);
    ctx.lineTo(x2, y2);
    ctx.stroke();

    if (x < 0 - halfw || x > halfw || y < 0 - halfh || y > halfh) {
      this.reset();
    }
  };
};

var starfield = function() {
  var numOfStars = 250;

  var stars = [];

  function _init() {
    for (var i = 0, len = numOfStars; i < len; i++) {
      stars.push(new star());
    }
  }

  _init();

  this.draw = function() {
    ctx.translate(halfw, halfh);

    for (var i = 0, len = stars.length; i < len; i++) {
      var currentStar = stars[i];

      currentStar.draw();
    }
  };
};

var mStarField = new starfield();

function draw() {
  // make 5 seconds
  var millSeconds = 1000 * 10;

  speed = 0.025;

  ctx.setTransform(1, 0, 0, 1, 0, 0);
  ctx.fillStyle = "rgba(0,0,0,0.2)";
  ctx.fillRect(0, 0, canvas.width, canvas.height);

  mStarField.draw();

  window.requestAnimationFrame(draw);
}

draw();

window.onresize = function() {
  canvas.width = canvas.offsetWidth;
  canvas.height = canvas.offsetHeight;

  halfw = canvas.width / 2;
  halfh = canvas.height / 2;
};

我试图弄清楚如何基于滚动来控制星星运动。基本上在向下滚动时移出,或者在向上滚动时反向移。

我认为我可以将控制台输出中显示的内容添加为“速度”,但这似乎不起作用。

任何想法表示赞赏

0 个答案:

没有答案