Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SVG scaling and clip path

I'm struggling with an SVG clip path scaling behaviour. I would like to scale a clip path to fit the element size it's applied to. I've been reading about clipPath units but I can't get this working.

Here is an example of what I am trying to do without any scaling: http://jsfiddle.net/1196o7n0/1/

...and the SVG ( the main shape and the clippath shape are exactly the same ):

<svg width="800" height="600"  xmlns="http://www.w3.org/2000/svg" xmlns:svg="http://www.w3.org/2000/svg">
  <clipPath id="svgPath">
        <circle r="40" cy="50" cx="50" />
        <circle r="74.576" cy="235" cx="193.949" />
        <circle r="47.034" cy="108.305" cx="426.576" />
        <circle r="43.644" cy="255.763" cx="346.915" />
        <circle r="35.17" cy="82.882" cx="255.39" />
  </clipPath>
  <g fill="#000">
    <circle r="40" cy="50" cx="50" />
    <circle r="74.576" cy="235" cx="193.949" />
    <circle r="47.034" cy="108.305" cx="426.576" />
    <circle r="43.644" cy="255.763" cx="346.915" />
    <circle r="35.17" cy="82.882" cx="255.39" />
  </g>
</svg>

Now if I define a viewbox and make that SVG scales to fit the document width and height, the clip path doesn't seem to scale: http://jsfiddle.net/1196o7n0/2/

Any idea on how I can make this work ? Am i missing out on something?

like image 208
picooose Avatar asked Sep 17 '14 22:09

picooose


Video Answer


2 Answers

To scale a clip path to fit the element that you are applying it to you need to add clipPathUnits="objectBoundingBox" to your clippath element.

Here is a JsFiddle based on your example demonstrating how to do this.

<svg width="0" height="0" >
    <defs>
        <clipPath id="svgPath" clipPathUnits="objectBoundingBox">
            <circle r="0.05" cy="0.0625" cx="0.1625" />
            <circle r="0.09322" cy="0.29375" cx="0.2424" /> 
            <!-- rest of path here-->
        </clipPath>
    </defs>
</svg>
<div class="content centered">
    <div class="clipped"></div>
</div>

The catcher is that the units of the path need to be decimal numbers between 0 and 1; these represent fractions of the corresponding element's width or height.

like image 144
Richard Hunter Avatar answered Oct 10 '22 17:10

Richard Hunter


The clipPath is defined in absolute units (pixels). If it was being applied to something in the SVG, it would get scaled. But the HTML side of things doesn't know that. It just applies the clipPath as defined.

like image 40
Paul LeBeau Avatar answered Oct 10 '22 15:10

Paul LeBeau