150 Chapter 5—Canvas
The circle is the source (A); the rectangle is the destination (B). Let’s use the Porter-
Duff terms to explain the different methods, because they are much more intui-
tive and describe more precisely what is going on.
With source-over, we draw A over B; with source-in, only that part of A that is
in B; with source-out, only that part of A that is outside of B; and with source-
atop, we draw both A and B but only the part of A that overlaps B. The second
line reverses the whole thing, so we do not need to explain it again.
The method lighter adds colors in the overlapping area, which makes it lighter.
copy eliminates B and only draws A, and xor removes the intersection of A and
B. The question mark indicates that vendor-specific composting operations are
also allowed, similar to the getContext() method.
Unfortunately, compositing is not yet fully implemented in any browser, which
makes it difficult to sensibly present all methods. We will pick two and take a look
at some examples for using the operations destination-in and lighter.
If we use destination-in to combine image and text, we can achieve a cutout
effect, as shown in Figure 5.31. First, we draw the image with drawImage(), set
the compositing method, and then insert the text with a maximum width of 1080
pixels. The text formatting corresponds to a font-size of 600 px with a text an-
chor point at the center top and a 60 pixel border with round line caps and joins:
context.drawImage(image,0,0,1200,600);
context.globalCompositeOperation = 'destination-in';
context.strokeText('HTML5',600,50,1080);