/

HTML / CSS / JavaScript Tutorial

JavaScript canvas2d object property: globalCompositeOperation

[this page | pdf | back links]

The globalCompositeOperation property of the JavaScript DOM object returned by the getContext("2d") method applied to the HTML <canvas> element sets / returns how new images are drawn onto existing images.

 

It can take the following values:

 

Value

Meaning

copy

Source image only (destination image is ignored)

destination-atop

As per source-atop but with source and destination flipped

destination-in

As per source-in but with source and destination flipped

destination-out

As per source-out but with source and destination flipped

destination-over

As per source-over but with source and destination flipped

lighter

Source image + destination image

source-atop

Source image on top of destination image (part of source image outside destination image is ignored)

source-in

Source image into destination image (only part of source image inside destination image is shown, destination image is transparent)

source-out

Source image out of destination image (only part of source image outside destination image is shown, destination image is transparent)

source-over

(default). Source image over destination image

xor

Source and destination images combined using XOR operation

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head></head>
<body>
<span id="element"></span>

<script>
var x2 = document.createElement("CANVAS");
x2.setAttribute("width", "200");
x2.setAttribute("height", "100");
x2.setAttribute("style", "border: 1px solid black");
var c2 = x2.getContext("2d");

c2.fillStyle = "blue";
c2.fillRect(10, 10, 50, 60);
c2.fillStyle = "orange";
c2.fillRect(30, 30, 50, 60);

c2.fillStyle = "blue";
c2.fillRect(110, 10, 50, 60);
c2.fillStyle = "orange";
c2.globalCompositeOperation="lighter";
c2.fillRect(130, 30, 50, 60);

document.getElementById("element").appendChild(x2);
</script>

</body>
</html>


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile