Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I limit or clip text in SVG?

Tags:

html

svg

I have done a table in SVG, and I want to fill it with data dynamically. That means that I don't know how much space the text takes, and I want to clip or hide the overlapping text. How can I do that in SVG?

My HTML document with SVG looks like:

<!DOCTYPE html> <html> <body> <svg> <text x="100" y="100">Orange</text>     <text x="160" y="100">12</text> <text x="100" y="115">Pear</text>       <text x="160" y="115">7</text> <text x="100" y="130">Banana</text>     <text x="160" y="130">9</text> <text x="100" y="145">Pomegranate</text><text x="160" y="145">2</text>  <line x1="157" y1="85" x2="157" y2="155" style="stroke:rgb(100,100,100)"/> </svg> </body> </html> 

And this will render to:

enter image description here

Is there any way I can clip the text i my SVG-"table"?


Implemented solution from Erik's answer:

<!DOCTYPE html> <html> <body> <svg>     <text x="10" y="20" clip-path="url(#clip1)">Orange</text>            <text x="10" y="35" clip-path="url(#clip1)">Pear</text>          <text x="10" y="50" clip-path="url(#clip1)">Banana</text>            <text x="10" y="65" clip-path="url(#clip1)">Pomegranate</text>      <text x="70" y="20">12</text>     <text x="70" y="35">7</text>     <text x="70" y="50">9</text>     <text x="70" y="65">2</text>      <line x1="67" y1="5" x2="67" y2="75" style="stroke:rgb(100,100,100)"/>      <clipPath id="clip1">         <rect x="5" y="5" width="57" height="90"/>     </clipPath> </svg> </body> </html> 

enter image description here

like image 327
Jonas Avatar asked Jul 14 '11 10:07

Jonas


People also ask

Is SVG text editable?

SVG 1.2 introduces editable text fields, moving the burden of text input and editing to the user agent, which has access to system text libraries.

How do I make SVG text editable?

But most importantly, what's the best way to make SVG text editable? document. getElementById("element"). contentEditable = "true"; You can also use the ref contenteditable="true" in an HTML element like so: <div contenteditable="true"> .

Can you put text in an SVG?

SVG treats a text element in much the same way that it treats graphical and shape elements. You position text with x and y coordinates and use fill and stroke options to color text the same way you would with a <circle> or <rect> element.


1 Answers

You can use clip-path to clip to whatever shape you want, see e.g masking-path-01 from the svg testsuite.

Relevant parts, defining the clip path:

<clipPath id="clip1">   <rect x="200" y="10" width="60" height="100"/>   ... you can have any shapes you want here ... </clipPath> 

and then apply the clip path like this:

<g clip-path="url(#clip1)">   ... your text elements here ... </g> 
like image 185
Erik Dahlström Avatar answered Oct 26 '22 03:10

Erik Dahlström