chevron_right Demos chevron_right Tutorial: Edge Style Implementation chevron_right 02 Crop the Polyline
01 Create a Polyline
03 Create Parallel Polylines

Cropping the path at the node outline

In the previous step, we generated and displayed an SVG path for an edge. However, it looks untidy as the path extends into its adjacent nodes. The reason behind it is that the path runs up to the port of the nodes, which is often located in the center of a node.

To fix this issue, it is necessary to adjust the path so that it ends precisely at the outline of the nodes. This requires computing the intersection point of the path and the node’s outline, which may be complex depending on the shape of the node. Thankfully, the EdgeStyleBase offers useful methods which not only calculate the intersection points but also shorten the path accordingly.

Working with paths

To create or modify paths in yFiles for HTML, we commonly use the GeneralPath class. To get an instance of this class from an edge, we can use the EdgeStyleBase.getPath method.

const generalPath = this.getPath(edge)

Using the EdgeStyleBase.cropPath method, we can now trim the path to end at the outline of the nodes. This method requires us to specify the arrows at the beginning and end of the edge. Since we haven’t added any arrows yet, we’ll use IArrow.NONE.

const croppedGeneralPath = this.cropPath(
  edge,
  IArrow.NONE,
  IArrow.NONE,
  generalPath!
)

Finally, we create a SVGPathElement instance from the corrected path using the GeneralPath.createSvgPath method.

const path = croppedGeneralPath!.createSvgPath()

Bringing everything together

Now we can use the above parts to create an SVG visual from the edge in the createVisual method:

protected createVisual(context: IRenderContext, edge: IEdge): Visual | null {
  const generalPath = this.getPath(edge)
  const croppedGeneralPath = this.cropPath(
    edge,
    IArrow.NONE,
    IArrow.NONE,
    generalPath!
  )
  const path = croppedGeneralPath!.createSvgPath()
  path.setAttribute('fill', 'none')
  path.setAttribute('stroke', 'black')
  path.setAttribute('stroke-width', '1')
  return new SvgVisual(path)
}