element

advertisement
<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>
• Similar to the <img> element, except it doesn’t
support alt or src attributes.
• 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
1. Find it in the DOM tree.
2. Access the rendering context
3. Draw to it.
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
Complete Example
<html>
<head>
<title>Canvas tutorial</title>
<script type="text/javascript">
window.onload = function draw(){
var canvas = document.getElementById('tutorial');
if (canvas.getContext){
var ctx = canvas.getContext('2d');
}
}
</script>
<style type="text/css">
canvas { border: 1px solid black; }
</style>
</head>
<body>
<canvas id="tutorial" width="150" height="150"></canvas>
</body>
</html>
Canvas Grid / Coordinate Space
• The origin of 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:
1. fillRect(x, y, width, height)
2. strokeRect(x, y, width, height);
3. clearRect(x, y, width, height);
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
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
fillRect(0,0,200,200);
clearRect(0,0,200,200);
strokeRect(0,0,200,200);
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.
Paths
• 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
1. Create a path
2. Specify paths to be drawn (repeat as
necessary)
3. Close the path
4. 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()
• 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 °
Step by Step
anticlockwise
endAngle
startAngle
x,y
radius
Final
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'
ctx.fillStyle = "orange";
ctx.fillStyle = "#FFA500";
ctx.fillStyle = "rgb(255,165,0)";
ctx.fillStyle = "rgba(255,165,0,1)";
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/
Transformations
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
Transform Tip
• When applying transforms to the canvas,
you’ll almost ALWAYS use save() and restore()
Translate
• Used to move the canvas and its origin to a
different point on the grid.
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.
Translate Example
• http://jsfiddle.net/blinkmacalahan/MVQyR/
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.
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.
Rotate Example
• http://jsfiddle.net/blinkmacalahan/vYbbr/
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
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.
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).
Download