Canvas globalCompositeOperation attribute
Definition and usage
globalCompositeOperation
Property settings or return how to draw a source (new) image onto the target (existing) image.
Source image = The drawing you plan to place on the canvas.
Target image = The drawing you have placed on the canvas.
Instance
Example 1
Draw rectangles with different globalCompositeOperation values. The red rectangle is the target image. The blue rectangle is the source image:
source-over destination-over
JavaScript:
var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.fillStyle="red"; ctx.fillRect(20,20,75,50); ctx.globalCompositeOperation="source-over"; ctx.fillStyle="blue"; ctx.fillRect(50,50,75,50); ctx.fillStyle="red"; ctx.fillRect(150,20,75,50); ctx.globalCompositeOperation="destination-over"; ctx.fillStyle="blue"; ctx.fillRect(180,50,75,50);
Example 2
All globalCompositeOperation attribute values:
Syntax
context.globalCompositeOperation="source-in";
Attribute value
Value | Description |
---|---|
source-over | Default. Display the source image on top of the target image. |
source-atop | Display the source image on top of the target image. The part of the source image outside the target image is invisible. |
source-in | Display the source image within the target image. Only the part of the source image within the target image will be displayed, and the target image is transparent. |
source-out | Display the source image outside the target image. Only the part of the source image outside the target image will be displayed, and the target image is transparent. |
destination-over | Display the target image above the source image. |
destination-atop | Display the target image on top of the source image. The part of the target image outside the source image will not be displayed. |
destination-in | Display the target image within the source image. Only the part of the target image within the source image will be displayed, and the source image is transparent. |
destination-out | Display the target image outside the source image. Only the part of the target image outside the source image will be displayed, and the source image is transparent. |
lighter | Display the source image + target image. |
copy | Display the source image. Ignore the target image. |
xor | Combine the source image with the target image using the XOR operation. |
Technical Details
Default Value: | source-over |
---|
Browser Support
The numbers in the table indicate the first browser version that fully supports this property.
Chrome | Edge | Firefox | Safari | Opera |
---|---|---|---|---|
Chrome | Edge | Firefox | Safari | Opera |
4.0 | 9.0 | 3.6 | 4.0 | 10.1 |
Note:Internet Explorer 8 and earlier versions do not support the <canvas> element.