I'm trying to simplify a hand-drawn path using paper.js' excellent path.simplify method to generate smooth curves after the user finishes drawing. As this is for a non HTML output (TV Telestration) I'm trying to create a microservice in nodejs to take the points and output the control points of the resulting simplified curves.
I tried using paper-jsdom and the method works and doesn't complain but always outputs a single segment with zero coords in all points. I wonder if I'm supposed to be using paper-jsdom-canvas instead to get the appropriate output.
Here is the node module I'm trying to build:
const Path = require('paper').Path
const Point = require('paper').Point
const Project = require('paper').Project
// the next line produces side effects without which
// the code will not run, but I'm not sure this is the way to go.
let p = new Project()
function simplify (points) {
let pts = []
for (let point in points) {
let pt = new Point(point.x, point.y)
pts.push(pt)
}
let path = new Path({
segments: pts,
strokeColor: 'black',
fullySelected: false
})
path.simplify(10)
let simplePath = []
for (const segment of path.segments) {
// only one segment reaches this point
// with all zeros in all the parameters
console.log(segment.path)
simplePath.push(
{
handleIn: { x: segment.handleIn.x, y: segment.handleIn.y },
handleOut: { x: segment.handleOut.x, y: segment.handleOut.y },
point: { x: segment.point.x, y: segment.point.y }
})
console.log(`
hi : (${segment.handleIn.x}, ${segment.handleIn.y})
ho : (${segment.handleOut.x}, ${segment.handleOut.y})
point: (${segment.point.x}, ${segment.point.y})`)
}
return simplePath
}
module.exports = simplify
I think that your error is here:
for (let point in points) {
let pt = new Point(point.x, point.y);
pts.push(pt);
}
If, as I think, the variable points
contains an array of objects, you should instead use:
for (let point of points) {
let pt = new Point(point.x, point.y);
pts.push(pt);
}
Note the keyword of
replacing in
in the for loop.
You are actually looping over the keys and not the values.