Download presentation
Presentation is loading. Please wait.
Published byDamian Melton Modified over 9 years ago
1
element
2
The element Used to dynamically draw graphics using javascript. Capable of drawing paths, circles, rectangles, text, and images.
3
Declaring a element Similar to the element, except it doesn’t support alt or src attributes. Defaults to width=“300” and height=“150” if not supplied. is required!
4
The rendering context The is initially blank. To use it, you must use a script to 1.Find it in the DOM tree. 2.Access the rendering context 3.Draw to it.
5
Accessing the render context var canvas = document.getElementById('tutorial'); var ctx = canvas.getContext('2d'); Access the drawing context using the getContext() method. getContext() takes two values: 1.2d – 2D rendering context similar to SKIA Graphics Library (used by Android). 2.3d – Gives developers a context to OpenGLES 2.0
6
Complete Example Canvas tutorial window.onload = function draw(){ var canvas = document.getElementById('tutorial'); if (canvas.getContext){ var ctx = canvas.getContext('2d'); } canvas { border: 1px solid black; }
7
Canvas Grid / Coordinate Space The origin of the grid is in the top left corner. Each unit on the grid is 1 pixel.
8
How to draw rectangles The canvas only supports one primitive shape – rectangles. Three functions to draw rectangles: 1.fillRect(x, y, width, height) 2.strokeRect(x, y, width, height); 3.clearRect(x, y, width, height);
9
Parameter List Explained 1.x – position on the canvas’ x-axis relative to the origin 2.y – position on the canvas’ y-axis relative to the origin 3.width – the specified width of the rectangle 4.height – the specified height of the rectangle
10
Draw rectangle functions fillRect() – draws a filled/solid rectangle strokeRect() – draws a rectangular outline clearRect() – clears the specified area and makes it fully transparent
11
Rectangle functions fillRect(0,0,200,200);clearRect(0,0,200,200);strokeRect(0,0,200,200);
12
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.
13
Paths To draw shapes other than rectangles, you must use a path. Paths are a combination of straight and curved segments.
14
Steps for using a path 1.Create a path 2.Specify paths to be drawn (repeat as necessary) 3.Close the path 4.Stroke and/or fill the path
15
Path Methods beginPath() – creates a new path. closePath() – tries to close the shape of the object from the current point to the starting point.
16
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.
17
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.
18
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.
19
arc() 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.PI radians === 180° 2 * Math.PI radians === 360 °
20
Step by Step x,y radius startAngleendAngle anticlockwise
21
Final
22
Convert Degrees to Radians var radians = (Math.PI/180)*degrees.
23
Your turn Make this weird shape
24
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.
25
Adding some color Both fillStyle and strokeStyle take a CSS color value represented as a string. // these all set the fillStyle to 'orange' ctx.fillStyle = "orange"; ctx.fillStyle = "#FFA500"; ctx.fillStyle = "rgb(255,165,0)"; ctx.fillStyle = "rgba(255,165,0,1)";
26
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.
27
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
28
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.
29
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.
30
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.
31
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.
32
save() and restore() example http://jsfiddle.net/blinkmacalahan/BrefR/
33
Transformations
34
Canvas Transforms The canvas has several transformation methods that make complex drawings easier. The 3 important transform methods are 1.Translate 2.Rotate 3.Scale
35
Transform Tip When applying transforms to the canvas, you’ll almost ALWAYS use save() and restore()
36
Translate Used to move the canvas and its origin to a different point on the grid.
37
Translate 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.
38
Translate Example http://jsfiddle.net/blinkmacalahan/MVQyR/
39
Rotate 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.
40
Rotate 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.
41
Rotate Example http://jsfiddle.net/blinkmacalahan/vYbbr/
42
How to make a square a diamond 1.Translate to the center of your square 2.Rotate Math.PI/4 radians 3.Translate negatively half the square width and half the square height. 4.Draw the rectangle at 0,0
43
Scaling 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.
44
Make a spinning sun.
45
Useful Links Canvas Examples MDN Canvas Tutorial Canvas Deep Dive (Really Good resource which has good coverage/examples of how to use the canvas). Canvas Deep Dive
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.