Over a million developers have joined DZone.

Using the HTML5 canvas clip method to hide certain content

DZone's Guide to

Using the HTML5 canvas clip method to hide certain content

· Web Dev Zone
Free Resource

Never build auth again! Okta makes it simple to implement authentication, authorization, MFA and more in minutes. Try the free developer API today! 

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);

        // Clip the view of the canvas

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

Source: http://robertnyman.com/2011/07/26/using-the-html5-canvas-clip-method-to-hide-certain-content

Launch your application faster with Okta’s user management API. Register today for the free forever developer edition!


Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}