Using the HTML5 canvas clip method to hide certain content
Join the DZone community and get the full member experience.
Join For Freepeople 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.
source:
http://robertnyman.com/2011/07/26/using-the-html5-canvas-clip-method-to-hide-certain-content
Opinions expressed by DZone contributors are their own.
Trending
-
How Agile Works at Tesla [Video]
-
Integrating AWS With Salesforce Using Terraform
-
Building the World's Most Resilient To-Do List Application With Node.js, K8s, and Distributed SQL
-
Integration Testing Tutorial: A Comprehensive Guide With Examples And Best Practices
Comments