I would like to filter the contents of <canvas>
using either the canvas' context https://wiki.mozilla.org/CanvasFilters#Using_a_SVG_reference or putting the filter into a CSS style:
<!DOCTYPE html>
<html>
<body>
<svg style="display:none;">
<filter id="color-filter">
<feColorMatrix type="matrix" values="0.5 0.5 0.5 0 0 0.3 0.3 0.3 0 0 0.3 0.3 0.3 0 0 0 0 0 1 0"/>
</filter>
</svg>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3; filter: url(#color-filter)">
Your browser does not support the HTML canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
ctx.filter = "url(#color-filter)";
var grd = ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"yellow");
grd.addColorStop(1,"cyan");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
</script>
</body>
</html>
Fiddle: https://jsfiddle.net/s1dw74u3/
In Chrome, both solutions work, so the code above applies the filter twice. In Firefox, none: the context filter is ignored and the style filter makes the canvas disappear entirely.
How to apply such a filter in a portable way?
Your filter doesn't work in Chrome either as far as I can see. the difference is that Firefox doesn't display anything when the filter doesn't work whereas Chrome displays the unfiltered image.
If you want to fix both Firefox and Chrome stop using display: none with SVG. If you need to hide something use width="0" and height="0"
<!DOCTYPE html>
<html>
<body>
<svg width="0" height="0">
<filter id="color-filter">
<feColorMatrix type="matrix" values="0.5 0.5 0.5 0 0 0.3 0.3 0.3 0 0 0.3 0.3 0.3 0 0 0 0 0 1 0"/>
</filter>
</svg>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #d3d3d3; filter: url(#color-filter)">
Your browser does not support the HTML canvas tag.</canvas>
<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
// Create gradient
ctx.filter = "url(#color-filter)";
var grd = ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"yellow");
grd.addColorStop(1,"cyan");
// Fill with gradient
ctx.fillStyle = grd;
ctx.fillRect(10,10,150,80);
</script>
</body>
</html>