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

使用Two.js绘制抛物线异常:仅显示两条直线的问题排查

问题:Two.js绘制抛物线仅显示两条直线,如何修复?

我希望使用Two.js库绘制一条从左端起始、向右展开的抛物线,但实际仅显示两条直线。请问是数学公式有误,还是路径处理存在问题?

原代码

JS代码

// Create a Two.js instance
var two = new Two({
  width: 300,
  height: 300
}).appendTo(document.getElementById("parabola"));

var path = two.makePath(0, two.height / 2);

path.stroke = "#000";
path.linewidth = 3;

for (var i = 0; i < two.width; i++) {
  var x = i;
  var y = Math.pow((x - two.width / 2), 2) / (2 * 50) + two.height / 2;
  console.log(`x: ${x} and y: ${y}`);
  path.vertices.push(new Two.Vector(x, y));
}

two.update();

HTML代码

<script src="https://cdnjs.cloudflare.com/ajax/libs/two.js/0.8.10/two.min.js"></script>
<div id="parabola"></div>

问题分析与修复

你的数学公式没有问题,抛物线的计算逻辑是正确的。问题出在Two.js的路径构建机制上:

  • two.makePath()创建路径后,直接向path.vertices数组push顶点不会自动生成连接这些顶点的线段指令,Two.js的路径依赖内部commands数组定义绘制规则,单纯添加顶点不会触发指令更新,最终只有初始点和最后一个顶点被连接,看起来像两条直线。

修复方案1:提前生成所有顶点,一次性传入makePath

先计算出抛物线的所有顶点坐标,再作为参数传入two.makePath(),Two.js会自动生成完整的线段指令:

var two = new Two({
  width: 300,
  height: 300
}).appendTo(document.getElementById("parabola"));

// 提前计算所有顶点
var vertices = [];
for (var i = 0; i < two.width; i++) {
  var x = i;
  var y = Math.pow((x - two.width / 2), 2) / (2 * 50) + two.height / 2;
  vertices.push(x, y);
}

// 一次性创建路径
var path = two.makePath(vertices);
path.stroke = "#000";
path.linewidth = 3;

two.update();

修复方案2:使用lineTo方法添加线段

在循环中使用path.lineTo(x, y)添加路径段,这个方法会自动更新commands数组,生成正确的连接线段:

var two = new Two({
  width: 300,
  height: 300
}).appendTo(document.getElementById("parabola"));

var path = two.makePath(0, two.height / 2);
path.stroke = "#000";
path.linewidth = 3;

for (var i = 1; i < two.width; i++) { // 从1开始避免重复初始点
  var x = i;
  var y = Math.pow((x - two.width / 2), 2) / (2 * 50) + two.height / 2;
  path.lineTo(x, y);
}

two.update();

两种方案都能正确绘制出预期的抛物线,可根据需求选择使用。

内容的提问来源于stack exchange,提问作者Real Noob

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 05:39:52