Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG viewbox overflow: hidden / crop

Tags:

svg

Is there a way to make anything outside the viewBox invisible? As if the viewBox itself were an element with overflow: hidden

In the jsFiddle, you can see the viewBox highlighted in blue.

<svg width="100%" height="100%" viewBox="0 0 800 100">
    <rect width="100%" height="100%" fill="none" stroke="blue" />
    <text y="10" x="10%" width="10%" height="200%" fill="#000" font-size="30" >
        Only the part inside the viewBox should be visible
    </text>
</svg>

Only the part inside the viewBox should be visible

like image 563
fregante Avatar asked Jun 06 '14 04:06

fregante


1 Answers

You can use the rectangle as a <clipPath>:

<defs>
    <rect id="rect" width="100%" height="100%" fill="none" stroke="blue" />
    <clipPath id="clip">
        <use xlink:href="#rect"/>
    </clipPath>
</defs>

and then apply it to a <g> element which contains your text (and anything else you want to clip:

<g clip-path="url(#clip)">
    <text y="10" x="10%" width="10%" height="200%" fill="#000" font-size="30">Only the part inside the viewBox should be visible</text>
</g>

Since the <rect> was used only to shape the clipPath, you have to redraw it:

<use xlink:href="#rect"/>

Updated fiddle

like image 112
helderdarocha Avatar answered Nov 20 '22 12:11

helderdarocha