来自 bezier.js 的代码对于我检查过的所有其他示例都非常有效。 除了这个:
const controlPoints = [450,50,300,183,150,150];
const line = { p1: {x: 400, y: 0}, p2: {x: 400, y: 100} }
const intersectionPoints = [];
const bezierCurve = new Bezier(x1,x2,c1,c2,y1,y2);
console.log(x1,x2,c1,c2,y1,y2);
const intersections = bezierCurve.lineIntersects(line);
if (intersections.length > 0) {
for (let e = 0; e < intersections.length; e++) {
let n = intersections[e],
t = bezierCurve.get(n);
intersectionPoints.push(t);
}
}
console.log("Intersection Points:", intersectionPoints);
return intersectionPoints;
它不返回交点。虽然肯定有一个在:{x: 400, y: 90/95 }
我期待贝塞尔曲线和指定线之间的交点。
这似乎是底层 bezier.js 库中的一个错误,与垂直线相交时有时会不返回交集。这可以在这个 Github 问题中看到:https://github.com/Pomax/bezierjs/issues/205
当您尝试找到与稍微旋转的线(例如
const line = { p1: { x: 400, y: 0 }, p2: { x: 400.01, y: 100 } }
)的交点时,它将按预期工作。
function demo() {
const controlPoints = [450, 50, 300, 183, 150, 150];
const line = {
p1: {
x: 400,
y: 0
},
p2: {
x: 400.001,
y: 100
}
};
const intersectionPoints = [];
const [x1, x2, c1, c2, y1, y2] = controlPoints;
const bezierCurve = new Bezier(x1, x2, Math.floor(c1), Math.floor(c2), y1, y2);
const intersections = bezierCurve.lineIntersects(line);
if (intersections.length > 0) {
for (let e = 0; e < intersections.length; e++) {
let n = intersections[e],
t = bezierCurve.get(n);
intersectionPoints.push(t);
}
}
console.log("Intersection Points:", intersectionPoints);
}
document.addEventListener("readystatechange", () => document.readyState === "complete" && demo());
<script type="module">
import { Bezier } from 'https://cdn.jsdelivr.net/npm/[email protected]/src/bezier.min.js';
window.Bezier = Bezier;
</script>