52
Advanced HTML5: Diving into the Canvas Tag Dave Voyles Sr. Tech Evangelist | Microsoft @DaveVoyles @gdiphilly

Advanced html5 diving into the canvas tag

Embed Size (px)

DESCRIPTION

Dive into the HTML5 canvas tag and learn how it works in the 2D context

Citation preview

Page 1: Advanced html5 diving into the canvas tag

Advanced HTML5: Diving into the Canvas TagDave VoylesSr. Tech Evangelist | Microsoft@DaveVoyles@gdiphilly

Page 2: Advanced html5 diving into the canvas tag

Welcome!Who are you?

What do you hope to get out of this class?

Icebreaker: What is your favorite TV show or video game of the 90s?

Page 3: Advanced html5 diving into the canvas tag

About MePreviously a Sr. Engineer on the Xbox team at Comcast

Have been working in the games industry for nearly 5 years

I’m a recent transplant from Long Island, NY.

Page 4: Advanced html5 diving into the canvas tag

What we’ll cover

• Terms and technologies• 2D drawing basics• Drawing shapes and paths• Animations

Page 5: Advanced html5 diving into the canvas tag

What to expect

• Some of it may be over your head - Ask questions! Even I don’t know it all

• This is a high-level overview of a complicated subject

• Much of this info can be used in other places! (Games! Apps! Data Visualization!)

Page 6: Advanced html5 diving into the canvas tag

What is the canvas?

Page 7: Advanced html5 diving into the canvas tag

A blank slate to draw graphs, game graphics, video, or other visual images on the fly.”

What is the canvas?

Page 8: Advanced html5 diving into the canvas tag

• 2D drawing tool within all modern browsers

• No downloads (plugins) required!

• Openly developed by the WC3 (WWW consortium)

Overview of the canvas

Page 9: Advanced html5 diving into the canvas tag

Introduced by Apple, as part of WebKit in 2004, to show the power of desktop apps within their Safari browser.

Now a standard!

History of the canvas

Page 10: Advanced html5 diving into the canvas tag

Browser Support

Page 11: Advanced html5 diving into the canvas tag

Uses of Canvas• Web apps

• Games

• Data visualization

Page 12: Advanced html5 diving into the canvas tag

Uses of Canvas

Page 13: Advanced html5 diving into the canvas tag
Page 14: Advanced html5 diving into the canvas tag
Page 15: Advanced html5 diving into the canvas tag

The Canvas Element

Page 16: Advanced html5 diving into the canvas tag

The <canvas> element<canvas id=“myCanvas" width="150" height="150"></canvas>

• Only 2 attributes: Width & Height

• Default values for width and height: 300px x 150px

Page 17: Advanced html5 diving into the canvas tag

Fallback content

Older browsers may not support the <canvas> element

Therefore, we insert fallback text, just in case it won’t display

<canvas id=“myChart" width="150" height="150">

Current version of IE: 11 </canvas>

Page 18: Advanced html5 diving into the canvas tag

