Monday, 11 May 2015

Miss Sunshine and HTML Canvas: Let's Draw Some Circles!

Miss Sunshine and HTML Canvas: Let's Draw Some Circles! Your browser does not support the canvas element.
I've realized that canvas combined with JavaScript is a powerful HTML element to create shapes, make animation and games.

I've created Miss Sunshine just with circles and lines. Let's dissect the code. First, create the canvas with <canvas> </canvas>. Get the context of canvas with variable of the canvas.getContext("2d") and store it in a variable.

Now the drawing begins! Create an object literal and store infos about what color to use, how circles and lins are drawn and the name of the function. Here is the syntax:

var x= {y:detailled information about the object}

We draw Miss Sunshine's head with the arc(x-coordinate,y-coordinate,radius,starting angle,ending angle) method. Now, a little bit of trigonometry is required.
Relax, just a little bit.
The total circumference of a circle (360°) is 2π thus to draw a circle the value of the starting angle is 0 and the ending angle 2π. Paint Miss Sunshine with your favourite color with fillyStyle="your color" and fill her with fill(). Here eyes and lips are created the same way. The lips are created with two small half circles and one big one. A half circle has the 180° (π) therefore the starting angle is π and the ending angle is 2π (or 0 to π depending on the direction).

Roll over the canvas and make her sky blue!

HTML and JavaScript Code