Quantcast

Creating Vector Masks with HTML5 Canvas Element

With the canvas element present in HTML5, a lot of interesting things such as games, video effects and graphs etc can be created.  It can also be used to produce some slightly less complex effects, like manipulating images on the page. In this tutorial we would use the canvas element to create vector masks and use them to modify images. For this purpose, first we need a canvas tag in our page:


This just sets up a simple canvas with the width and height of our image. We have chosen these dimensions so that it does not take up any more space than is needed. Next in JavaScript we will get the canvas and its drawing context in JavaScript:

So now we are ready to begin drawing our image into the canvas.

We have our canvas set up, now we need to draw the image into that canvas. We can do this easily, but we need an HTML img element with our image in order to draw it. We could grab an <img> tag from our page, but we can do it using JavaScript.

Here we are creating a new element for our image. Since we can’t draw the image until it has been downloaded, we need to wait for onload to draw it. Inside of the onload listener, we call the ctx.drawImage(), and pass it the img element. We also pass 0, 0 meaning we want to draw 0 pixels from the top and left.

In the canvas, we can use a technique called clipping. We can use a path we define to specify that future operations should only affect the area within the path. Since the canvas is transparent, if we create a clipping path, and then draw the image, the image will only show up inside the shape of that path. So let’s draw a circle, clip to that path, and draw the image:

You may notice the ctx.save() and ctx.restore() calls. This is because anything we try to do to the canvas after we clip it will only work within the clipping region. We call save() before we clip and then call restore() after, and the state of the canvas will be restored to before the clipping was applied. Everything you drew will remain, but the clipping definition will be gone. So the entire thing can also be done without clipping, but clipping can be used to further enhance the beauty of the overall effects.

Looking for a quality hosting service? here are a few I suggest.
BlueHost | HostGator | Media Temple
Admin
Admin
Ali has been an entrepreneur in web, video and related technologies. Having worked with many business across the globe, Ali stands truly a great pillar in the business working with him.