HTML canvas globalCompositeOperation Property

Introduction

Draw rectangles using two different globalCompositeOperation values.

Red rectangles are destination images.

Blue rectangles are source images:

View in separate window

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="180" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>
var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "red";
ctx.fillRect(20, 20, 75, 50);/*from   ww  w. j av a2s.  co  m*/
ctx.fillStyle = "blue";
ctx.globalCompositeOperation = "source-over";
ctx.fillRect(50, 50, 75, 50);
ctx.fillStyle = "red";
ctx.fillRect(150, 20, 75, 50);
ctx.fillStyle = "blue";
ctx.globalCompositeOperation = "destination-over";
ctx.fillRect(180, 50, 75, 50);
</script>

</body>
</html>

The globalCompositeOperation property sets or gets how a source image are drawn onto a destination image.

source image is the drawings you are about to place onto the canvas.

destination image is the drawings that are already placed onto the canvas.

Default value: source-over

context.globalCompositeOperation = "source-in";

Property Values

ValueDescription
source-over Default. Displays the source image over the destination image
source-atop Displays the source image on top of the destination image.
source-inDisplays the source image in to the destination 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 destination image on top of the source image.
destination-in Displays the destination image in to 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 destination image is ignored
xor The source image is combined by using an exclusive OR with the destination image



PreviousNext

Related