从右上到左下绘制正弦波

Drawing a sine wave from top right to bottom left

我正在尝试使用 canvas 设计一个小项目,我想设计一个正弦波,如果可能的话,波从右上角到左下角无限生成.

有点像反正弦图。

我所能做的就是让正弦波从左到右,但是让这个工作从右上到左下是非常困难的。

这是我目前的代码

看起来很难过...

const canvas = document.querySelector(".canvas");
const ctx = canvas.getContext("2d");

canvas.width = window.innerWidth - 5;
canvas.height = window.innerHeight - 5;

window.addEventListener("resize", () => {
  canvas.width = window.innerWidth;
  canvas.height = window.innerHeight;
});

const wave = {
  y: canvas.height / 2,
  length: 0.02,
  amplitude: 100,
  frequency: 0.01,
  yOffSet: canvas.height,
};

let increment = wave.frequency;

function animate() {
  requestAnimationFrame(animate);
  ctx.fillStyle = "rgb(0,0,0)";
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  ctx.moveTo(0, canvas.height);
  for (let i = 0; i < canvas.width; i++) {
    ctx.lineTo(Math.sin(i / wave.length + increment) * wave.amplitude + wave.yOffSet, 0);
  }
  ctx.stroke();
  increment += wave.frequency;
}

animate();
body {
  margin: 0;
  padding: 0;
}
<div>
  <canvas class="canvas"></canvas>
</div>

期望的输出

问题出在这一行:

ctx.lineTo(Math.sin(i / wave.length + increment) * wave.amplitude + wave.yOffSet, 0);

您只是在 x 坐标上移动。 为了清楚起见,我在 y 坐标中添加了运动并重写了三行。

    x=i+wave.amplitude*Math.sin(i/wave.length);
    y=canvas.height-(i-(wave. amplitude * Math.sin(i/wave.length)));
    ctx.lineTo(x,y);

如果我理解正确的话,它产生的结果就像你描述的那样。波浪比图中显示的要多得多,但可以通过 wave.length 参数进行调整。