a blog for those who code

Thursday 15 October 2015

Beginning with Canvas element in HTML5

In this post we will be discussing about <canvas> element in HTML5. The <canvas> element in HTML5 can be used to kill flash from the browser. According to W3C ,<canvas> element provides scripts with a resolution-dependent bitmap canvas, which can be used for rendering graphs, game graphics, art, or other visual images on the fly. The canvas can be used to do the animations, to display videos or to display a webcam stream.

Lets take an example, place the below code in your HTML page. It will define an area of 100 X 100 pixels in your webpage.

<canvas id="canvas" width="100" height="100"></canvas>

Since canvases by default are transparent, you will see nothing. To make it visible you have to write a CSS like #canvas border: 2px solid red which will create a border of 2px around the area. To get the canvas object in the JavaScript you have to write code like var canvas = document.getElementId("canvas"); With this code you will have a canvas object which will be useful for performing the animation.

As of October 2015, Browser support of Canvas element are :

PC : http://caniuse.com/#search=canvas


Getting a 2D Context associated with the canvas

var context = canvas.getContext('2d');
context.fillStyle='#0000FF';
context.fillRect(0,0,50,50);

The above code will create a rectangle of width 50 pixels and height 50 pixels and fill it with blue color. Below are the properties and methods of context object which can be used for styling or drawing.

fillStyle - It is a property of the context which can take a color, a pattern or a gradient. The default value of fillStyle is black color. This property is used to determine how to render the filled part of the drawing.

fillRect (x, y, width, height) - It is a method which draws a filled rectangle. x and y are the coordinates of the top left corner of the rectangle.

strokeStyle - It is a property of the context which can take a color, a pattern or a gradient. The default value of strokeStyle is black color. This property is used to determine how to render the shape of the drawing.

strokeRect (x, y, width, height) - It is a method which draws a rectangle in wireframe mode.

clearRect (x, y, width, height) - It is a method which erases a specified rectangle.

Below example shows, how different properties and methods work :

Check at : http://codepen.io/codingdefined/pen/dYVgmv

In our next post we will be discussing about 2D Transformation using the canvas and context objects in HTML5. Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

No comments:

Post a Comment