Blazor WebAssembly: Connecting Lines in SVG
A Way To Implement Connecting Lines Between SVG Objects
This article describes a way to implement connecting lines between SVG objects. Connecting lines automatically change when you change the position of objects. Along the way, the OnParametersSet method is considered.
What we will get in the end
The result is a Blazor component Connector. Example of use:
Connector gets input parameters:
- coordinates of the start and end point,
- direction of entry to the point: top, right, bottom, left.
When the input parameters are changed, the Connector rebuilds the connecting line (see Pic. 1).
If you just need a ready-made solution, you don’t need to read the article — just copy and paste Connector component from source code.
SVG has a built-in ability to draw smooth lines — the Path element. Path supports various options for drawing lines. For connecting lines, the cubic Bezier curve implemented in Path is suitable.
To draw a cubic Bezier curve, we need 4 points (Pic 3):
- start point, end point,
- start reference point and end reference point.
The shape of the curve depends on the position of the reference points. In Pic 4, the first reference point is lifted up.
Blazor Connector component
Listing 1 shows the use of the Connector component. The Connector displays on the page as an SVG path element.
When drawing connecting lines:
- the start and end points (X1, Y1; X2, Y2) (marked in blue in Pic 3) are set,
- the reference points (c1x, c1y; c2x, c2y) (marked in red in Pic 3) need to be calculated.
Let the connector line can come to the point only from 4 sides (see the enum Direction in Listing 2):
- from above,
- from right,
- from below,
- from left.
Let’s calculate the reference points for the left and right connection.
On Pic 5, the connecting line comes to the upper blue point from the right. The Y coordinate of the reference point equals Y1 (c1y = Y1). The X coordinate depends on X1: c1x = X1 + 70. 70 is an arbitrary coefficient.
Reference points for top and bottom connections are calculated by analogy.
Implementation of the algorithm see on GitHub.
Rebuilding the connecting line dynamically. OnParametersSet method
When changing the values of the input parameters, the Connector must recalculate the reference points c1x, c1y; c2x, c2y.
It is possible to use setters of input parameters as an event for recalculation — listing 3.
This is not the best option. For example, the parameters of the Connector are changed all at once:
The setter will be called for each input parameter, i.e. the “calc” method will be called 6 times.
This problem can be fixed with OnParametersSet:
For Listing 4, the OnParametersSet method will be called once.
OnParametersSet is used for more than just such cases, see Avoid unnecessary rendering of component subtrees.
The Connector is ready. Using the Connector and Draggable from the previous article, we can make underwater plants, or IKEA lights — pic 1.