HTML5 Graphics

825 views

Published on

This presentation will show you the principles of HTML5 graphics using Canvas, SVG and WebGL

Published in: Technology, Art & Photos
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
825
On SlideShare
0
From Embeds
0
Number of Embeds
136
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • Use getContext() to access the 2D rendering context
  • Uses the standard screen-based coordinate systemarcToFor example an rounded box
  • Sample: Simple.html
  • Sample: Gradient.html
  • Paths are a list of subpathsSubpaths are one or more points connected by lines (straight or curved)Creating pathsBeginPath - Function call to start a pathClosePath - Function call to end a path
  • Sample: Complex.htm
  • The state includes the current transform, Fill colorsstroke colorscurrent fontfew other variables. You can save this state by pushing it onto a stack using the save() function
  • WebGL makes it possible to display amazing realtime 3D graphicsWhat many people don't know is that WebGL is actually a 2D API, not a 3D API. WebGL only cares about 2 things. Clipspace coordinates in 2DColors
  • HTML5 Graphics

    1. 1. SELA OPEN HOUSEJune 9, 2013CanvasSebastian PederivaSenior Consultant@spederivablogs.microsoft.co.il/blogs/zurdoilDrawing as Da Vinci on a browser
    2. 2. Agenda1. Canvas• Shapes• States• Text & Shadows2. SVG• Introduction• Samples3. Canvas vs. SVG4. WebGL• Samples
    3. 3. Canvas• An HTML5 element that allows fordynamic, scriptable rendering of 2D shapes andbitmaps• Simple API: 45 methods, 21 attributes• Supported by modern browsers• Created by Apple© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 3
    4. 4. Canvas Browser Support© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 4
    5. 5. Easy to Make Things Like:<body><canvas height=”600”width=”800”></canvas></body>© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 5
    6. 6. Canvas API© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 6saverestorescalerotatetranslatetransformsetTransformglobalAlphaglobalCompositeOperationstrokeStylefillStyleCanvasGradient createLinearGradientCanvasGradient createRadialGradientCanvasPattern createPatternlineWidthlineCaplineJoinmiterLimitdrawFocusRingshadowOffsetXshadowOffsetYshadowBlurshadowColorclearRectfillRectstrokeRectbeginPathclosePathmoveTolineToquadraticCurveTobezierCurveToarcTorectarcfillstrokeclipisPointInPathdrawImagefonttextAligntextBaselinefillTextstrokeTextTextMetrics measureTextImageData createImageDataImageData createImageDataImageData getImageDataputImageDataaddColorStopwidthwidthheightCanvasPixelArray datalengthgettersetter
    7. 7. var canvas =document.getElementById("canvas");var ctx = canvas.getContext("2d");Getting the Context (APIs)© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 7
    8. 8. Drawing Simple Shapes• Lineso lineTo - Draws a straight line from the previous point• Rectangleso fillRect - draw filled rectangleso strokeRect - draw the borders of a rectangleo clearRect - Clears the specified area making it fullytransparent• Circles & Arcso arc – draw an arc without dependencieso arcTo – draw an arc connected to the previous point© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 8
    9. 9. Drawing Simple Shapes:Examples© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 9//Draw a circumferencecxt.arc(50, 50, 50, 0, Math.PI * 2, true);cxt.stroke();//Draw a diagonalcxt.moveTo(0, 0);cxt.lineTo(500, 500);cxt.stroke();//Draw a rectanglecxt.strokeRect(50, 250, 150, 100);
    10. 10. • Styleso fillStyle - set the colors used for rendering filled shapeso strokeStyle - set the colors used for rendering strokes• Gradiento createLinearGradient – create a linear gradientobjecto createRadialGradient – create a radial gradientobjectShape Styles© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 10
    11. 11. Shape Styles: Examples© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 11//Linear Gradientvar grad = cxt.createLinearGradient(0, 0, 200, 0);grad.addColorStop(0, yellow);grad.addColorStop(1, blue);cxt.fillStyle = grad;cxt.fillRect(50, 250, 150, 100);//Radial Gradientvar grd = context.createRadialGradient(150, 150, 0, 150, 150, 200);grd.addColorStop(0, "red");grd.addColorStop(1, "blue");context.fillStyle = grd;context.fillRect(0, 0, 300, 300);
    12. 12. DescriptionAttributeDraws a straight line from the previous pointlineTo(x, y)Adds a new closed subpath representing the given rectanglerect(x, y, w, h)Adds an arc described by the circumference of the circle described bythe argumentsarc(x, y, radius, startAngle,endAngle, anticlockwise)Adds a subpath connecting two points by an arc of the defined radiusarcTo(x1, y1, x2, y2, radius)Adds cubic Bézier curve connected to the previous point with the givencontrol points.bezierCurveTo(cp1x, cp1y, cp2x,cp2y, x, y)Adds a quadratic Bézier curve with the given control pointsquadraticCurveTo(cpx, cpy, x, y)Complex Shapes• Path & Subpath• Paths are points connected by lines (straight orcurved)• BeginPath & ClosePath© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 12
    13. 13. © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 13Complex Shapes
    14. 14. Stateso Drawing on the Canvas makes use of a stack of drawing“states”o A state stores Canvas data of elements drawno Transformations and clipping regions use data stored instateso Save() and Restore()o Save()o Pushes the current state to the stacko Restore()o Restores the last state saved from the stack14
    15. 15. Text & Pattern• Creating a Pattern – use thecreatePattern(image, repetition) function• fillText and strokeText – use for text creation© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 15
    16. 16. Images on Canvaso Canvas Image API can load in image data and applydirectly to canvas Image data can be cut and sized todesired portionso drawImageo ctx.drawImage(image, dx, dy);o ctx.drawImage(image, dx, dy, dw, dh);o ctx.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh);o getImageDatao ctx.getImageData(sx, sy, sw, sh);16
    17. 17. Canvas Pitfalls• Canvas is stupid – no memory of what you drewlast• Not all operations were created equal. Some aremore expensive than others– Shadows, clipping and composition operations aremore expensive as they require an additionalintermediate• Use feature detection to detect a canvas andavailable features• Reading and writing to video memory is slow• Avoid setting attributes unnecessarily© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 17
    18. 18. Introduction to SVG• SVG stands for Scalable Vector Graphics• Defines graphics by using an XML model;embedded in HTML by using an <svg> tag• Vector Based• Use Geometry• Is part of the DOM• Can be used from an external .svg• Became a recommendation of W3C in 2001, andre-edited in 201118
    19. 19. SVG – Browser Support© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 19
    20. 20. SVG Sample20<svg width="400" height="200" xmlns="http://www.w3.org/2000/svg"><rect fill="red" x="20" y="20" width="100" height="75" /><rect fill="blue" x="50" y="50" width="100" height="75" /></svg>
    21. 21. 21SVG is awesome!
    22. 22. Canvas vs. SVG© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 22
    23. 23. When to Use Canvas?© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 23Screen CaptureComplexscenes, lots ofobjectsVideoManipulationWeb AdvertisingInteractiveCharts, GraphsStatic ImagesHigh-FidelityDocuments forViewing, Printing2D Gaming
    24. 24. Performance Comparison24
    25. 25. WebGL• Enables 3D graphics• Conforms to OpenGL ES 2.0• Used in HTML5 canvas elements• Supported in Firefox 4 and above and Chrome 9and above© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 25
    26. 26. WebGL – Browser Support© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 26
    27. 27. WebGL© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 27var canvas = document.getElementById("glcanvas");initWebGL(canvas); // Initialize the GL context// Only continue if WebGL is available and workingif (gl) {gl.clearColor(0.0, 0.0, 0.0, 1.0); // Set clear color to black, fully opaquegl.enable(gl.DEPTH_TEST); // Enable depth testinggl.depthFunc(gl.LEQUAL); // Near things obscure far thingsgl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT); // Clear the color as well as the depth buffer.}function initWebGL(canvas) {// Initialize the global variable gl to null.gl = null;try {// Try to grab the standard context. If it fails, fallback to experimental.gl = canvas.getContext("webgl");}catch(e) {}// If we dont have a GL context, give up nowif (!gl) {console.log("Unable to initialize WebGL. Your browser may not support it.");}}
    28. 28. © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 28WebGL Examplehttp://lab.aerotwist.com/webgl/undulating-monkey/http://inear.se/beanstalk/
    29. 29. Resources29Articles1. www.html5canvastutorials.com2. html5doctor.com/an-introduction-to-the-canvas-2d-api/3. http://joshondesign.com/p/books/canvasdeepdive/toc.html4. fhtr.org/canvasfilters5. westciv.com6. www.canvasdemos.com7. http://www.html5gamedevelopment.com / http://html5gameengine.com8. http://www.sitepoint.com/gaming-battle-on-the-high-seas-part-1/9. http://www.sitepoint.com/the-complete-guide-to-building-html5-games-with-canvas-and-svg/10. http://labs.skookum.com/demos/barcampclt_physics/Frameworks1. www.kineticjs.com2. easeljs.com3. pixastic.com4. paperjs.org5. raphaeljs.com
    30. 30. Samples301. www.cuttherope.ie2. www.drawastickman.com3. www.lucidchart.com/pages/examples/flowchart_software4. slides.html5rocks.com/#canvas-2d-example5. www.picozu.com/editor6. www.neave.com/webcam/html57. worldsbiggestpacman.com8. www.visitnmc.com9. disneydigitalbooks.go.com/tron10. mudcu.be/sketchpad11. snappyTree12. SVG Filter Effects13. n-e-r-v-o-u-s.com/cellCycle/14. http://jsfiddle.net/g105b/Z4TFh/
    31. 31. Q & A
    32. 32. Let’s Play!
    33. 33. Summary© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 33The Canvas is a new HTML5 elementthat brings a lot of power to theclient sideIt enables an interactive drawingsurfaceThe future: Hardware-AcceleratedHTML5 CanvasWe made a game!

    ×