Reputation: 14927
I have a problem with applying filters to an svg image. I'd like to apply a flood filter to just the image, but when I set that filter, it covers an area bigger than the image, seemingly increasing the size of the image. Is there a way to fix this? Run the snippet below to see the problem.
One thing to note: the height of the image is unknown
image {
outline: 3px solid red;
outline-offset: -3px;
}
image.flood {
filter: url(#floodFilter);
}
<svg width="500" height="200" viewBox="0 0 500 200">
<defs>
<filter id="floodFilter" filterUnits="objectBoundingBox">
<feFlood flood-color="lightblue" flood-opacity="1"></feFlood>
<feBlend in="SourceGraphic" in2="floodFill" mode="multiply"></feBlend>
</filter>
</defs>
<image x="0" y="30" width="200" href="https://www.fillmurray.com/g/200/140"> </image>
<image class="flood" x="230" y="30" width="200" href="https://www.fillmurray.com/g/200/140"></image>
</svg>
Upvotes: 2
Views: 276
Reputation: 124059
Just give the filter explicit bounds, the exact size of the object being filled.
By default the bounds are 10% bigger than the object so that drop shadows work.
Note that for your images to work cross-browser they will need height attributes.
image {
outline: 3px solid red;
outline-offset: -3px;
}
image.flood {
filter: url(#floodFilter);
}
<svg width="500" height="200" viewBox="0 0 500 200">
<defs>
<filter id="floodFilter" filterUnits="objectBoundingBox" x="0" y="0" width="1" height="1">
<feFlood flood-color="lightblue" flood-opacity="1" result="floodFill"></feFlood>
<feBlend in="SourceGraphic" in2="floodFill" mode="multiply"></feBlend>
</filter>
</defs>
<image x="0" y="30" height="140" width="200" href="https://www.fillmurray.com/g/200/140"> </image>
<image class="flood" x="230" y="30" height="140" width="200" href="https://www.fillmurray.com/g/200/140"></image>
</svg>
Upvotes: 2