Categories
HTML JavaScript Web development

HTML canvas globalCompositeOperation Property

HTML canvas globalCompositeOperation Property

The HTML canvas globalCompositeOperation property sets how a source (new) image is drawn into a destination (existing) image.

Example:

<!DOCTYPE html>
<html>
<body>

<canvas id="composite" width="300" height="150" style="border:1px solid #333;">
</canvas>

<script>
var c = document.getElementById("composite");
var ctx = c.getContext("2d");
ctx.fillStyle = "#2a9d8f";
ctx.fillRect(40, 20, 75, 75);
ctx.fillStyle = "#e9c46a";
ctx.globalCompositeOperation = "source-over";
ctx.fillRect(60, 50, 75, 75);
ctx.fillStyle = "#2a9d8f";
ctx.fillRect(160, 20, 75, 75);
ctx.fillStyle = "#e9c46a";
ctx.globalCompositeOperation = "destination-over";
ctx.fillRect(190, 50, 75, 75);
</script>

</body>
</html>

Output:

Syntax:

context.globalCompositeOperation="source-in";

source-over (default) – displays the source image over the existing image.

source-atop – displays the source image on top of the existing image.

source-in – displays the source image into the existing image.

source-out – displays the source image out of the destination image.

destination-over – displays the destination image over the source image.

destination-atop – displays the existing image on top of the source image.

destination-in – displays the destination image into the source image.

destination-out – displays the destination image out of the source image.

lighter – displays the source image + the destination image.

copy – displays the source image (the existing image is ignored).

xor – the source image is combined by using an exclusive OR with the destination image.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
canvas {
  border: 1px solid #333;
  margin-right: 15px;
  margin-bottom: 20px;
}
</style>
</head>
<body>

<script>
var gco = new Array();
gco.push("source-atop");
gco.push("source-in");
gco.push("source-out");
gco.push("source-over");
gco.push("destination-atop");
gco.push("destination-in");
gco.push("destination-out");
gco.push("destination-over");
gco.push("lighter");
gco.push("copy");
gco.push("xor");

var n;
for (n = 0; n < gco.length; n++) {
  document.write("<div id='p_" + n + "' style='float:left;'>" + gco[n] + ":<br>");
  var c = document.createElement("canvas");
  c.width = 100;
  c.height = 100;
  document.getElementById("p_" + n).appendChild(c);
  var ctx = c.getContext("2d");    
  ctx.fillStyle = "#2a9d8f";
  ctx.fillRect(10, 10, 50, 50);
  ctx.globalCompositeOperation = gco[n];
  ctx.beginPath();
  ctx.fillStyle = "#e9c46a";
  ctx.arc(50, 50, 30, 0, 2 * Math.PI);
  ctx.fill();
  document.write("</div>");
}
</script>

</body>
</html>

Output:

HTML canvas globalCompositeOperation Property

Enjoy coding!