Konva – path point simplification with Simplify.js

Free-drawn lines can be represented on the Konva stage by the Line or Path shapes. Standard UX is that the user moves the pointer and we add a line point at the pointer position in each mouse-move event.

This can lead to a huge number of points being recorded. That in turn leads to a lot of overhead for the line to be redrawn on any stage redraw, which can hurt the success of your project.

It would be better to simplify the points, so that say any points that happen to be in a straight line can be simplified to a start and end point alone, since we do not require the intermediate points in order to draw the line segment the user intended.

This is what simplify.js does for us – we give it an array of plain JS objects formed as {x: xPos, y: yPos} and it filters out the unneeded points.

The result it a simplified list of points. The quantity of points reduced depends on how ‘curvy’ the line is – a mostly straight line segment can be simplified tremendously, and a curvy line less so. Regardless, the reduction is worth the small effort of the extra simplification process as can be witnessed in the image above where we simplify from 180 raw points to 54 – almost a factor of 3 reduction. The demo code is below.

Summary

Using a lib like simplify.js can help us reduce the number of points in a hand-drawn line and so increase the performance of stage redraws, and ultimately the UX of our app.

Thanks for reading.

VW May 2022.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: