Using the HTML5 canvas clip method to hide certain content
People are creating amazing things with HTML5 canvas
, especially combined with other HTML5 features. I thought I’d touch on a handy method that some people don’t seem to know about: canvas clip.
When it comes to presenting things on a canvas
, you can stage parts of it off the canvas area or load it somewhere else and then display it at will on the canvas. Another way of doing it, and also to easily create some interesting features is the clip
method.
Basically, what clip
does is that it offers a way to display what you want on a canvas through using any shape of your liking, and then calling clip
, thus hiding the other parts of the canvas.
I’ve put together a little canvas clip demo in my playground, which looks like this:
The magic in it is creating a number of shapes and then calling the clip
method, hiding everything that is positioned outside those areas. Breaking down the code, this is what it looks like:
(function() { var cvs = document.getElementById("canvas-clip"), ctx = cvs.getContext("2d"); // Create circle ctx.strokeStyle = "transparent"; ctx.arc(300, 100, 75, 0, Math.PI*2, false); // Create bottom shape of the looking glass ctx.strokeStyle = "#000"; ctx.lineWidth = "10"; ctx.moveTo(350, 50); ctx.lineTo(100, 300); ctx.closePath(); ctx.stroke(); ctx.fill(); // Clip the view of the canvas ctx.clip(); // Create rectangles that will shine through the clip ctx.fillStyle = "#fff"; ctx.fillRect(200, 0, 200, 200); ctx.fillStyle = "#f00"; ctx.fillRect(200, 0, 100, 100); ctx.fillRect(300, 100, 100, 100); })();
There you have it – another little trick up your sleeve. 🙂
I use this exact technique in a jquery plugin to do irregular area highlighting on images, using a second image as the source data for the highlight effect. Just hide everything *except* the area to be highlighted and render the whole image in a canvas over the background, and it creates a context-specific highlight effect.
Combined with globalCompositeOperation = “source-out” you can go one step further and create masks within the clipped area like this demo enabling you to have areas with holes.
Neat stuff…
Jamie,
Cool, thanks for sharing!
[…] wrote about it in Using the HTML5 canvas clip method to hide certain content, showing how to stage content and create a looking glass […]
good good. i will try