The <canvas> Element
 

The HTML canvas is used to draw graphics that include everything from simple lines to complex graphic objects.

The <canvas> element is defined by: 

<canvas id=“canvas1” width=“200” height=“100”>
</canvas>

 

Note!
The <canvas> element is only a container for graphics. You must use a script to actually draw the graphics (usually JavaScript).
 

The <canvas> element must have an id attribute so it can be referred to by JavaScript:

<

p dir=”ltr”>

<html>
   <head></head>
   <body>
     <canvas id=“canvas1”
   width=“400” height=“300”></canvas>

   <script>
      var can = document.getElementById(“canvas1”);
      var ctx = can.getContext(“2d”);
   </script>

   </body>
</html>

 

getContext() returns a drawing context on the canvas. 

Note!
Basic knowledge of JavaScript is required to understand and use the Canvas.

Canvas Coordinates
 

The HTML canvas is a two-dimensional grid.
The upper-left corner of the canvas has the coordinates (0,0).

X coordinate increases to the right.
Y coordinate increases toward the bottom of the canvas.

Holla Tech - Learn HTML5

Note!
The <canvas> element is only a container for graphics.
 


Drawing Shapes
 

The fillRect(x, y, w, h) method draws a “filled” rectangle, in which w indicates width and h indicates height. The default fill color is black.

A black 100*100 pixel rectangle is drawn on the canvas at the position (20, 20):

var c=document.getElementById(“canvas1”);

var ctx=c.getContext(“2d”);
ctx.fillRect(20,20,100,100);

 

Result:

Holla Tech - Learn HTML5

 

The fillStyle property is used to set a color, gradient, or pattern to fill the drawing.
Using this property allows you to draw a green-filled rectangle.

var canvas=document.getElementById(“canvas1”);

var ctx=canvas.getContext(“2d”);
ctx.fillStyle =“rgba(0, 200, 0, 1)”;
ctx.fillRect (36, 10, 22, 22);

 

Result: 

Holla Tech - Learn HTML5

The canvas supports various other methods for drawing:

Draw a Line
moveTo(x,y): Defines the starting point of the line.
lineTo(x,y): Defines the ending point of the line.

Draw a Circle
beginPath(): Starts the drawing.
arc(x,y,r,start,stop): Sets the parameters of the circle.
stroke(): Ends the drawing.

Gradients
createLinearGradient(x,y,x1,y1): Creates a linear gradient.
createRadialGradient(x,y,r,x1,y1,r1): Creates a radial/circular gradient.

Drawing Text on the Canvas
Font: Defines the font properties for the text.
fillText(text,x,y): Draws “filled” text on the canvas.
strokeText(text,x,y): Draws text on the canvas (no fill).

 

Note!
There are many other methods aimed at helping to draw shapes and images on the canvas.
BACK NEXT

HTML MAIN COURSE PAGE

 

CONTACT HOLLA TECH LEARN SUPPORT