vel.text(content [, opt])
Set the text content
of the element. This only makes sense for the
<text> element. This method can deal with multi-line text in case the content
string contains the new line characters (\n
). opt.lineHeight
can be optionally used
to set the line height of the text. It defaults to '1em'
. The opt.lineHeight
can
also be set to 'auto'
in which case it is left on Vectorizer to set the best possible line height.
This is useful if you annotate the text making it a rich-text (see below) and you don't want to set the
line height to a fixed value for all the lines.
opt.textPath
can
be either string or an object. If it is a string, it specifies a path the text should go along. If it is
an object, then it should contain a d
property that specifies the path the text should go along and
optinally other attributes that will be set on the automatically created <textPath>
SVG element
such as startOffset
.
t.text('my text\neven multiline')
t.text('my text\nwith custom line height', { lineHeight: '2em' })
t.text('text that goes along a path', { textPath: 'M 0 100 Q 30 10 100 0' })
t.text('another text that goes along a path', { textPath: { d: 'M 0 100 Q 30 10 100 0', startOffset: 50 } })
If opt.annotations
array is set, the text will be annotated by the attributes defined in the
annotations array. This means that you can easily render a rich-text. Each annotation in the annotations array
is an object of the form { start: Number, end: Number, attrs: Object }
where
start
(inclusive) and end
(exclusive) define the range of the text content
where
the attrs
SVG Attributes will be applied. If there are overlapping annotations, they will be
smartly merged (classes concatenated, attributes merged, style
can be always defined either as a string
or an object).
var text = V('text', { x: 250, y: 150, fill: 'black' });
text.text('This is a rich text.\nThis text goes to multiple lines.', { lineHeight: 'auto', annotations: [
{ start: 5, end: 10, attrs: { fill: 'red', 'font-size': 30, rotate: '20' } },
{ start: 7, end: 15, attrs: { fill: 'blue' } },
{ start: 20, end: 30, attrs: { fill: 'blue', 'class': 'text-link', style: 'text-decoration: underline' } }
]});
svg.append(text);
If opt.includeAnnotationIndices
is set to true
, each <tspan>
will contain the 'annotations'
attribute with comma separated indices of annotations that applied
to that piece of text. Vectorizer provides some useful functions for working with annotations. Those are
V.findAnnotationsAtIndex(), V.findAnnotationsBetweenIndexes()
V.shiftAnnotations() and V.annotateString().