There are 12 different compositing methods in Canvas. By default, source-over is applied for all the drawing operations on canvas.
In this video tutorial, we draw 2 rectangle and show the effects of applying different compositing methods on them.
index.html and myStyle.css file content are same as Linear Gradients in Canvas: HTML5
JavaScript file: Full code
myScript.js
window.onload = canvas;
function canvas()
{
var myCanvas = document.getElementById("myCanvas");
if( myCanvas && myCanvas.getContext("2d") )
{
var context = myCanvas.getContext("2d");
context.fillStyle = "red";
context.fillRect(40, 40, 250, 100);
context.globalCompositeOperation = "darker";
context.fillStyle = "blue";
context.fillRect(80, 80, 250, 100);
}
}
Here we’ve given a value of darker to globalCompositeOperation and the result is as shown in above image. i.e., the intersection region of the two image gets darker color.
Global Composite Operation in Canvas: HTML5
Change the value of globalCompositeOperation to see the effects, as listed in below image:
There are 12 different compositing methods:
1. source-over: This is the default value. Here the new image is drawn on top of the existing elements.
2. source-in: Displays only the new element in the region where the intersection takes place.
3. source-out: New drawing shown in the area where it doesn’t overlap with the existing elements.
4. source-atop: Drawing is shown only at the place where the first/existing drawing is present.
5. lighter: The intersection region is drawn in a lighter color.
6. xor: Exclusive or composite method clears the overlapping region and displays the rest of the drawing.
7. destination-over: The older/existing elements/drawing is shown on top of the new element. That is the new element is behind the existing ones.
8. destination-in: Displays only the existing element in the region where the intersection takes place.
9. destination-out: Existing/old element/drawing shown in the area where it doesn’t overlap with the new element/image.
10. destination-atop: Drawing is shown only at the place where the new element/drawing is present.
11. darker: The intersection region is drawn in a darker color.
12. copy: older content/element/image is removed and only the new content/element is shown.