How to apply matrix filter to canvas?

Member

by addison , in category: Javascript , 4 months ago

How to apply matrix filter to canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by gilbert , 4 months ago

@addison 

To apply a matrix filter to a canvas using HTML5 and JavaScript, you can use the CanvasRenderingContext2D.filter property. Here is an example code snippet to apply a matrix filter to a canvas:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!DOCTYPE html>
<html>
<head>
    <title>Matrix Filter Example</title>
</head>
<body>
    <canvas id="myCanvas" width="400" height="400"></canvas>

    <script>
        var canvas = document.getElementById("myCanvas");
        var ctx = canvas.getContext("2d");

        // Create an image object
        var img = new Image();
        img.onload = function() {
            // Draw the image on the canvas
            ctx.drawImage(img, 0, 0);

            // Apply a matrix filter
            ctx.filter = 'matrix(1, 0, 0, 0, 0,  0, 1, 0, 0, 0,  0, 0, 1, 0, 0,  0, 0, 0, 1, 0)';
            ctx.drawImage(canvas, 0, 0);
        };
        img.src = 'example.jpg';
    </script>
</body>
</html>


In this example, the matrix filter matrix(1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0) is applied to the canvas. You can adjust the values in the matrix filter to achieve different visual effects. The image 'example.jpg' needs to be replaced with the path to the image you want to apply the filter to.


Note that the matrix filter property is still experimental and may not be supported in all browsers.