Checking for supportvar canvas = document.getElementById('tutorial'); if (canvas.getContext){

var ctx = canvas.getContext('2d'); // drawing code here

} else { // canvas-unsupported code here: Hey, you need to update your browser!}

Page 19: Advanced html5 diving into the canvas tag

The grid (coordinates)The canvas is a two-dimensional grid. The coordinate (0, 0) is at the upper-left corner of the canvas.

Along the X-axis, values increase from left to right.

Along the Y-axis, values increase from top to bottom.

Page 20: Advanced html5 diving into the canvas tag

Rendering context

Two ways of drawing content: 2D or 3D (webGL)

var canvas = document.getElementById(‘myCanvas'); var ctx = canvas.getContext('2d');

Page 21: Advanced html5 diving into the canvas tag

A Simple Example

Page 22: Advanced html5 diving into the canvas tag

Drawing via JavaScriptvar canvas = document.getElementById(“myCanvas");

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

ctx.fillRect(50, 25, 150, 100);

Parameters:

X: The x-coordinate of the upper-left corner of the rectangleY The y-coordinate of the upper-left corner of the rectangleWidth: The width of the rectangle, in pixelsHeight: The height of the rectangle, in pixels

Page 23: Advanced html5 diving into the canvas tag

Result

(50,25)

(0,0)

Page 24: Advanced html5 diving into the canvas tag

Properties•fillStyle:   can be a CSS color, a pattern, or a gradient. (Default color is black)

•strokeStyle: like fillStyle, but used for lines

•fillRect( x, y, width, height) draws a rectangle filled with the current fill style.

•strokeRect(x, y, width, height) draws an rectangle w/ current stroke style. Only draws edges.

•clearRect( x, y, width, height) clears the pixels in the specified rectangle.

Page 25: Advanced html5 diving into the canvas tag

ClearRect(x, y, width, height)<canvas id="myCanvas" width=“300" height="150"></canvas>

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

ctx.fillStyle = "red";ctx.fillRect (0, 0, 300, 150);ctx.clearRect(20, 20, 100, 50);

Page 26: Advanced html5 diving into the canvas tag

Draw the German Flag<canvas id="myCanvas" width=200 height=120></canvas>

var canvas = document.getElementById('myCanvas');var ctxt = canvas.getContext('2d');

ctx.fillStyle = '#000000'; // set color to blackctx.fillRect(0, 0, 200, 40); // draw (200x40 pixel) rectangle at (0,0ctx.fillStyle = '#FF0000'; // set color to red ctx.fillRect(0, 40, 200, 40); // draw (200x40 pixel) rectangle at (0,40) ctx.fillStyle = '#FFCC00'; // set color to gold ctx.fillRect(0, 80, 200, 40); // draw (200x40 pixel) rectangle at (0,80)

Page 27: Advanced html5 diving into the canvas tag

Transformations

Page 28: Advanced html5 diving into the canvas tag

Transformations

• Scale(): Scales the current drawing, bigger or smaller

• Rotate(): Rotates current drawing

• Translate(): Moves the (0,0) position on the canvas

• Transform(): Replaces current transform matrix for current drawing

• setTransform(): Resets current transform matrix to the identity matrix, then runs transform()

Page 29: Advanced html5 diving into the canvas tag
Page 30: Advanced html5 diving into the canvas tag

Rotate(angle [in radians])

<canvas id="myCanvas" width="300" height="200"></canvas>

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

ctx.rotate(20 * Math.PI / 180);ctx.fillRect(50, 20, 100, 50);

Save & Restore contextSave & Restore context (cont’d)

To calculate from degrees to radians: degrees * Math.PI/180

Page 31: Advanced html5 diving into the canvas tag

Scale (width, height)<canvas id="myCanvas" width=“300" height=“300"></canvas>

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

ctx.strokeRect(5, 5, 100, 30); // draw first rectanglectx.scale(2,2); // 2x width, 2x heightctx.strokeRect(5, 5, 100, 30); // draw second triangle

Page 32: Advanced html5 diving into the canvas tag

Transform (a,b,c,d,e,f)http://www.w3schools.com/tags/playcanvas.asp?filename=playcanvas_transformb&preval=1,0,0,1,0,0

A – Scales the drawing horizontallyB – Skew the drawing horizontally

C- Skew the drawing verticallyD - Scale the drawing vertically

E – Moves the drawing horizontallyF – Moves the drawing vertically

Page 33: Advanced html5 diving into the canvas tag

Translate (x, y)<canvas id="myCanvas" width=“300" height=“300"></canvas>

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

ctx.fillRect (10, 10, 100, 50);ctx.translate(70, 70);ctx.fillRect (10, 10, 100, 50);

Page 34: Advanced html5 diving into the canvas tag

Drawing Paths

Page 35: Advanced html5 diving into the canvas tag

Three steps are required:1. Begin the path – beginPath()2. Move the points – moveTo() or

lineTo()3. Stroke (outline) / Fill the path – stroke() or

fill()4. *Close the path – closePath()

*Note: When you call fill(), any open shapes are closed automatically, so you don’t need to call closePath(). This is not true when you use stroke(), though.

Drawing shapes using paths

Page 36: Advanced html5 diving into the canvas tag

Moves the “pencil” to the x, y coordinates

Doesn’t draw anything, but becomes part of the path

Think of it as lifting a pencil, then places it at this spot

moveTo(x, y) [“pencil” method]

Page 37: Advanced html5 diving into the canvas tag

Drags the “pencil” to the x, y coordinates

lineTo(x, y) [“pencil” method]

Page 38: Advanced html5 diving into the canvas tag

Drawing a trianglevar canvas = document.getElementById(‘myCanvas');

if (canvas.getContext){ var ctx = canvas.getContext('2d');

ctx.beginPath(); // starts drawing ctx.moveTo(75,50); // First point (left) ctx.lineTo(100,75); // Bottom point ctx.lineTo(100,25); // Top point ctx.fill(); // black is default }

Page 39: Advanced html5 diving into the canvas tag

Drawing Fonts

Page 40: Advanced html5 diving into the canvas tag

Unlike text on a webpage, there is no box model, so CSS layout techniques are not available, such as:- float, margin, padding, word wrap

Available attributes:• font (style, font variant, weight, size, line height,

family)• textAlign (start, end, left, right, center)• TextBaseline (top, hanging, middle, alphabetic,

ideographic, bottom)

Drawing Fonts

Page 41: Advanced html5 diving into the canvas tag

<canvas id=“myCanvas" width=“150” height=“100”></canvas>

var canvas = document.getElementById ('myCanvas'); // access the canvas object var ctx = canvas.getContext ('2d'); // access the canvas contextctx.fillRect (5,5,140,50); // fill rectangle with black color ctx.fillStyle = 'red'; // set text color to 'red'ctx.font = '40pt Arial'; // define the CSS font for writing textctx.fillText ('Text',1 0,50); // write the text 'Text‘

Drawing Text

Page 42: Advanced html5 diving into the canvas tag

Drawing Gradients

Page 43: Advanced html5 diving into the canvas tag

Drawing Gradients

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

var grd = ctx.createLinearGradient(0,0,170,0);grd.addColorStop(0,"black");grd.addColorStop(1,"white");

ctx.fillStyle=grd;ctx.fillRect(0,0,150,100);

Smooth transition between two colors

Page 44: Advanced html5 diving into the canvas tag

CSS Gradients

Canvas gradients aren’t widely used

Instead, most developers prefer CSS Gradients

Page 45: Advanced html5 diving into the canvas tag

CSS Gradients#grad{ background: -webkit-linear-gradient(left, white, black); /* For Safari 5.1 to 6.0 */ background: -o-linear-gradient(right, white, black); /* For Opera 11.1 to 12.0 */ background: -moz-linear-gradient(right white, black); /* For Firefox 3.6 to 15 */ background: linear-gradient(to right, white, black); /* Standard syntax */}

Page 46: Advanced html5 diving into the canvas tag

Popular Libraries

Page 47: Advanced html5 diving into the canvas tag

Popular Libraries• Impact.js  is gaming framework with 2D and 3D

capabilities• Turbulenz is a gaming framework with excellent

webGL support• Paper.js open source vector graphics scripting

framework that runs on top of the HTML5 Canvas• Canvas.js is an easy-to-use framework for creating

charts• Processing.js is a port of the Processing visualization

language• EaselJS is a library with a Flash-like API

• HTML5 Canvas Tutorials

Page 49: Advanced html5 diving into the canvas tag

The Future of the Canvas

Page 50: Advanced html5 diving into the canvas tag
Page 51: Advanced html5 diving into the canvas tag

I don’t think HTML5 is going anywhere either.

Page 52: Advanced html5 diving into the canvas tag

Questions? Comments?

Survey: http://bit.ly/gdi-canvas