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

p5.js中拉伸正弦图像且保留分辨率、解决卡顿的方法咨询

优化方案说明

卡顿原因

  • 每次draw()执行时都会循环创建800个新的createPoint实例,频繁的对象创建和内存回收会造成性能损耗
  • 额外绘制4个遮挡矩形增加了不必要的渲染开销
  • 固定800次循环包含了大量超出画布范围的无效点位计算

需求实现思路(不改变点位x坐标前提下拉伸线条)

  • x坐标固定生成:在setup阶段就初始化所有点位的x坐标,后续运行过程中永远不修改x值
  • 横向拉伸:仅调整正弦函数的输入系数,不修改点位x坐标,实现波形疏密变化的拉伸效果
  • 纵向拉伸:调整正弦值的放大系数,仅修改点位y坐标,不影响x值

优化后代码

JS代码

let slidery;
let sliderx;
const width_ = 800;
const height_ = 400;
const xStart = 50;
const xEnd = width_ - 50;
// 有效x坐标范围内的总点数
const pointCount = xEnd - xStart;
// 存储点位的数组
const points = [];

function setup() {
  createCanvas(width_, height_);
  // 创建纵向拉伸控制滑块
  slidery = createSlider(0, 100, 50);
  slidery.position(10, 10);
  slidery.style('width', '200px');
  // 创建横向拉伸控制滑块,仅调整正弦输入系数,不修改x坐标
  sliderx = createSlider(1, 100, 10);
  sliderx.position(250, 10);
  sliderx.style('width', '200px');

  // 初始化所有点位,x坐标固定,后续永远不修改
  for (let i = 0; i < pointCount; i++) {
    points[i] = {
      x: xStart + i,
      y: height_ / 2
    }
  }
}

function draw() {
  const yScale = slidery.value();
  const xScale = sliderx.value() / 100;
  background(220);

  // 绘制坐标轴
  stroke(0);
  line(xStart, height_ / 2, xEnd, height_ / 2);
  line(xStart, 50, xStart, height_ - 50);

  // 仅更新所有点的y坐标,不修改x值
  for (let i = 0; i < pointCount; i++) {
    points[i].y = height_ / 2 - sin(i * xScale) * yScale;
  }

  // 连线绘制波形
  stroke(255, 0, 0);
  for (let i = 1; i < pointCount; i++) {
    line(points[i-1].x, points[i-1].y, points[i].x, points[i].y);
  }
}

HTML代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.4.0/p5.js"></script>

内容的提问来源于stack exchange,提问作者theunicornatihascome MLG

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 05:39:03