How to get image mask in canvas?

Member

by denis , in category: Javascript , 4 months ago

How to get image mask in canvas?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by cortez.connelly , 3 months ago

@denis 

To get an image mask in canvas, you can use the globalCompositeOperation property of the CanvasRenderingContext2D object. Here's an example of how to create an image mask in 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
27
28
// Get canvas and context
var canvas = document.getElementById('myCanvas');
var ctx = canvas.getContext("2d");

// Create the mask image
var maskImg = new Image();
maskImg.src = 'mask.png';

// Create the main image
var mainImg = new Image();
mainImg.src = 'mainImg.png';

// When both images have loaded
maskImg.onload = function() {
  mainImg.onload = function() {
    // Draw the mask image on the canvas
    ctx.drawImage(maskImg, 0, 0, canvas.width, canvas.height);
    
    // Set global composite operation to 'source-in' to apply the mask
    ctx.globalCompositeOperation = 'source-in';
    
    // Draw the main image on the canvas, clipped by the mask
    ctx.drawImage(mainImg, 0, 0, canvas.width, canvas.height);
    
    // Reset global composite operation
    ctx.globalCompositeOperation = 'source-over';
  };
};


In this code snippet, we first load the mask and main images, then draw the mask image on the canvas. We set the globalCompositeOperation property to 'source-in' to apply the mask effect. Finally, we draw the main image on the canvas, which will be clipped by the mask.


You can customize the mask image and main image URLs according to your needs.