If we want to apply an SVG filter on a canvas element, there are different ways to achieve this. According to this resource, we can apply a SVG filter to the CanvasRenderingContext2D in javascript using the following code snippet:
ctx.filter = "url(#bar)";
Alternatively, we can also apply the filter in CSS directly on the whole canvas like so:
#canvas {
filter: url(#bar);
}
In my case, I need to apply the filter in javascript as I only want part of the canvas to be affected. It's worth noting that when applying a feColorMatrix to some or all of the shapes, the results may vary depending on whether the filter was applied through JS on the 2D Context or via CSS on the entire canvas element.
Here is a sample JavaScript code snippet demonstrating how to apply the filter selectively:
const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
ctx.filter = "url(#bar)";
ctx.fillRect(10,10,100,100);
ctx.fillRect(10,120,100,100);
ctx.fillRect(120,10,100,100);
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.ellipse(170, 170, 50, 50, Math.PI / 4, 0, 2 * Math.PI);
ctx.fill();
#canvas {
/* Uncomment to see the difference */
/* filter: url(#bar); */
}
<svg xmlns="http://www.w3.org/2000/svg" version="1.1>
<defs>
<filter id="bar">
<fegaussianblur in="SourceGraphic" stdDeviation="10" result="blur"></fegaussianblur>
<fecolormatrix in="blur" mode="matrix" values="1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 18 -7"></fecolormatrix>
</filter>
</defs>
</svg>
<canvas id="canvas" width="400" height="400"></canvas>