HTML and CSS Reference
In-Depth Information
The Canvas Clipping Region
ByusingtheCanvasclippingregion,wecanlimitthedrawingareaforapathanditssubpaths.
We do this by first setting rect() attribute of the context to a rectangle that encompasses the
region we would like to draw in and then calling the clip() function. This will set the clip
region to be the rectangle we defined with the rect() method call. Now, no matter what we
draw onto the current context, it will display only the portion that is in this region. Think of
this as a sort of mask that you can use for your drawing operations. Example 2-5 shows how
this works, producing the clipped result shown in Figure 2-10 .
In this example, we will implement the save() and restore() Canvas functions around the
red circle. If we did not, the blue circle would not be drawn. You can test this for yourself by
commenting out the save() and restore() lines in Example 2-5 .
Example 2-5. The Canvas clipping region
function
function drawScreen () {
//draw a big box on the screen
context . fillStyle = "black" ;
context . fillRect ( 10 , 10 , 200 , 200 );
context . save ();
context . beginPath (); //clip the canvas to a 50×50 square starting at 0,0
context . rect ( 0 , 0 , 50 , 50 );
context . clip ();
//red circle
context . beginPath ();
context . strokeStyle = "red" ;
context . lineWidth = 5 ;
context . arc ( 100 , 100 , 100 , ( Math . PI / 180 ) * 0 , ( Math . PI / 180 ) * 360 , false
false );
//full circle
context . stroke ();
context . closePath ();
context . restore ();
//reclip to the entire canvas
context . beginPath ();
context . rect ( 0 , 0 , 500 , 500 );
context . clip ();
//draw a blue line that is not clipped
context . beginPath ();
Search WWH ::




Custom Search