SlideShare a Scribd company logo
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
Agenda
1.

Canvas
• Shapes
• States
• Text & Shadows

2.

SVG
• Introduction
• Samples

3.

Canvas vs. SVG

4.

WebGL
• Samples
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
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
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 & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel

6
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
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
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
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
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
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
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
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 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
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
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
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
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
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" height="75" />
<rect fill="blue" x="50" y="50" width="100" height="75" />
</svg>

21
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
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
Performance Comparison

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

More Related Content

Drawing in HTML5 Open House

  • 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. Agenda 1. Canvas • Shapes • States • Text & Shadows 2. SVG • Introduction • Samples 3. Canvas vs. SVG 4. WebGL • Samples
  • 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. Canvas Browser Support © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 5
  • 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. 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. 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. 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. 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. 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. 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. 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. Complex Shapes © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 14
  • 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. 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. 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. 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. 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. SVG – Browser Support © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 20
  • 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
  • 23. Canvas vs. SVG © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 23
  • 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
  • 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. WebGL – Browser Support © Copyright SELA software & Education Labs Ltd. 14-18 Baruch Hirsch St.Bnei Brak 51202 Israel 27
  • 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. 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. 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. Q&A
  • 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

Editor's Notes

  1. Use getContext() to access the 2D rendering context
  2. Uses the standard screen-based coordinate systemarcToFor example an rounded box
  3. Sample: Simple.html
  4. Sample: Gradient.html
  5. 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
  6. Sample: Complex.htm
  7. 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
  8. 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