【发布时间】:2022-01-26 17:14:09
【问题描述】:
我正在尝试移植此草图:https://codepen.io/giorgiomartini/pen/JjrOVXq?editors=1010,它使用类似的库:https://cdn.rawgit.com/ironwallaby/delaunay/master/delaunay.js,但我只得到一个三角形。
这是我的代码:https://github.com/GiorgioRemindme/giorgio-martini/blob/main/src/sketches/tris.js
我认为这是有问题的部分:
for (let i = 0; i < triangulation.triangles.length; i += 3) {
triangles.push(new Triangle(
pts[triangulation.triangles[i]],
pts[triangulation.triangles[i + 1]],
pts[triangulation.triangles[i + 2]]
))
}
但是,它只渲染一个三角形,而在 codepen 中它会渲染所有三角形。
这是初始化函数:
function initializeTriangulation() {
triangles = [];
let pts = [];
// push canvas rect points
pts.push(p5.createVector(0, 0))
pts.push(p5.createVector(p5.width, 0))
pts.push(p5.createVector(p5.width, p5.height))
pts.push(p5.createVector(0, p5.height))
// add a certain nb of pts proportionally to the size of the canvas
// ~~ truncates a floating point number and keeps the integer part, like floor()
var n = 2
for (let i = 0; i < n; i++) {
pts.push(p5.createVector(~~p5.random(p5.width), ~~p5.random(p5.height)))
}
// Now, let's use Delaunay.js
// Delaunay.triangulate expect a list of vertices (which should be a bunch of two-element arrays, representing 2D Euclidean points)
// and it will return you a giant array, arranged in triplets, representing triangles by indices into the passed array
// Array.map function let's us create an Array of 2 elements arrays [ [x,y],[x,y],..] from our array of PVector [ PVector(x,y), PVector(x,y), ... ]
let delunaySource = pts.map(pt => [pt.x, pt.y]).flat(Infinity)
console.log({delunaySource})
const triangulation = new Delaunator(delunaySource)
console.log({triangulation})
//create Triangles object using indices returned by Delaunay.triangulate
for (let i = 0; i < triangulation.triangles.length; i += 3) {
triangles.push(new Triangle(
pts[triangulation.triangles[i]],
pts[triangulation.triangles[i + 1]],
pts[triangulation.triangles[i + 2]]
))
}
}
有什么想法可能出在哪里吗?
谢谢。
【问题讨论】: