使粒子以水平8形状行进

时间:2015-06-05 11:31:49

标签: javascript html css canvas particles

我现在正试图让粒子沿着水平方向移动,这就像"∞"。

我只能通过跟随this tutorial使粒子绕圈行进。

但我不知道如何让它以水平8字形行进。

这是我的代码:



var cvs = document.createElement('canvas'),
    context = cvs.getContext("2d");
document.body.appendChild(cvs);

var numDots = 200,
  n = numDots,
  currDot,
  maxRad = 250,
  minRad = 150,
  radDiff = maxRad - minRad,
  dots = [],
  PI = Math.PI,
  centerPt = {
    x: 0,
    y: 0
  };

resizeHandler();
window.onresize = resizeHandler;

while (n--) {
  currDot = {};
  currDot.radius = minRad + Math.random() * radDiff;
  currDot.ang = (1 - Math.random() * 2) * PI;
  currDot.speed = (1 - Math.random() * 2) * 0.025;
  currDot.intensity = Math.round(Math.random() * 255);
  currDot.fillColor = "rgb(" + currDot.intensity + "," + currDot.intensity + "," + currDot.intensity + ")";
  dots.push(currDot);
}

function drawPoints() {
  n = numDots;
  var _centerPt = centerPt,
    _context = context,
    dX = 0,
    dY = 0;

  _context.clearRect(0, 0, cvs.width, cvs.height);

  //draw dots
  while (n--) {
    currDot = dots[n];
    dX = _centerPt.x + Math.sin(currDot.ang) * currDot.radius;
    dY = _centerPt.y + Math.cos(currDot.ang) * currDot.radius;

    currDot.ang += currDot.speed;

    //console.log(currDot);
    _context.fillStyle = currDot.fillColor;
    _context.fillRect(dX, dY, 10, 10);

  } //draw dot
  window.requestAnimationFrame(drawPoints);
}

function resizeHandler() {
  var box = cvs.getBoundingClientRect();
  var w = box.width;
  var h = box.height;
  cvs.width = w;
  cvs.height = h;
  centerPt.x = Math.round(w / 4);
  centerPt.y = Math.round(h / 2);
}

drawPoints();

body,
html {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}
canvas {
  position: absolute;
  width: 100%;
  height: 100%;
  background: #000000;
}

<canvas></canvas>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

您可以使用不同半径和不同速度的余弦和正弦值:

对于“永恒”符号(∞),余弦与正弦之间的关系为1:2。半径也更像是椭圆形而不是圆形,但不一定是相同的关系。 1:1.5通常效果更好:

x = centerX + radiusX * Math.cos(angle)
y = centerY + radiusY * Math.sin(angle * 2);

实施例

var cx = 200, cy = 75,                          // center of path
    rx = 150, ry = 50,                          // radius for x and y
    angleStep = 0.05,                           // "speed"
    angle = 0,                                  // current angle
    o = document.querySelector("div").style;    // object to move (demo)

(function loop() {

  var x = cx + rx * Math.cos(angle),
      y = cy + ry * Math.sin(angle * 2);
  
  o.transform = o.webkitTransform = "translate(" + x + "px," + y + "px)";
  
  angle += angleStep;
  angle = angle % (2*Math.PI);
  
  requestAnimationFrame(loop)
})();
div {border-radius:50%;background:#78f;width:20px;height:20px}
<div></div>