SlideShare ist ein Scribd-Unternehmen logo
1 von 33
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

Weitere ähnliche Inhalte

Ähnlich wie Drawing in HTML5 Open House

Leaving Flatland: Getting Started with WebGL- SXSW 2012
Leaving Flatland: Getting Started with WebGL- SXSW 2012Leaving Flatland: Getting Started with WebGL- SXSW 2012
Leaving Flatland: Getting Started with WebGL- SXSW 2012
philogb
 
Develop With Pleasure Deploy With Fun Glass Fish And Net Beans For A Better...
Develop With Pleasure  Deploy With Fun  Glass Fish And Net Beans For A Better...Develop With Pleasure  Deploy With Fun  Glass Fish And Net Beans For A Better...
Develop With Pleasure Deploy With Fun Glass Fish And Net Beans For A Better...
railsconf
 

Ähnlich wie Drawing in HTML5 Open House (20)

Svcc 2013-css3-and-mobile
Svcc 2013-css3-and-mobileSvcc 2013-css3-and-mobile
Svcc 2013-css3-and-mobile
 
Academy PRO: HTML5 API graphics
Academy PRO: HTML5 API graphicsAcademy PRO: HTML5 API graphics
Academy PRO: HTML5 API graphics
 
Leaving Flatland: Getting Started with WebGL- SXSW 2012
Leaving Flatland: Getting Started with WebGL- SXSW 2012Leaving Flatland: Getting Started with WebGL- SXSW 2012
Leaving Flatland: Getting Started with WebGL- SXSW 2012
 
Html 5 mobile - nitty gritty
Html 5 mobile - nitty grittyHtml 5 mobile - nitty gritty
Html 5 mobile - nitty gritty
 
Advanced Web Graphics with Canvas
Advanced Web Graphics with CanvasAdvanced Web Graphics with Canvas
Advanced Web Graphics with Canvas
 
Responsive Web Design: Clever Tips and Techniques
Responsive Web Design: Clever Tips and TechniquesResponsive Web Design: Clever Tips and Techniques
Responsive Web Design: Clever Tips and Techniques
 
HTML5DevConf 2013 (October): WebGL is a game changer!
HTML5DevConf 2013 (October): WebGL is a game changer!HTML5DevConf 2013 (October): WebGL is a game changer!
HTML5DevConf 2013 (October): WebGL is a game changer!
 
Html5 more than just html5 v final
Html5  more than just html5 v finalHtml5  more than just html5 v final
Html5 more than just html5 v final
 
WT-4064, Build Rich Applications with HTML5 and WebGL, by Tony Parisi
WT-4064, Build Rich Applications with HTML5 and WebGL, by Tony ParisiWT-4064, Build Rich Applications with HTML5 and WebGL, by Tony Parisi
WT-4064, Build Rich Applications with HTML5 and WebGL, by Tony Parisi
 
HTML5 and Other Modern Browser Game Tech
HTML5 and Other Modern Browser Game TechHTML5 and Other Modern Browser Game Tech
HTML5 and Other Modern Browser Game Tech
 
Rich Media Advertising with SVG and JavaScript
Rich Media Advertising with SVG and JavaScriptRich Media Advertising with SVG and JavaScript
Rich Media Advertising with SVG and JavaScript
 
WebGL, HTML5 and How the Mobile Web Was Won
WebGL, HTML5 and How the Mobile Web Was WonWebGL, HTML5 and How the Mobile Web Was Won
WebGL, HTML5 and How the Mobile Web Was Won
 
D3.js and SVG
D3.js and SVGD3.js and SVG
D3.js and SVG
 
Familiar HTML5 - 事例とサンプルコードから学ぶ 身近で普通に使わているHTML5
Familiar HTML5 - 事例とサンプルコードから学ぶ 身近で普通に使わているHTML5Familiar HTML5 - 事例とサンプルコードから学ぶ 身近で普通に使わているHTML5
Familiar HTML5 - 事例とサンプルコードから学ぶ 身近で普通に使わているHTML5
 
Everything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the WebEverything is Awesome - Cutting the Corners off the Web
Everything is Awesome - Cutting the Corners off the Web
 
Building Rich Internet Applications with HTML5 and WebGL
Building Rich Internet Applications with HTML5 and WebGLBuilding Rich Internet Applications with HTML5 and WebGL
Building Rich Internet Applications with HTML5 and WebGL
 
資料視覺化 - D3 的第一堂課 | WeiYuan
資料視覺化 - D3 的第一堂課 | WeiYuan資料視覺化 - D3 的第一堂課 | WeiYuan
資料視覺化 - D3 的第一堂課 | WeiYuan
 
Web Vector Graphics
Web Vector GraphicsWeb Vector Graphics
Web Vector Graphics
 
Neptue Graph Database - 0 to Production
Neptue Graph Database - 0 to ProductionNeptue Graph Database - 0 to Production
Neptue Graph Database - 0 to Production
 
Develop With Pleasure Deploy With Fun Glass Fish And Net Beans For A Better...
Develop With Pleasure  Deploy With Fun  Glass Fish And Net Beans For A Better...Develop With Pleasure  Deploy With Fun  Glass Fish And Net Beans For A Better...
Develop With Pleasure Deploy With Fun Glass Fish And Net Beans For A Better...
 

Mehr von Noam Kfir

Mehr von Noam Kfir (16)

Agile Mind Games and the Art of Self-Delusion
Agile Mind Games and the Art of Self-DelusionAgile Mind Games and the Art of Self-Delusion
Agile Mind Games and the Art of Self-Delusion
 
Testers and Coders - Blurring the Lines
Testers and Coders - Blurring the LinesTesters and Coders - Blurring the Lines
Testers and Coders - Blurring the Lines
 
TDD and the Legacy Code Black Hole
TDD and the Legacy Code Black HoleTDD and the Legacy Code Black Hole
TDD and the Legacy Code Black Hole
 
TypeScript Modules
TypeScript ModulesTypeScript Modules
TypeScript Modules
 
There Is No JavaScript
There Is No JavaScriptThere Is No JavaScript
There Is No JavaScript
 
Angular on ASP.NET MVC 6
Angular on ASP.NET MVC 6Angular on ASP.NET MVC 6
Angular on ASP.NET MVC 6
 
Meteor
MeteorMeteor
Meteor
 
Clean code
Clean codeClean code
Clean code
 
Maximizing UI Automation – A Case Study
Maximizing UI Automation – A Case StudyMaximizing UI Automation – A Case Study
Maximizing UI Automation – A Case Study
 
Web components
Web componentsWeb components
Web components
 
HTML5 and the Evolution of the Web
HTML5 and the Evolution of the WebHTML5 and the Evolution of the Web
HTML5 and the Evolution of the Web
 
Git Workflows
Git WorkflowsGit Workflows
Git Workflows
 
Getting Started with Git: A Primer for SVN and TFS Users
Getting Started with Git: A Primer for SVN and TFS UsersGetting Started with Git: A Primer for SVN and TFS Users
Getting Started with Git: A Primer for SVN and TFS Users
 
Building Cross-Platform JavaScript Apps using Cordova
Building Cross-Platform JavaScript Apps using CordovaBuilding Cross-Platform JavaScript Apps using Cordova
Building Cross-Platform JavaScript Apps using Cordova
 
Telerik Platform
Telerik PlatformTelerik Platform
Telerik Platform
 
Profiling JavaScript Performance
Profiling JavaScript PerformanceProfiling JavaScript Performance
Profiling JavaScript Performance
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 

Kürzlich hochgeladen (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 

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

Hinweis der Redaktion

  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