To make my code more DRY, I would like to be able to use an existing SVG file for a clipPath
. For example:
picture-frame.svg:
<svg width="2000" height="1000" viewBox="0 0 2000 1000" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M932.66 998.369L932.251 ..." fill="black"/>
</svg>
example.php:
...
<body>
<svg viewBox="0 0 2000 1000" xmlns="https://www.w3.org/2000/svg" version="1.1" style="position: absolute; left: -9999px; overflow: hidden;">
<defs>
<clipPath id="my-clip">
<?php echo insertSVG( 'picture-frame' ); ?>
</clipPath>
</defs>
</svg>
<div style="clip-path: url('#my-clip');">
<img />
</div>
</body>
...
The code to insert the SVG code is simple using file_get_contents()
, see this blog post.
The tricky part is <clipPath>
doesn't allow <svg>
as a descendent, so copying the file contents verbatim does not work. Nor does using SimpleXMLElement
to change <svg>
to a tag with no-effect, like <g>
.
How can I can insert just the contents of the root <svg>
element (ie. <path>
in my example above) into the clipPath
element?
My Answer:
One way to achieve this is to use DOMDocument to parse the SVG file and extract the contents of the
Rate this post
3 of 5 based on 8917 votesComments