HTML5 Canvas
The HTML canvas is used to draw graphics that include everything from simple lines to complex graphic objects. The <canvas>
element is only a container for graphics. You must use JavaScript to actually draw the graphics. Canvas has several methods for drawing paths, boxes, circles, text, and adding images.
The <canvas>
element is defined by:
<canvas id=”canvas1" width=”200" height=”100">
</canvas>
The <canvas>
element always specify an id
attribute to be referred to in a script.
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.
Drawing Shapes
getContext() returns a drawing context on the canvas. The fillStyle property is used to set a color, gradient, or pattern to fill the drawing.
1.Rectangle
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. fillRect(20,20,100,100) indicates a black 100*100 pixel rectangle is drawn on the canvas at the position (20, 20):
Output:
2.Line
moveTo(x,y): Defines the starting point of the line.
lineTo(x,y): Defines the ending point of the line.
Output:
3.Circle
beginPath(): Starts the drawing.
arc(x,y,r,start,stop): Sets the parameters of the circle.
stroke(): Ends the drawing.
Output:
4.Gradiants
createLinearGradient(x,y,x1,y1): Creates a linear gradient.
createRadialGradient(x,y,r,x1,y1,r1): Creates a radial/circular gradient.
Output:
5.Text
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).
Output:
There are many other methods aimed at helping to draw shapes and images on the canvas.