Compositing means to combine several images into one single image.
In combination with the alpha property (transparency using either rgba or globalAlpha),
it is a very powerful tool for bringing elements from various scenes into a single
scene. In this tutorial, we will go through the basics of how the geature works
on canvas.
Compositing can be accomplished using the globalCompositeOperation attribute. Assuming
you are trying to composite two different images, the image you draw first is the
'source' and the second image is the 'destination'. Before drawing the destination,
you should mention the type of compositing you wish to do using the globalCompositeOperation
attribute. The attribute takes the following 12 values:
source-over: The destination image goes over the source. The destination will cover
parts of the source where they intersect.
source-in: Only those parts of the destination that intersect with the source are
visible.
source-out: Only those parts of the destination that fall outside the source are
visible.
source-atop: The source and parts of the destination that intersect with the source
are visible. Where the destination covers the source, the source is invisible.
destination-over: The source image goes over the destination and covers the intersecting
parts of the destination.
destination-in: Only those parts of the source that intersect with the destination
are visible.
destination-out: Only thoes parts of the source that fall outside the destination
are visible.
destination-atop: The destination and parts of the source that intersect with the
destination are visible. Where the source covers the destination, the destination
is invisible.
lighter: the portion where source and destination intersect appear lighter, with
the colour of the destination being dominant.
darker:
copy:
XOR: The intersecting pixels of the source and destination are XORed.
It is important to remember that you will get the above results only when both the
source and destination are opaque. If you introduce transparency to either the source
or destination, results will vary.
HTML Code
<html>
<head>
<script type="application/javascript">
function init() {
var canvas = document.getElementById("canvas");
if (canvas.getContext)
{
var ctx = canvas.getContext("2d");
//Load the images to be blended
var dove = new Image();
dove.src = "dove.png";
var flower = new Image();
flower.src = "flower.png";
//Draw the source image
dove.onload = function() {
ctx.drawImage(dove,25,25);
}
//Set the globalCompositeOperation to lighter
ctx.globalCompositeOperation = "lighter";
Note: Try out the other compositing options in the above code to see how they work.
Also, note that the globalCompositeOperation attribute affects all drawing on the
canvas.