Canvas element
Sponsored Links
This presentation is the property of its rightful owner.
1 / 45

element PowerPoint PPT Presentation

  • Uploaded on
  • Presentation posted in: General

<canvas> element. The <canvas> element. Used to dynamically draw graphics using javascript. Capable of drawing paths, circles, rectangles, text, and images. . Declaring a <canvas> element. <canvas id = "tutorial" width = " 150 " height = "150" ></canvas >

Download Presentation


An Image/Link below is provided (as is) to download presentation

Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author.While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server.

- - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - -

Presentation Transcript

<canvas> element

The <canvas> element

  • Used to dynamically draw graphics using javascript.

  • Capable of drawing paths, circles, rectangles, text, and images.

Declaring a <canvas> element


  • Similar to the <img> element, except it doesn’t support alt or srcattributes.

  • Defaults to width=“300” and height=“150” if not supplied.

  • </canvas> is required!

The rendering context

  • The <canvas> is initially blank.

  • To use it, you must use a script to

    • Find it in the DOM tree.

    • Access the rendering context

    • Draw to it.

Accessing the render context

varcanvas =document.getElementById('tutorial');


  • Access the drawing context using the getContext()method.

  • getContext() takes two values:

    • 2d – 2D rendering context similar to SKIA Graphics Library (used by Android).

    • 3d – Gives developers a context to OpenGLES 2.0

Complete Example



<title>Canvas tutorial</title>


window.onload=function draw(){

var canvas =document.getElementById('tutorial');







canvas { border: 1px solid black; }







Canvas Grid / Coordinate Space

  • The originof the grid is in the top left corner.

  • Each unit on the grid is 1 pixel.

How to draw rectangles

  • The canvas only supports one primitive shape – rectangles.

  • Three functions to draw rectangles:

    • fillRect(x, y, width, height)

    • strokeRect(x, y, width, height);

    • clearRect(x, y, width, height);

Parameter List Explained

  • x – position on the canvas’ x-axis relative to the origin

  • y – position on the canvas’ y-axis relative to the origin

  • width – the specified width of the rectangle

  • height – the specified height of the rectangle

Draw rectangle functions

  • fillRect() – draws a filled/solid rectangle

  • strokeRect() – draws a rectangular outline

  • clearRect() – clears the specified area and makes it fully transparent

Rectangle functions




Canvas tips

  • Fill – solid shape

  • Stroke – outlined shape

  • Clear – erases

    • Use clearRect() to erase the entire canvas or just parts of it. Necessary for animations.


  • To draw shapes other than rectangles, you must use a path.

  • Paths are a combination of straight and curved segments.

Steps for using a path

  • Create a path

  • Specify paths to be drawn (repeat as necessary)

  • Close the path

  • Stroke and/or fill the path

Path Methods

  • beginPath() – creates a new path.

  • closePath() – tries to close the shape of the object from the current point to the starting point.

Path draw methods

  • lineTo(x, y) – used for drawing straight lines.

  • arc(x, y, radius, startAngle, endAngle, anticlockwise) – for drawing arcs or circles

  • quadraticCurveTo(cp1x, cp1y, x, y) – draw curves with one control point.

  • bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) – draw curves with two control points.

  • rect(x, y, width, height) – draws a rectangular path.

Quadratic vs Bezier

  • Takes time to understand and use well because it’s hard to visualize in your head. Therefore you constantly have to go back and forth between code and result to make sure your drawing is correct.

Path tip

  • lineTo(), quadraticCurveTo(), and bezierCurveTo() use the previous path’s ending point as the starting point for their new segment.

  • Use moveTo(x, y) to move to a different location on the canvas without drawing anything.


  • arc(x, y, radius, startAngle, endAngle, anticlockwise) – for drawing arcs or circles

  • x,y is your arc’s center

  • startAngle and endAngle are measured in radians

    • Math.PI/2 radians === 90°

    • Math.PIradians === 180°

    • 2 * Math.PI radians === 360 °

Step by Step







Convert Degrees to Radians

  • var radians = (Math.PI/180)*degrees.

Your turn

  • Make this weird shape

Adding some color

  • By default, stroke and fill are set to black.

  • You can set the fill color using the fillStyle property

  • You can set the stroke color using the strokeStyle property.

Adding some color

  • Both fillStyle and strokeStyle take a CSS color value represented as a string.

    // these all set the fillStyle to 'orange'





Sticky colors

  • If you set the fillStyle or strokeStyle properties, the new value becomes the default color used for drawing all shapes.

  • Every time you want to use a new color, you must reassign fillStyle and strokeStyle.

Applying other styles

  • globalAlpha – applies transparency to all shapes drawn

  • lineWidth – sets the current thickness of line

  • lineCap – determines how end points of a line are drawn.

  • Gradients

  • Shadows

Saving and Restoring State

  • The canvas object keeps track of several things

    • strokeStyle

    • fillStyle

    • lineWidth

    • Etc.

  • At times, a developer may want to drastically change the current canvas settings temporarily.

save() and restore()

  • Rather than having to save the state of the canvas yourself, the canvas provides a save() method to do this for you.

  • The restore() method will discard any changes made to the canvas and restore the previously saved state.

States stored on a stack

  • Every time the save method is called, the current canvas state is pushed onto a stack.

  • You can call the save method as many times as you like.

  • Every time the restore method is called, the last saved state is returned from the stack and all saved settings are restored.

save() and restore() tip

  • Make sure your save() and restore() methods are always paired.

  • If they aren’t paired, “weird” things will start happening.

  • To avoid this problem, I always declare both at the same time and then fill in the middle.

save() and restore() example

  • http://jsfiddle.net/blinkmacalahan/BrefR/


Canvas Transforms

  • The canvas has several transformation methods that make complex drawings easier.

  • The 3 important transform methods are

    • Translate

    • Rotate

    • Scale

Transform Tip

  • When applying transforms to the canvas, you’ll almost ALWAYS use save() and restore()


  • Used to move the canvas and its origin to a different point on the grid.


  • translate(x,y)

    • x – the amount to move left or right

    • y – the amount to move up of down

  • x,y are relative to the canvas’s current origin

    • translate(0,0) will move your origin 0 pixels to the left and 0 pixels down. It will not move your origin to the top left of the canvas.

Translate Example

  • http://jsfiddle.net/blinkmacalahan/MVQyR/


  • rotate(angle) – rotates the canvas clockwise by angle radians.

  • The rotation center is always the canvas origin.

  • To change the center point, you’ll need to use the translate() method.


  • An easy way to think about rotation is to get a piece of paper and pretend its your canvas.

  • Place your finger at the canvas’ origin and rotate the piece of paper around your finger.

Rotate Example

  • http://jsfiddle.net/blinkmacalahan/vYbbr/

How to make a square a diamond

  • Translate to the center of your square

  • Rotate Math.PI/4 radians

  • Translate negatively half the square width and half the square height.

  • Draw the rectangle at 0,0


  • scale(x,y) – decreases/increases the units on the canvas grid.

  • x – scale factor for horizontal direction. Defaults to 1.0.

  • y – scale factor for vertical direction. Defaults to 1.0.

Make a spinning sun.

Useful Links

  • Canvas Examples

  • MDN Canvas Tutorial

  • Canvas Deep Dive (Really Good resource which has good coverage/examples of how to use the canvas).

  • Login