JavaScript Canvas Clipping & Basic Compositing |
Written by Ian Elliot | ||||
Monday, 23 December 2019 | ||||
Page 3 of 3
outThis pair of modes displays only the parts of the image outside the overlap.
The same two rectangles drawn before are shown using source-out on the left and destination-out on the right. You can see that the red rectangle has been clipped to what is outside of the blue and vice versa. Again to find out what happens in the case of intermediate transparency it is best to see what the equations are. For source-out we have: An = (1-Ad)*As Cn = (1-Ad)*Cs You can see that the Alpha is a product and so if the destination is 1 or source is 0 the pixel is not rendered. The color value is multiplied by one minus destination Alpha so it only shows within background pixels. For destination-out we have: An = (1-As)*Ad Cn = (1-As)*Cd and only the pixels in the destination that are outside the source are left. You can see the effect of overlapping the same blue and red rectangles but with Alpha set to 0.5 for source-out (left) and destination-out (right):
A Demonstration ProgramIt is slightly harder to create the dual source and destination illustrations shown above than you might realize. The problem is that while you can display both left and right rectangle pairs by changing the composite mode between the two, some compositing modes wipe the canvas outside of the source or destination. We have to isolate the two pairs of rectangles from one another. The solution is to use a clip path to restrict where the compositing mode is applied, i.e. apply clipping to compositing. The program is: ctx.fillStyle = "rgba(0,0,255,0.5"; ctx.fillRect(100, 50, 100, 50); ctx.fillRect(300, 50, 100, 50); var myPath = new Path2D(); myPath.rect(75,25,200,125); ctx.save(); ctx.clip(myPath ); ctx.globalCompositeOperation="source-out"; ctx.fillStyle = "rgba(255,0,0,0.5"; ctx.fillRect(150, 75, 100, 50); ctx.restore(); myPath = new Path2D(); myPath.rect(275,25,200,125); ctx.clip(myPath); ctx.globalCompositeOperation="destination-out"; ctx.fillStyle = "rgba(255,0,0,0.5"; ctx.fillRect(350, 75, 100, 50); Notice the use of save and restore to allow two rectangular clipping paths to be used. You can change the CompositeOperation and fillStyle parameters to see the effects of different configurations. In book but not included in this extract:
Summary
Now available as a paperback or ebook from Amazon.JavaScript Bitmap Graphics
|
||||
Last Updated ( Monday, 10 February 2020 ) |