动画 Javascript 画布线,具有代表互联网流量的随机幅度

问题描述 投票:0回答:1

如何在屏幕截图中实现这些动画线条?它们应该是无穷无尽的

screenshot

我尝试这样做,但结果只是一个遵循可预测轨迹的正弦波,但我需要一个随机轨迹

const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

let xOffset = 0;
const frequency = 0.02;
const speed = 2;

function animate() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);

  ctx.beginPath();
  ctx.moveTo(0, canvas.height / 2);

  for (let x = 0; x < canvas.width; x++) {
    let currentAmplitude = (x / canvas.width) * 100;
    let y = canvas.height / 2 + Math.sin((x + xOffset) * frequency) * currentAmplitude;
    ctx.lineTo(x, y);
  }

  ctx.strokeStyle = '#000';
  ctx.lineWidth = 2;
  ctx.stroke();

  xOffset += speed;

  requestAnimationFrame(animate);
}

animate();
canvas {
  display: block;
  margin: 0 auto;
  background-color: #f0f0f0;
}
<canvas id="myCanvas" width="800" height="400"></canvas>

javascript animation canvas
1个回答
0
投票

您可以查看柏林噪声来创建不会到处传播的随机信号。您必须稍微调整一下变量才能获得您喜欢的不同信号形状。

这是一个例子,仅使用我在谷歌上找到的第一个柏林噪声片段

for (const canvas of document.querySelectorAll("canvas")) {
  const bumpyness = 4 + Math.random() * 4;
  const seed = Math.random() * canvas.width;
  const ctx = canvas.getContext('2d');

 
  let i = 0;
  const Point = () => (perlin.get(seed + i++ / canvas.width * bumpyness, 1) + 1) / 2 * canvas.height;

  const points = Array.from({ length: canvas.width }, Point);

  function animate(dt) {
    ctx.clearRect(0, 0, canvas.width, canvas.height);

    ctx.beginPath();
    ctx.moveTo(0, points[0]);

    points.push(Point());
    points.shift();

    for (let x = 1; x < points.length; x++) {
      const y = points[x];
      ctx.lineTo(x, y);
    }

    ctx.strokeStyle = '#000';
    ctx.lineWidth = 2;
    ctx.stroke();


    requestAnimationFrame(animate);
  }

  animate();
}
canvas {
  display: block;
  margin: .5rem;
  background-color: #f0f0f0;
}
<script src='http://joeiddon.github.io/perlin/perlin.js'></script>
<canvas id="myCanvas" width="200" height="60"></canvas>
<canvas id="myCanvas" width="200" height="60"></canvas>
<canvas id="myCanvas" width="200" height="60"></canvas>

© www.soinside.com 2019 - 2024. All rights reserved.