Tspan element background color

Can I set the background color of an SVG <tspan> element? If not, what would be the best way to mimic it?

My goal is to give the background color of the text, and I thought that the <tspan> fill elements would be perfect - they already “outline” the text fragments ( <tspan> ) that represent the lines in multi-line text.

An example I'm working with:

 <text x="100" y="100" font-size="30"> <tspan>hello</tspan> <tspan x="100" dy="1.2em">world</tspan> </text> 

I tried the "fill" attribute, but it seems to affect the fill (color) of the text, and not the area behind it:

 <tspan fill="yellow">hello</tspan> 

I also tried setting the background color using CSS:

 <style type="text/css">tspan { background-color: yellow }</tspan> 

.. but this does not work (at least in Chrome 17 and Firefox 12).

Wrapping tspan in <g> (or text in <g> ) using "fill" also does not work:

 <g fill="yellow"><tspan>hello</tspan></g> <tspan><g fill="yellow">hello</g></tspan> 

Besides creating a <rect> element located in the same place, something that I would like to avoid, is there another way to achieve this?

+5
css text svg
Dec 30 '11 at 1:12
source share
2 answers

The direct is probably the best way to do this (assuming that you are dealing only with the simplest forms of text).

In SVG 1.1, tspans do not have a "background", the background is everything that is painted before tspan. There are many cases to consider, for example, the case where tspan is inside a textPath that has a circle shape. Also note that in all cases it is not as simple as a continuous rectangle, one tspan can be skewed, rotated and split into several intersecting and disjoint figures due to transformations, glyph positioning, etc.

Another way I can think of is to do this without scripts, but then you will need to know the line width in advance (for example, using a monospace font). If you have this, you can add another tspan element using the Ahem font, placing it in front of another tspan in the document and giving it the same x, y position as the tspan you want to give the "background".

Otherwise, the way to do this is through scripting and adding rectangles (or tspans with an Ahem-like font).

+5
Dec 30 '11 at 2:18 a.m.
source share

SVG does not support directly specifying the background color of an image ... but you can configure four values ​​for the viewBox attribute (complex). I know this, what you want to avoid, but CSS will not help you.

... or you can use getBBox and getCTM ... this will give you benefits for the rotated text. EXAMPLE: http://srufaculty.sru.edu/david.dailey/svg/getCTM.svg

+2
Dec 30 '11 at 10:55
source share



All Articles