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:
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>
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.
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"> .
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With