Is it possible to transform any SVG into a solid black shape in an automated way (in javascript or otherwise) by simplifying the path?
Is there a library to do this, or is there another way?
Let’s take this SVG as an example:
<svg height="512" viewBox="0 0 16.933 16.933" width="512" xmlns="http://www.w3.org/2000/svg"><path d="M12.289 10.724a.265.265 0 0 0-.168.066 5.555 5.555 0 0 1-2.74 1.303.265.265 0 0 0-.2.363l1.597 3.806a.265.265 0 0 0 .489-.004l.732-1.825 1.852.743a.265.265 0 0 0 .342-.348l-1.653-3.942a.265.265 0 0 0-.251-.162zm-7.897.165-1.652 3.94a.265.265 0 0 0 .343.348l1.851-.744.732 1.825c.089.22.398.222.49.004l1.598-3.81a.265.265 0 0 0-.2-.363 5.556 5.556 0 0 1-2.743-1.297.265.265 0 0 0-.419.097z" fill="#ff5757"/><path d="M8.467.529C5.109.529 2.38 3.257 2.38 6.615s2.728 6.084 6.086 6.084 6.086-2.726 6.086-6.084S11.825.529 8.467.529z" fill="#ffcb3c"/><path d="M8.467 1.851a4.767 4.767 0 0 0-4.762 4.764c0 2.627 2.135 4.762 4.762 4.762s4.762-2.135 4.762-4.762A4.767 4.767 0 0 0 8.467 1.85z" fill="#ffea54"/><path d="M8.465 3.576a.265.265 0 0 0-.229.172l-.7 1.857-1.987.06a.265.265 0 0 0-.156.471L6.94 7.38l-.554 1.906a.265.265 0 0 0 .4.295l1.658-1.09 1.643 1.117a.265.265 0 0 0 .404-.289L9.97 7.402l1.568-1.215a.265.265 0 0 0-.148-.475L9.404 5.62l-.672-1.87a.265.265 0 0 0-.267-.175z" fill="#feaa2b"/></svg>
Here’s what I’d like to achieve:
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 362.76 480.62"><g ><path d="m307.02,320.09C411.21,221.17,369.32,3.28,181.41,0-6.38,3.3-48.38,220.77,55.44,319.82l-47.2,112.57c-1.7,4.08.23,8.78,4.31,10.48.97,4.42,59.38-22.24,62.03-22.45l22.13,55.18c2.69,6.65,12.03,6.71,14.82.12l45.88-109.4c7.71.95,15.69,1.52,23.97,1.67,8.29-.14,16.28-.72,23.99-1.67,9.72,23.16,45.91,109.4,45.91,109.4,1.74,4.07,6.45,5.96,10.52,4.22,3.97,2.43,24.7-57.52,26.4-59.52l56,22.47c6.34,2.72,13.15-4.25,10.34-10.52-2.54-1.46-31.18-81.18-47.53-112.26Z"/></g></svg>
2
Answers
If it is enough for the SVG to be rendered black, you can use clip-path with a combination of CSS and JavaScript.
The core approach here is to wrap the SVG paths in
<clipPath>
and use CSS’sclip-path
to then change the shape of a<div>
to be the shape of the SVG.The snippets assume that your SVG is a string. But if your SVG is already in the html, you can use
querySelector
instead to select the<svg>
element.This also assumes that there is only one SVG that this applies to. If that is untrue, you have to use
clipNodePath.id = randomId
for each SVG and useelement.style.clipPath = url("#`${randomId}`");
instead. That approach can be found in the collapsed snippet.Or with random IDs if there are multiple black SVGs per page:
I don’t know if you find this too simple a solution, but you could use the !important keyword to make all fills black.