You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Canvas绘制从右上角到左下角无限滚动的反向正弦波

解决方案

核心改动点

  • 修正了原代码中lineTo参数x/y顺序颠倒的错误
  • 新增右上到左下的斜向基准线计算,基准线公式为y = -x + canvas.height
  • 将正弦波动值叠加到基准线的Y坐标上,调整相位增量实现沿斜向无限滚动的效果
  • 适配窗口resize逻辑,避免窗口大小变化后波浪显示异常

完整可运行代码

<div>
  <canvas class="canvas"></canvas>
</div>
body {
  margin: 0;
  padding: 0;
}
const canvas = document.querySelector(".canvas");
const ctx = canvas.getContext("2d");

// 初始化画布尺寸
function resizeCanvas() {
  canvas.width = window.innerWidth - 5;
  canvas.height = window.innerHeight - 5;
}
resizeCanvas();
window.addEventListener("resize", resizeCanvas);

const wave = {
  length: 0.01, // 波长,数值越小单个波浪长度越长
  amplitude: 80, // 振幅,数值越大波浪起伏高度越高
  frequency: 0.02, // 滚动速度,数值越大波浪滚动速度越快
};

let increment = 0;

function animate() {
  requestAnimationFrame(animate);
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  ctx.beginPath();
  // 遍历所有x坐标计算对应波浪y值
  for (let x = 0; x < canvas.width; x++) {
    // 计算右上到左下基准线的y坐标
    const baseY = -x + canvas.height;
    // 叠加正弦波动偏移
    const y = baseY + Math.sin(x * wave.length + increment) * wave.amplitude;
    x === 0 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
  }
  ctx.strokeStyle = '#000';
  ctx.lineWidth = 2;
  ctx.stroke();
  // 更新相位实现滚动效果
  increment += wave.frequency;
}

animate();

参数调整说明

  • 修改wave.amplitude数值可调整波浪的起伏高度
  • 修改wave.length数值可调整单个波浪的长度
  • 修改wave.frequency数值可调整波浪滚动的速度

内容的提问来源于stack exchange,提问作者Un Jin Jang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 04:15:06