yFiles for HTML provides an abstract base class which provides the basic functionality
to create a custom label style. We start with a custom subclass of
LabelStyleBase.
class CustomLabelStyle extends LabelStyleBase {
protected createVisual(context: IRenderContext, label: ILabel): Visual | null {
return null
}
}
This code will not produce anything visible, yet. We first have to implement the
createVisual
method. This method returns an SVG element, wrapped into
an SvgVisual. Let’s start with only a text for now to keep
things simple. We will switch to a more complex visualization later on.
protected createVisual(
context: IRenderContext,
label: ILabel
): Visual | null {
const textElement = document.createElementNS(
'http://www.w3.org/2000/svg',
'text'
)
textElement.textContent = label.text
const transform = LabelStyleBase.createLayoutTransform(
context,
label.layout,
true
)
transform.applyTo(textElement)
textElement.setAttribute('dy', String(label.layout.height))
return new SvgVisual(textElement)
}
Note
|
The SVG element returned in createVisual does not necessarily
have to be created using the JavaScript DOM API. You could also create it
using any JavaScript UI framework or API like React, Vue, etc.
|
As you can see in the sample graph, the label style works for both, node and edge
labels. It also supports rotation without any further adjustment. This is handled
by the layout transform that is created and assigned in the following two lines.
The last parameter in createLayoutTransform
specifies whether the
label should be flipped if it is upside-down.
const transform = LabelStyleBase.createLayoutTransform(
context,
label.layout,
true
)
transform.applyTo(textElement)
Since the SVG text anchor point is bottom-left and the label layout anchor point
is top-left, we have to manually set the 'dy' attribute of the text to move it
down by one label height, or else the text would be placed above the actual label
layout.
textElement.setAttribute('dy', String(label.layout.height))