SELA OPEN HOUSE
November 12, 2013

Canvas
Drawing as Da Vinci on a browser

Sebastian Pederiva
Senior Consultant
@spederiv...
Agenda
1.

Canvas
• Shapes
• States
• Text & Shadows

2.

SVG
• Introduction
• Samples

3.

Canvas vs. SVG

4.

WebGL
• Sa...
Samples
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

www.cuttherope.ie
www.drawastickman.com
www.lucidchart.com/pages/examples/flow...
Canvas
• An HTML5 element that allows for
dynamic, scriptable rendering of 2D shapes and
bitmaps
• Simple API: 45 methods,...
Canvas Browser Support

© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel

5
Easy to Make Things Like:

<body>
<canvas height=”600”
width=”800”></canvas>

</body>

© Copyright SELA software & Educati...
Canvas API
shadowOffsetX
shadowOffsetY
shadowBlur
shadowColor

save
restore
scale
rotate
translate
transform
setTransform
...
Getting the Context (APIs)

var canvas =
document.getElementById("canvas");
var ctx = canvas.getContext("2d");

© Copyrigh...
Drawing Simple Shapes
• Lines
o lineTo - Draws a straight line from the previous point

• Rectangles
o fillRect - draw fil...
Drawing Simple Shapes:
Examples
//Draw a circumference
cxt.arc(50, 50, 50, 0, Math.PI * 2, true);
cxt.stroke();
//Draw a d...
Shape Styles
• Styles
o fillStyle - set the colors used for rendering filled shapes
o strokeStyle - set the colors used fo...
Shape Styles: Examples
//Linear Gradient
var grad = cxt.createLinearGradient(0, 0, 200, 0);
grad.addColorStop(0, 'yellow')...
Complex Shapes
• Path & Subpath
• Paths are points connected by lines (straight or
curved)
• BeginPath & ClosePath
Attribu...
Complex Shapes

© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel

14
States
o Drawing on the Canvas makes use of a stack of drawing
“states”
o A state stores Canvas data of elements drawn
o T...
Text & Pattern
• Creating a Pattern – use the createPattern(image,
repetition) function
• fillText and strokeText – use fo...
Images on Canvas
o Canvas Image API can load in image data and apply
directly to canvas Image data can be cut and sized to...
Canvas Pitfalls
• Canvas is stupid – no memory of what you drew
last
• Not all operations were created equal. Some are
mor...
Introduction to SVG
• SVG stands for Scalable Vector Graphics
• Defines graphics by using an XML model;
embedded in HTML b...
SVG – Browser Support

© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel

20
SVG Sample
<svg width="400" height="200" xmlns="http://www.w3.org/2000/svg">
<rect fill="red" x="20" y="20" width="100" he...
SVG is awesome!

22
Canvas vs. SVG

© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel

23
When to Use Canvas?
Screen Capture

Interactive
Charts, Graphs
Static Images
Complex scenes,
lots of objects

Video
Manipu...
Performance Comparison

25
WebGL
•
•
•
•

Enables 3D graphics
Conforms to OpenGL ES 2.0
Used in HTML5 canvas elements
Supported in Firefox 4 and abov...
WebGL – Browser Support

© Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel

27
WebGL
var canvas = document.getElementById("glcanvas");
initWebGL(canvas);

// Initialize the GL context

// Only continue...
WebGL Example

http://lab.aerotwist.com/webgl/undulating-monkey/
http://inear.se/beanstalk/

© Copyright SELA software & E...
Resources
Articles
1. www.html5canvastutorials.com
2. html5doctor.com/an-introduction-to-the-canvas-2d-api/
3. http://josh...
Q&A
Let’s Play!
Summary
The Canvas is a new HTML5 element
that brings a lot of power to the
client side
It enables an interactive drawing
...
Upcoming SlideShare
Loading in...5
×

Drawing in HTML5 Open House

924

Published on

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
924
On Slideshare
0
From Embeds
0
Number of Embeds
1
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&apos;t know is that WebGL is actually a 2D API, not a 3D API. WebGL only cares about 2 things. Clipspace coordinates in 2DColors
  • Transcript of "Drawing in HTML5 Open House"

    1. 1. SELA OPEN HOUSE November 12, 2013 Canvas Drawing as Da Vinci on a browser Sebastian Pederiva Senior Consultant @spederiva Noam Kfir Senior Consultant @NoamKfir http://blogs.microsoft.co.il/blogs/zurdoil http://noam.kfir.cc
    2. 2. Agenda 1. Canvas • Shapes • States • Text & Shadows 2. SVG • Introduction • Samples 3. Canvas vs. SVG 4. WebGL • Samples
    3. 3. Samples 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. www.cuttherope.ie www.drawastickman.com www.lucidchart.com/pages/examples/flowchart_software slides.html5rocks.com/#canvas-2d-example www.picozu.com/editor www.neave.com/webcam/html5 worldsbiggestpacman.com www.visitnmc.com disneydigitalbooks.go.com/tron mudcu.be/sketchpad snappyTree 12. SVG Filter Effects 13. n-e-r-v-o-u-s.com/cellCycle/ 14. http://jsfiddle.net/g105b/Z4TFh/ 3
    4. 4. Canvas • An HTML5 element that allows for dynamic, scriptable rendering of 2D shapes and bitmaps • 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 4
    5. 5. Canvas Browser Support © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 5
    6. 6. 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 6
    7. 7. Canvas API shadowOffsetX shadowOffsetY shadowBlur shadowColor save restore scale rotate translate transform setTransform clearRect fillRect strokeRect globalAlpha globalCompositeOperation strokeStyle fillStyle CanvasGradient createLinearGradient CanvasGradient createRadialGradient CanvasPattern createPattern lineWidth lineCap lineJoin miterLimit drawFocusRing beginPath closePath moveTo lineTo quadraticCurveTo bezierCurveTo arcTo rect arc fill stroke clip isPointInPath drawImage font textAlign textBaseline fillText strokeText TextMetrics measureText ImageData createImageData ImageData createImageData ImageData getImageData putImageData addColorStop width width height CanvasPixelArray data length getter setter © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 7
    8. 8. Getting the Context (APIs) var canvas = document.getElementById("canvas"); var ctx = canvas.getContext("2d"); © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 8
    9. 9. Drawing Simple Shapes • Lines o lineTo - Draws a straight line from the previous point • Rectangles o fillRect - draw filled rectangles o strokeRect - draw the borders of a rectangle o clearRect - Clears the specified area making it fully transparent • Circles & Arcs o arc – draw an arc without dependencies o arcTo – draw an arc connected to the previous point © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 9
    10. 10. Drawing Simple Shapes: Examples //Draw a circumference cxt.arc(50, 50, 50, 0, Math.PI * 2, true); cxt.stroke(); //Draw a diagonal cxt.moveTo(0, 0); cxt.lineTo(500, 500); cxt.stroke(); //Draw a rectangle cxt.strokeRect(50, 250, 150, 100); © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 10
    11. 11. Shape Styles • Styles o fillStyle - set the colors used for rendering filled shapes o strokeStyle - set the colors used for rendering strokes • Gradient o createLinearGradient – create a linear gradient object o createRadialGradient – create a radial gradient object © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 11
    12. 12. Shape Styles: Examples //Linear Gradient var 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 Gradient var 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); © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 12
    13. 13. Complex Shapes • Path & Subpath • Paths are points connected by lines (straight or curved) • BeginPath & ClosePath Attribute Description lineTo(x, y) Draws a straight line from the previous point rect(x, y, w, h) Adds a new closed subpath representing the given rectangle arc(x, y, radius, startAngle, endAngle, anticlockwise) Adds an arc described by the circumference of the circle described by the arguments arcTo(x1, y1, x2, y2, radius) Adds a subpath connecting two points by an arc of the defined radius bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) Adds cubic Bézier curve connected to the previous point with the given control points. quadraticCurveTo(cpx, cpy, x, y) Adds a quadratic Bézier curve with the given control points © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 13
    14. 14. Complex Shapes © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 14
    15. 15. States o Drawing on the Canvas makes use of a stack of drawing “states” o A state stores Canvas data of elements drawn o Transformations and clipping regions use data stored in states o Save() and Restore() o Save() o Pushes the current state to the stack o Restore() o Restores the last state saved from the stack 15
    16. 16. Text & Pattern • Creating a Pattern – use the createPattern(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 16
    17. 17. Images on Canvas o Canvas Image API can load in image data and apply directly to canvas Image data can be cut and sized to desired portions o drawImage o 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 getImageData o ctx.getImageData(sx, sy, sw, sh); 17
    18. 18. Canvas Pitfalls • Canvas is stupid – no memory of what you drew last • Not all operations were created equal. Some are more expensive than others – Shadows, clipping and composition operations are more expensive as they require an additional intermediate • Use feature detection to detect a canvas and available 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 18
    19. 19. 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, and re-edited in 2011 19
    20. 20. SVG – Browser Support © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 20
    21. 21. SVG Sample <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
    22. 22. SVG is awesome! 22
    23. 23. Canvas vs. SVG © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 23
    24. 24. When to Use Canvas? Screen Capture Interactive Charts, Graphs Static Images Complex scenes, lots of objects Video Manipulation Web Advertising High-Fidelity Documents for Viewing, Printing 2D Gaming © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 24
    25. 25. Performance Comparison 25
    26. 26. WebGL • • • • Enables 3D graphics Conforms to OpenGL ES 2.0 Used in HTML5 canvas elements Supported in Firefox 4 and above and Chrome 9 and above © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 26
    27. 27. WebGL – Browser Support © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 27
    28. 28. WebGL var canvas = document.getElementById("glcanvas"); initWebGL(canvas); // Initialize the GL context // Only continue if WebGL is available and working if (gl) { gl.clearColor(0.0, 0.0, 0.0, 1.0); gl.enable(gl.DEPTH_TEST); gl.depthFunc(gl.LEQUAL); gl.clear(gl.COLOR_BUFFER_BIT|gl.DEPTH_BUFFER_BIT); } // // // // Set clear color to black, fully opaque Enable depth testing Near things obscure far things 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 don't have a GL context, give up now if (!gl) { console.log("Unable to initialize WebGL. Your browser may not support it."); } } © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 28
    29. 29. WebGL Example http://lab.aerotwist.com/webgl/undulating-monkey/ http://inear.se/beanstalk/ © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 29
    30. 30. Resources Articles 1. www.html5canvastutorials.com 2. html5doctor.com/an-introduction-to-the-canvas-2d-api/ 3. http://joshondesign.com/p/books/canvasdeepdive/toc.html 4. fhtr.org/canvasfilters 5. westciv.com 6. www.canvasdemos.com 7. http://www.html5gamedevelopment.com / http://html5gameengine.com 8. 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/ Frameworks 1. www.kineticjs.com 2. easeljs.com 3. pixastic.com 4. paperjs.org 5. raphaeljs.com 30
    31. 31. Q&A
    32. 32. Let’s Play!
    33. 33. Summary The Canvas is a new HTML5 element that brings a lot of power to the client side It enables an interactive drawing surface The future: Hardware-Accelerated HTML5 Canvas We made a game! © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 33

    ×