Create a canvas

Canvas is one of the most important in all the new HTML5 features.
<canvas id=”myCanvas” width=”300″ height=”200″ > </canvas >

The code above creates a canvas in you web page with 200px height. Imagine it’s a real life canvas, but without background color. Of course, you can add your favorite background and border style with css, like below: background color is light blue and canvas border is yellow and 5px wide.

Source Code Box: Create a canvas(Browser: IE9+,Firefox24+,Chrome29+, Safari5.1+,Opera17+,iOS3.2+,Android3.0+)

Notes for Javascript novice

In this and the following HTML5 series of articles, we will use Javascript to manipulate HTML5 features. But, don’t worry. All the javascripts in these articles are almost self-explicit; we also add necessary comments to make sure you understand the javascripts without difficulty even though you are not familiar with Javascript.

Fill a rectangle

In the code below, we firstly still create a canvas with an id="mycanvas2" for further reference. You may notice the tag pair <script> .... </script>. The code inside script tag pair is javascript. Now let’s explain the javascript code. We use the code var cvs=document.getElementById("myCanvas2"); to get the already created canvas, mycanvas2. Since there are two types of canvas, two dimension and three dimension, we need to further specify that we will use 2d(two dimension) canvas in this example with the code cvs.getContext("2d"). Now it’s the turn to draw something on our canvas. We create a rectangle with two corner upper-left(0,0) , lower-right (200,75); and fill(fillStyle) it with color blue(#0000ff).

Source Code Box: Fill a rectangle(Browser: IE9+,Firefox24+,Chrome29+, Safari5.1+,Opera17+,iOS3.2+,Android3.0+)

Fill a circle

In the code below, we firstly still create a canvas with an id="mycanvas3" for further reference. Similiar to the code in the previous example, we get the already created 2d canvas, mycanvas3. We set circle border color as red with code ctx.strokeStyle; filled color as yellow with code ctx.fillStyle. The coordinates of circle center is (100,100). The radius of circle is 75. By specifying starting angle and ending angle, we can define a circle, half circle or a arc with code ctx.arc(centreX,centreY,radius,startAngle,endAngle,false);. The last parameter of false indicates the arc is clockwise; otherwise, true indicates counter-clockwise. Last, we draw the circle border with code ctx.stroke();; and fill the circle with code ctx.fill();

Source Code Box: Fill a circle(Browser: IE9+,Firefox24+,Chrome29+, Safari5.1+,Opera17+,iOS3.2+,Android3.0+)