I was curious about how to close Konva lines, and I wanted to explore what we can do with lines and animation – here’s where it ended up.
TLDR: this is about closing lines, line tension, and animation. Have a look at the code here.
About Konva.Line
The Konva.Line produces a line on the canvas – we give it some of points by filling up the line.points() array and it draws between them. The mechanism under the covers looks simple – go to the starting point, draw to the next point, repeat until the last point. Job done.
However, the line has some interesting additional capabilities.
Line.closed() & Line.fill()
Closing the line connects the first and last points. But also when a line becomes closed via line.closed(true), then it’s fill color takes effect and the area inside the closed line is filled. Nice.
Line.tension()
As I described, in its basic form the Konva.line gives you a bunch of straight lines between points. But the line’s super-power is that it can be smoothed via the line.tension() property. Set this to a value in the range 0 – 1 and you get smoother lines. Nice.
Line editing
Editing a line is a matter of manipulating the contents of the line.points() array. Rather than an array of (x, y) pairs, this is a simple array which you cab visualize as [x1, y1, x2, y2, x3, y3,…xn, yn].
This is not the easiest format to work with for editing so in my demo I have a point class which is managed for creation and editing of point positions, then I dump that into the simple points array whenever a redraw is needed.
Line animation
Once we understand the points array, it’s a small step to see that if we throw different points array contents at a line shape in an animation loop then we will get an animated line. In the demo I’m using a closed shape so the animation is more of a blob.
Konva.Line versus Konva.Path
Folks often ask about the difference between Konva.Line and Konva.Path. Both can draw lines, both can make filled shapes, both can have curves. The way you define what they draw differs significantly though – the Line is driven by a simple array of x, y points whilst the Path is controlled by an SVG-like command syntax.
My take is that the Line is my go-to for drawing simple a-to-b lines or making some polygons. When the requirement is a more complex thing, then Path has more horsepower. Or, put another way, Line is simple to understand and quick to code, Path is more complex and powerful but takes more time to develop code.
Summary
We’ve been introduced to some of the extended features of the Konva.Line, and we have a fun demo showing off those capabilities.
Thanks for reading.
VW. Jan 2023