Search code examples
javascriptimagesvgpathsvg-filters

Apply combination of background colour and image filter to a svg path


I have a svg path where I apply both a background colour as well as a filter containing a (possible scaled and translated) image.

First the background colour is applied using the css fill property: myPath.css('fill', bgColour);

Afterwards the filter is added like this:

var filter = svg.filter(defs, 'myImageFilter',
    0, 0, scale + '%', scale + '%',
    {
        filterUnits: 'objectBoundingBox'
    }
);

// add the image
var outputSlot = 'myImage' + sectionNumber;
svg.filters.image(filter, outputSlot, pathToImageFile);
// move it
svg.filters.offset(filter, 'movedImage', outputSlot, moveX, moveY);
// combine image with path for clipping
svg.filters.composite(filter, 'clip', 'in', 'movedImage', 'SourceGraphic');
// mix both images
svg.filters.blend(filter, '', 'multiply', 'SourceGraphic', 'clip');

// assign filter to the path
myPath.attr('filter', 'url(#myImageFilter)');

The problem I have with that is the background colour affects the image, too (as if it was painted above the image). What I need is that the image is placed on top of the background instead.

Any idea about how to achieve this?

Do I maybe need to duplicate the whole path to have it one time for the background colour only and one time for the image?


Solution

  • It's probably the "multiply" in your svg.filters.blend. Just use "normal" instead of "multiply".