1. HTML CANVAS
The HTML canvas element provides HTML a bitmapped surface
to work with. It is used to draw graphics on the web page.
The HTML 5 <canvas> tag is used to draw graphics using
scripting language like JavaScript.
The <canvas> element is only a container for graphics, you must
need a scripting language to draw the graphics. The <canvas>
element allows for dynamic and scriptable rendering of 2D shapes
and bitmap images.
There are several methods in canvas to draw paths, boxes, circles,
text and add images.
2. HOW TO CREATE A HTML CANVAS?
A canvas is a rectangle like area on an HTML page. It is specified
with canvas element. By default, the <canvas> element has no
border and no content, it is like a container.
<canvas id = "mycanvas" width ="200"height ="100"></canvas>
Note: It is always necessary to specify the id attribute and the height
& width attribute to define the size of the canvas. You can have
multiple canvas elements on one HTML page.
3. HOW TO CREATE A HTML CANVAS?
Here is a simple <canvas> element which has only two specific
attributes width and height plus all the core HTML 5 attributes like id,
name and class, etc.
HTML 5 Canvas Tag Example:
<canvas id="myCanvas1" width="300" height="100"style="border:2px solid;">
HTML 5 canvas tag view
</canvas>
You can easily find that <canvas> element in the DOM
using getElementById() method as follows −
var canvas = document.getElementById("mycanvas");
4. THE RENDERING CONTEXT
The <canvas> is initially blank, and to display something, a script
first needs to access the rendering context and draw on it.
The canvas element has a D O M method called get Context , used to
obtain the rendering context and its drawing functions. This function
takes one parameter, the type of context2d.
var canvas = document.getElementById("mycanvas");
var ctx = canvas.getContext('2d');
5. DRAWING LINE ON CANVAS
If you want to draw a straight line on the canvas, you can use the
following two methods.
moveTo(x,y): It is used to define the starting point of the line.
lineTo(x,y): It is used to define the ending point of the line.
If you draw a line which starting point is (0,0) and the end point is
(200,100), use the stroke method to draw the line.
6. DRAWING RECTANGLE ON CAN VAS
There are three methods that draw rectangles on the canvas −
Here x and y specify the position on the canvas (relative to the origin)
of the top-left corner of the rectangle and width and height are width
and height of the rectangle.
Sr.No. Method and Description
1
fillRect(x,y,width,height)
This method draws a filled rectangle.
2
strokeRect(x,y,width,height)
This method draws a rectangular outline.
3
clearRect(x,y,width,height)
This method clears the specified area and makes it fully
transparent
7. DRAWING PATH ON CANVAS
The canvas paths allow you to draw custom shapes. In HTML5
canvas, a path consists of a list of zero or more subpaths. There are
one or more points in each subpath that are connected by straight
lines or curves. To create a custom shape perform the following steps
:
Use beginPath() method to start drawing the path.
Draw the path that makes a shape using lines, curves and other
primitives.
After creating the path, call fill() method to fills subpaths by using
the current fill style or stroke() method to render the strokes of the
current subpath by using the current stroke styles. Your shape will
not be visible until you call fill() or stroke() methods.
Now call closePath() method to close the current subpath and starts
a new subpath that has a start point that is equal to the end of the
closed subpath.
8. DRAWING BEZIERCURVE ON CANVAS
The bezierCurveTo() method adds a curve to the path by using the
control points that represent a cubic Bézier curve.
Use the stroke() or fill() method to draw the path.
A cubic bezier curve requires three points. The first two points are
control points that are used in the cubic Bézier calculation and the
last point is the ending point for the curve. The starting point for
the curve is the last point in the current path. If a path does not
exist, use the beginPath() and moveTo() methods to define a starting
point.
9. DRAWING BEZIERCURVE ON CANVAS
Start point: moveTo(20, 20)
Control point 1: bezierCurveTo(20, 100, 200, 100, 200, 20)
Control point 2: bezierCurveTo(20, 100, 200, 100, 200, 20)
End point: bezierCurveTo(20, 100, 200, 100, 200, 20)
10. DRAW ING BEZIERCU RVE ON CA NVAS (Syntax Parameter Values)
context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
Param Description
cp1x The x-coordinate of the first Bézier control point
cp1y The y-coordinate of the first Bézier control point
cp2x The x-coordinate of the second Bézier control point
cp2y The y-coordinate of the second Bézier control point
x The x-coordinate of the ending point
y The y-coordinate of the ending point
11. DRAWING QUADRATICCURVE ON CAN VAS
The quadraticCurveTo() method adds a curve to the current path by
using the control points that represent a quadratic Bézier curve.
Use the stroke() or fill() method to draw the path.
A quadratic Bézier curve requires two points. The first point is a
control point that is used in the quadratic Bézier calculation and the
second point is the ending point for the curve. The starting point for
the curve is the last point in the current path. If a path does not
exist, use the beginPath() and moveTo() methods to define a starting
point.
12. DRAWING QUADRATICCURVE ON CAN VAS
Syntax:context.quadraticCurveTo(cpx, cpy, x, y)
Parameter Values
P arameter Description
cpx The x-coordinate of the Bézier control point
cpy The y-coordinate of the Bézier control point
x The x-coordinate of the ending point
y The y-coordinate of the ending point
13. DRAWING QUADRATICCURVE ON CAN VAS
Start point: moveTo(20, 20)
Control point: quadraticCurveTo(20, 100, 200, 20)
End point: quadraticCurveTo(20, 100, 200, 20)
14. CANVAS - USI N G IMAGES
To draw an image on a canvas, use the following method:
● drawImage(image,x,y)
This method draws the given image onto the canvas. Here image is
a reference to an image or canvas object. x and y form the
coordinate on the target canvas where our image should be placed.
15. CANVAS - CREATE GRADIENTS
Gradients can be used to fill rectangles, circles, lines, text, etc.
Shapes on the canvas are not limited to solid colors.
There are two different types of gradients:
createLinearGradient(x,y,x1,y1) - creates a linear gradient
createRadialGradient(x,y,r,x1,y1,r1) - creates a
radial/circular gradient
Once we have a gradient object, we must add two or more color
stops.
The addColorStop() method specifies the color stops, and its
position along the gradient. Gradient positions can be anywhere
between 0 to 1.
To use the gradient, set the fillStyle or strokeStyle property to the
gradient, then draw the shape (rectangle, text, or a line).
16. CANVAS - CREATE GRADIENTS
Method Description
addColorStop(offset, color) This method adds a color stop with the given color to the
gradient at the given offset. Here 0.0 is the offset at one end of
the gradient, 1.0 is the offset at the other end.
createLinearGradient(x0
, y0, x1, y1)
This method returns a CanvasGradient object that represents a
linear gradient that paints along the line given by the
coordinates represented by the arguments. The four arguments
represent the starting point (x1,y1) and end point (x2,y2) of the
gradient.
createRadialGradient(x0
, y0, r0, x1, y1, r1)
This method returns a CanvasGradient object that represents a
radial gradient that paints along the cone given by the circles
represented by the arguments. The first three arguments
define a circle with coordinates (x1,y1) and radius r1 and the
second a circle with coordinates (x2,y2) and radius r2.
17. HTML5 - Styles and Colors
HTML5 canvas provides the following two important
properties to apply colors to a shape −
Sr.No. Method and Description
1
fillStyle
This attribute represents the color or style to use inside
the shapes.
2
strokeStyle
This attribute represents the color or style to use for the
lines around shapes.
The fillStyle property sets or returns the color,
gradient, or pattern used to fill the drawing.
The default value is #000000 (solid black).
18. HTML5 - Styles and Colors
The strokeStyle Property (Set stroke color/style)
The fillRect() Method (Draw a filled rectangle)
The rect() Method (Draw an unfilled rectangle)
19. Canvas - Text and Fonts
HTML5 canvas provides capabilities to create text using different font and text properties listed below −
Sr.No. Property and Description
1
font [ = value ]:This property returns the current font settings and can be set, to change
the font.
2
textAlign [ = value ]:This property returns the current text alignment settings and can be
set, to change the alignment. The possible values are start, end, left, right, and center.
3
textBaseline [ = value ]:This property returns the current baseline alignment settings and
can be set, to change the baseline alignment. The possible values are top, hanging, middle
, alphabetic, ideographic and bottom.
4
fillText(text, x, y [, maxWidth ] ):This property fills the given text at the given position
indicated by the given coordinates x and y.
5
strokeText(text, x, y [, maxWidth ] ):This property strokes the given text at the given
position indicated by the given coordinates x and y.
20. Canvas - Text and Fonts
Syntax
context.font = "italic small-caps bold 12px arial"
Values Description
font-style •Normal ,italic ,oblique
font-variant •Normal ,small-caps
font-weight •Normal,bold,bolder,lighter,100,200
font-size The font size in pixels{10px,25px,etc}
font-family The font family{ Areal, Times new roman}
Drawing Text on the Canvas
To draw text on a canvas, the most important property and methods are:
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)
21. Canvas - Pattern and Shadow
Create Pattern
There is following method required to create a pattern on the canvas −
Sr.No. Method and Description
1
createPattern(image, repetition)
This method will use image to create the pattern. The second argument could be a string
with one of the following values: repeat, repeat-x, repeaty, andno-repeat. If the empty string
or null is specified, repeat will. be assumed
Description
The createPattern() method repeats the specified element in the specified direction.
The element can be an image, video, or another <canvas> element.
The repeated element can be used to draw/fill rectangles, circles, lines etc.
JavaScript syntax:context.createPattern(image, "repeat|repeat-x|repeat-y|no-repeat");
22. Canvas - Pattern and Shadow
Create Pattern
There is following method required to create a pattern on the canvas −
Param Description
image Specifies the image, canvas, or video element of the pattern to use
repeat Default. The pattern repeats both horizontally and vertically
repeat-x The pattern repeats only horizontally
repeat-y The pattern repeats only vertically
no-repeat The pattern will be displayed only once (no repeat)
23. Canvas -Shadow
In HTML5 canvas, you can add shadows on a shape, a line, text, or an image which can create a sense of third
dimension. To add shadows with the HTML5 Canvas, you can use the following properties of the canvas context.
shadowOffsetX,shadowOffsetY,shadowColor,shadowBlur.
shadowOffsetX() Property
The property is used to get or set the horizontal distance of a shadow from a shape. You can use positive or negative
values to control the position of a shadow. The default value is zero.
Syntax:
ctx.shadowOffsetX = h_distance;Where h_distance (type: number) is the horizontal distance of a shadow from a shape.
shadowOffsetY() Property
The property is used to get or set the vertical distance of a shadow from a shape. You can use positive or negative
values to control the position of a shadow. The default value is zero.
Syntax:
ctx.shadowOffsetX = v_distance;Where v_distance (type: number) is the vertical distance of a shadow from a shape.
24. Canvas -Shadow
shadowColor() Property
The property is used to get or set the color to use for shadows.
Syntax:
ctx.shadowColorWhere shadowColor (type: string) is the CSS color.
shadowBlur() Property
The property is used to get or set the current level of blur that is applied to shadows.
Syntax:
ctx.shadowBlur = blur_valueWhere blur_value is the amount of blur (type: number) that is applied to shadows.
25. Canvas - Pattern and Shadow
HTML5 canvas provides capabilities to create nice shadows around the drawings. All drawing operations are affected
by the four global shadow attributes.
Sr.No. Property and Description
1
shadowColor [ = value ]:This property returns the current shadow color and can
be set, to change the shadow color.
2
shadowOffsetX [ = value ]:This property returns the current shadow offset X
and can be set, to change the shadow offset X.
3
shadowOffsetY [ = value ]:This property returns the current shadow offset Y
and can be set, change the shadow offset Y.
4
shadowBlur [ = value ]:This property returns the current level of blur applied to
shadows and can be set, to change the blur level.
26. HTML5 Canvas - Save and Restore States
HTML5 canvas provides two important methods to save and restore the canvas states. The canvas
drawing state is basically a snapshot of all the styles and transformations that have been applied and consists of the
followings −
The transformations such as translate, rotate and scale etc.
The current clipping region.
The current values of the following attributes − strokeStyle, fillStyle, globalAlpha, lineWidth,shadowOffsetX,
shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline.
Canvas states are stored on a stack every time the save method is called, and the last saved state is returned from the
stack every time the restore method is called.
Sr. No. Method and Description
1
save()
This method pushes the current state onto the stack.
2
restore()
This method pops the top state on the stack, restoring the context to that state.
27. Canvas - Translation
HTML5 canvas provides translate(x, y) method which is used to move the canvas and its origin to a
different point in the grid.
Here argument x is the amount the canvas is moved to the left or right, and y is the amount it's moved up or down.
The translate() method is used to move the origin point to a specified point in a canvas.
Syntax :
ctx.translate(x, y)
28. Canvas - Rotation
HTML5 canvas provides rotate(angle) method which is used to rotate the canvas around the current origin.
This method only takes one parameter and that's the angle the canvas is rotated by. This is a clockwise rotation
measured in radians.
Using context’s rotate(angle) method you can rotate the canvas’s coordinate system around its origin. The coordinate
system is rotated by angle radians, clockwise. Anything already on the canvas is unaffected, but subsequent drawing
operations are rotated.