Date post: | 10-May-2015 |
Category: |
Technology |
Upload: | david-voyles |
View: | 412 times |
Download: | 0 times |
Advanced HTML5: Diving into the Canvas TagDave VoylesSr. Tech Evangelist | Microsoft@DaveVoyles@gdiphilly
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?
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.
What we’ll cover
• Terms and technologies• 2D drawing basics• Drawing shapes and paths• Animations
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!)
What is the canvas?
A blank slate to draw graphs, game graphics, video, or other visual images on the fly.”
What is the canvas?
• 2D drawing tool within all modern browsers
• No downloads (plugins) required!
• Openly developed by the WC3 (WWW consortium)
Overview of the canvas
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
Browser Support
Uses of Canvas• Web apps
• Games
• Data visualization
Uses of Canvas
The Canvas Element
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
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>
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!}
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.
Rendering context
Two ways of drawing content: 2D or 3D (webGL)
var canvas = document.getElementById(‘myCanvas'); var ctx = canvas.getContext('2d');
A Simple Example
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
Result
(50,25)
(0,0)
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.
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);
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)
Transformations
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()
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
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
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
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);
Drawing Paths
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
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]
Drags the “pencil” to the x, y coordinates
lineTo(x, y) [“pencil” method]
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 }
Drawing Fonts
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
<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
Drawing Gradients
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
CSS Gradients
Canvas gradients aren’t widely used
Instead, most developers prefer CSS Gradients
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 */}
Popular Libraries
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
The Future of the Canvas
I don’t think HTML5 is going anywhere either.
Questions? Comments?
Survey: http://bit.ly/gdi-canvas