In the next example, called ch07_clip, we will use another useful canvas operation. We will use a clipping mask to restrict a layer to a small square, creating a peeking window, just like the one in the Google Maps application.
For this example, we extend our init function with a custom layer. We register the required precompose and postcompose events on it, and then silently add it to the map:
var clippedLayer = new ol.layer.Tile({
source: new ol.source.MapQuest({
layer: 'osm'
}),
zIndex: 9999
});
clippedLayer.on('precompose', function (evt) {
var ctx = evt.context;
ctx.save();
ctx.beginPath();
ctx.rect(20, 20, 100, 100);
ctx.clip();
});
clippedLayer.on('postcompose', function (evt) {
evt.context.restore();
});
clippedLayer.setMap(map);The trick of clipping a context is this: we save the context and then draw a rectangle. First, we begin a path. Next, we define the position of the rectangle relative to the top-left corner of the canvas in the first two arguments. In the second two arguments, we define the width and the height of the rectangle, respectively. Instead of drawing the rectangle on the canvas by calling the stroke or fillRect methods, we convert the path to a clipping mask using the context's clip method.
When the layer is drawn (the postcompose event), we restore the saved context, disabling the clipping mask for every other layer. If we skip this step, the entire map is clipped to the defined mask.
If you load the example, you can see our peeking window showing a MapQuest layer over our base map:
