1 / 45

<canvas> element

<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 >

phuong
Télécharger la présentation

<canvas> element

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. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. <canvas> element

  2. The <canvas> element • Used to dynamically draw graphics using javascript. • Capable of drawing paths, circles, rectangles, text, and images.

  3. Declaring a <canvas> element <canvasid="tutorial"width="150"height="150"></canvas> • 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!

  4. 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.

  5. Accessing the render context varcanvas =document.getElementById('tutorial'); varctx=canvas.getContext('2d'); • 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

  6. Complete Example <html> <head> <title>Canvas tutorial</title> <scripttype="text/javascript"> window.onload=function draw(){ var canvas =document.getElementById('tutorial'); if(canvas.getContext){ varctx=canvas.getContext('2d'); } } </script> <styletype="text/css"> canvas { border: 1px solid black; } </style> </head> <body> <canvasid="tutorial"width="150"height="150"></canvas> </body> </html>

  7. Canvas Grid / Coordinate Space • The originof 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: • fillRect(x, y, width, height) • strokeRect(x, y, width, height); • clearRect(x, y, width, height);

  9. 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

  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 • Create a path • Specify paths to be drawn (repeat as necessary) • Close the path • 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.PIradians === 180° • 2 * Math.PI radians === 360 °

  20. Step by Step anticlockwise endAngle startAngle radius x,y

  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 • Translate • Rotate • 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 • 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

  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).

More Related