How to add 'screen' blend mode to canvas element?

Member

by rollin , in category: Javascript , 5 months ago

How to add 'screen' blend mode to canvas element?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by jerad , 5 months ago

@rollin 

To add the 'screen' blend mode to a canvas element in HTML5, you can use the globalCompositeOperation property of the canvas context.


Here is an example code snippet to achieve this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
<canvas id="myCanvas" width="200" height="200"></canvas>
<script>
    var canvas = document.getElementById('myCanvas');
    var ctx = canvas.getContext('2d');
    
    // Set the global composite operation to 'screen'
    ctx.globalCompositeOperation = 'screen';
    
    // Draw a rectangle with a fill color
    ctx.fillStyle = 'blue';
    ctx.fillRect(50, 50, 100, 100);
</script>


In the code above, we first get the canvas element and its 2D drawing context. We then set the globalCompositeOperation property of the context to 'screen'. Finally, we draw a rectangle on the canvas with a blue fill color, and the 'screen' blend mode will be applied to it.