Why is my clip path not working when it is svg?
I am following mozilla documentation on using css property clip-path
to apply svg clipPath
to HTMLElement
. But for some reason this doesn't work for me, not in divs, not in images.
The documentation says that you can easily copy the item with this code:
<style>.target { clip-path: url(#c1); }</style>
<svg:svg height="0">
<svg:clipPath id="c1" clipPathUnits="objectBoundingBox">
<svg:circle cx="0.25" cy="0.25" r="0.25" id="circle"/>
<svg:rect x="0.5" y="0.2" width="0.5" height="0.8"/>
</svg:clipPath>
</svg:svg>
And I tried this but it doesn't work. The property clip-path
works with predefined methods such as polygon () and ellipse (), but will not work with associated svg.
I made a JSFiddle illustrating my problem, I hope you can find my error :)
source to share
Put tags clipPath
in tags defs
. Use foreignObject
to import HTML elements that need to be trimmed and use inline clip-path
for maximum browser support.
#kitten {
width: 250px;
}
#kittenReplica {
width: 250px;
height: 187.5px;
background-color: lightblue;
}
<svg width="500px" height="187.5px">
<defs>
<clipPath id="path" clipPathUnits="objectBoundingBox">
<circle cx="0.25" cy="0.25" r="0.25" id="circle" />
<rect x="0.5" y="0.2" width="0.5" height="0.8" />
</clipPath>
</defs>
<foreignObject clip-path="url(#path)" width="50%" height="100%">
<img src="http://i.imgur.com/tzPv43g.jpg" id="kitten" class="clipped" />
</foreignObject>
<foreignObject x="250" clip-path="url(#path)" width="50%" height="100%">
<div id="kittenReplica" class="clipped"></div>
</foreignObject>
</svg>
source to share
Your problem was that you were using elements with the svg namespace prefix, but did not define the svg namespace. If you remove "svg:" from each item, it works.
For example change <svg:svg ...>
to <svg ...>
.
If you look at the original Firefox example you copied from, you can see that the svg namespace is defined in the <html>
: element xmlns:svg="http://www.w3.org/2000/svg"
.
Below is a version of this example that works in Firefox and Chrome.
And here is an updated version of your violin that works.
body {
background:#ccc;
font-size:30px;
}
p {
width:300px;
border:1px solid black;
display:inline-block;
margin:1em;
}
b {
outline:1px dotted blue;
}
.target {
-webkit-clip-path: url(#c1);
clip-path: url(#c1);
}
<p class="target" style="background:lime;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor
incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.
</p>
<img src="http://i.imgur.com/tzPv43g.jpg" id="kitten" class="target" />
<svg height="0">
<defs>
<clipPath id="c1" clipPathUnits="objectBoundingBox">
<circle cx="0.25" cy="0.25" r="0.25" id="circle"/>
<rect x="0.5" y="0.2" width="0.5" height="0.8"/>
</clipPath>
</defs>
</svg>
source to share