svgdotjs / svg.js

The lightweight library for manipulating and animating SVG
https://svgjs.dev
Other
11.15k stars 1.08k forks source link

how to add a `tspan` to an existing `text` #1074

Closed voxspox closed 4 years ago

voxspox commented 4 years ago

Fiddle

https://jsfiddle.net/h9rq2pa3/2/

Explanation

I want to create a Text element and add some lines aka TSpans afterwards. Calling tspan() on a text element replaces the text instead of adding text. The docs says "Just adding one tspan is also possible:"

How it is supposed by svgjs to do this?

Do I have to do something like this:

t1 = SVG('text')
ts1 = SVG('tspan').addTo(t1).tspan('hello').fill('Red')
Fuzzyma commented 4 years ago

You can pass a function to text() to have more fine control about text creation:

const t1 = canvas.text(function(text) {
  text.tspan('One Line').newLine()
  text.tspan('Another Line').newLine()
  text.tspan('Third Line').newLine()
})

The text gets deleted because text has a build mode which you can enable and disable. When you disable it, the text is replaced. Otherwise it is added to the text element. However, when you want tspan to behave as lines, you have to call newLine() on them.

https://svgjs.com/docs/2.7/elements/#text-build

voxspox commented 4 years ago

hmm, I want a mixture of this ;)

I just want to add a tspan and position it myself. Thus, tspan() should not clear() but also not build.

Fuzzyma commented 4 years ago

When you want to add a tspan without the text beeing cleared you do want the build mode. The above code is the same as this:

const t1 = canvas.text('').build(true)
t1.tspan('One Line').newLine()
...
...
voxspox commented 4 years ago

please check the resulting SVG. text('') adds an extra empty tspan

Fuzzyma commented 4 years ago

alright, you wanna go full pro mode?

const t1 = new SVG.Text().build(true)
t1.tspan('One Line').newLine()
...
...

canvas.add(t1)

better?

(btw, version 3 of svg.js is better, if you still have the chance you should migrate)