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:

A picture of a looking glass with red and white shapes in it

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. :-)

Posted in Developing,HTML5/HTML/XHTML,JavaScript,Technology |

4 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>