Search code examples
imagesvgsvg-filters

SVG path with image filter but transparent background


I have a path with an image which is added through a filter. Also the path has a background colour set like this:

myPath.css('fill', bgColour);

My question is how it is possible to have the path transparent but keep the image visible?

I tried fill: transparent, fill-opacity: 0, fill: rgba(0, 0, 0, 1) but with these the image becomes invisible, too.

Here is my current code:

var filter = svg.filter(defs, 'myFilter', 0, 0, '100%', '100%', filterOptions);

var sourcePathRef = 'SourceGraphic';
if (hasTransparentBackground()) {
    // make path transparent
    svg.filters.colorMatrix(filter, 'TransformedGraphic', sourcePathRef, 'matrix', [
        [0, 0, 0, 0, 0], 
        [0, 0, 0, 0, 0], 
        [0, 0, 0, 0, 0], 
        [0, 0, 0, 0, 0]
    ]);
    sourcePathRef = 'TransformedGraphic';
}

// add the image
var outputSlot = 'customImage';
svg.filters.image(filter, outputSlot, imageFile, {
    preserveAspectRatio: aspectRatio
});
// move it
svg.filters.offset(filter, 'movedImage', outputSlot, moveX, moveY);
// combine image with path for clipping
svg.filters.composite(filter, 'clip', 'in', 'movedImage', sourcePathRef);
// mix both images
svg.filters.blend(filter, '', 'normal', 'clip', sourcePathRef);
// apply the filter
imageSlot.attr('filter', 'url(#myFilter)');

Solution

  • Simple fix: skip the last (blend) filter :-)