HTML canvas globalCompositeOperation attribute

Definition and Usage

globalCompositeOperation Attribute settings or returns how to draw a source (new) image onto the target (existing) image.

Source Image = The drawing you intend 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

Your browser does not support the canvas tag.

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);

Try It Yourself

Example 2

All globalCompositeOperation attribute values:

Try It Yourself

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 atop the target image. The part of the source image outside the target image is not visible.
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 at the 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.