首页 > 解决方案 > 从右上角到左下角绘制正弦波

问题描述

我正在尝试使用画布设计一个小项目,我想设计一个正弦波,以便尽可能从右上角到左下角无限生成波。

类似于反正弦图的东西。

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

这是我目前的代码

看起来很悲伤...

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>

期望的输出
我的目标

标签: javascriptcanvashtml5-canvas

解决方案


问题出在这一行:

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 参数进行更改。


推荐阅读