javascript - 从右上角到左下角绘制正弦波
问题描述
我正在尝试使用画布设计一个小项目,我想设计一个正弦波,以便尽可能从右上角到左下角无限生成波。
类似于反正弦图的东西。
我所能做的就是让正弦波从左到右,但是从右上到左下进行这项工作是非常困难的。
这是我目前的代码
看起来很悲伤...
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 参数进行更改。
推荐阅读
- android - 如何强制 expo 应用程序更新
- ios - UIApplicationShortcutIcon 只能使用主包中的图像吗?
- eclipse - Eclipse 未打开,NoSuchFieldError: useDarkestDarkColors
- javascript - 表单字段数据的实时计算未插入数据库
- google-apps-script - Google Apps 脚本 - 在 Google 幻灯片表格中插入图像
- facebook - Facebook 用户 ID 问题
- templates - 我的 pug 模板文件中的访问窗口(全局变量)
- ios - 如何打印 SFSafariViewController 完整网页?
- r - 向与 ggmap 一起使用的数据添加一列
- oracle - 使用 sum 和 nvl 函数更新语句很慢