html5 canvas api

101
HTML5 Canvas API Dr. Raymond Bond

Upload: tucker

Post on 23-Feb-2016

110 views

Category:

Documents


0 download

DESCRIPTION

HTML5 Canvas API. Dr. Raymond Bond. API Definition: “a bitmapped area of the screen that can be manipulated with JavaScript ”. Oreilly , HTML5 Canvas. Element Definition: “The HTML5 element is used to draw graphics, on the fly, via scripting (usually JavaScript) .”. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: HTML5 Canvas API

HTML5 Canvas API

Dr. Raymond Bond

Page 2: HTML5 Canvas API

API Definition:

“a bitmapped area of the screen that can be manipulated with JavaScript” Oreilly, HTML5 Canvas

Page 3: HTML5 Canvas API

Element Definition:

“The HTML5 <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript).”

http://www.w3schools.com/html/html5_canvas.asp

Page 4: HTML5 Canvas API

“HTML5 Canvas is the technology that has the best capability of replacing Flash functionalityon the web and mobile web.”

Oreilly, HTML5 Canvas

Page 5: HTML5 Canvas API

Support

Page 7: HTML5 Canvas API

Testing for Support

<script src="http://modernizr.com/downloads/modernizr-latest.js"></script>

if(Modernizr.canvas == true){startCanvasApp();}else{

//browser does not support canvas}

Page 8: HTML5 Canvas API

Canvas Element

<canvas id="myCanvas" width="200" height="100">

</canvas>

NOTE: Need id for script access.

Page 9: HTML5 Canvas API

• The <canvas> element is only a container for the graphics.

• A canvas can only be rectangular• You can have multiple <canvas> elements on

one HTML page• By default, the <canvas> element has no

border and no content.

Canvas Element

Page 10: HTML5 Canvas API

Adding a Border

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">

</canvas>

Page 11: HTML5 Canvas API

Inline Canvas Scripting<body><canvas id="myCanvas" width="200" height="100” > Your browser does not support the HTML5 canvas tag.</canvas>

<script>var c = document.getElementById("myCanvas");var ctx = c.getContext("2d");ctx.fillStyle = "#FF0000";ctx.fillRect(0,0,150,75);</script></body>

Returns the CanvasRenderingContext2D object

Page 12: HTML5 Canvas API

Or use the onload event<head> <script>function onload(){

var c=document.getElementById("myCanvas");var ctx=c.getContext("2d");ctx.fillStyle="#FF0000";ctx.fillRect(0,0,150,75);

}</script></head><body onLoad="onload()"><canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">Your browser does not support the HTML5 canvas tag.</canvas></body>

Page 13: HTML5 Canvas API

Or link to external JS file<head> <script type="text/javascript" src="canvasapp.js"></script></head>

<body onLoad="onload()">

<canvas id="myCanvas" width="200" height="100" style="border:1px solid #c3c3c3;">Your browser does not support the HTML5 canvas tag.</canvas>

</body>

NOTE: In HTML5, you no longer have to specify the script type attribute.

Do we need this?

Page 14: HTML5 Canvas API

No!!

window.onload = function(){canvasApp();

}

function canvasApp(){var c=document.getElementById("myCanvas");var ctx=c.getContext("2d");ctx.fillStyle="#FF0000";ctx.fillRect(0,0,150,75);

}

Page 15: HTML5 Canvas API

AddEventListener

window.addEventListener("load", canvasApp, false);

function canvasApp(){var c=document.getElementById("myCanvas");var ctx=c.getContext("2d");ctx.fillStyle="#FF0000";ctx.fillRect(0,0,150,75);

}

Page 16: HTML5 Canvas API

Jquery onload event

$(function() {

// insert code

});

Page 17: HTML5 Canvas API

Canvas Coordinate system

Page 18: HTML5 Canvas API

What makes canvas different from other graphics technologies such as Adobe Flash?

Page 19: HTML5 Canvas API

Immediate mode

“Canvas is an immediate mode bitmapped area of the screen... Immediate mode refers to the way the canvas renders pixels… Canvas completely redraws the bitmapped screen on every frame...”

“which means everything needs to be redrawn every time something changes.”

Page 20: HTML5 Canvas API

Retained mode

“This makes Canvas very different from Flash, Silverlight, or SVG, which operatein retained mode. In this mode, a display list of objects is kept by the graphics renderer…”

Oreilly, HTML5 Canvas

Page 21: HTML5 Canvas API

Immediate mode:low level operationsmore control

Responsive mode:high level operationsless control

Pros and cons

Page 22: HTML5 Canvas API

- W3C Schools

Page 23: HTML5 Canvas API

Text on the Canvasvar c = document.getElementById("myCanvas");

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

ctx.font = "30px Arial";

ctx.fillText("Hello World", 10, 50);

Page 24: HTML5 Canvas API

Text on the Canvas

var c=document.getElementById("myCanvas");

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

ctx.font="30px Arial";

ctx.strokeText("Hello World",10,50);

Page 25: HTML5 Canvas API

Drawing functionsvar c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.beginPath(); ctx.moveTo(20,20); ctx.lineTo(20,100); ctx.lineTo(70,100); ctx.closePath(); ctx.stroke();

Note: no primitives other than fillRect()

Page 26: HTML5 Canvas API

Drawing a circlevar c=document.getElementById("myCanvas");

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

ctx.beginPath(); ctx.arc(95, 50, 40, 0, 2*Math.PI); ctx.stroke();

Why 2*PI?

Page 27: HTML5 Canvas API

The arc function

arc(x, y, r, start, stop, antic);

Page 28: HTML5 Canvas API

Combination

ctx.moveTo(0,0);ctx.lineTo(100, 200);ctx.arcTo(350,350,100,100,20);

Page 29: HTML5 Canvas API

Bezier Curves

ctx.moveTo(0,0);ctx.quadraticCurveTo(100, 25, 0, 50);

// context.quadraticCurveTo(cpx, cpy, x, y)

Page 30: HTML5 Canvas API

clearRect command

var c=document.getElementById("myCanvas");var ctx=c.getContext("2d");ctx.fillStyle="red";ctx.fillRect(0,0,300,150);ctx.clearRect(20, 20, 100, 50);

Page 31: HTML5 Canvas API

Dynamically load imagesvar c=document.getElementById("myCanvas");var ctx=c.getContext("2d");

var helloWorldImage = new Image();helloWorldImage.src = "helloworld.gif”;

helloWorldImage.onload = function () {

ctx.drawImage(helloWorldImage, 160, 130);}

What is this?

Page 32: HTML5 Canvas API

Dynamically load images

1. ctx.drawImage(img, dx, dy);

2. ctx.drawImage(img, dx, dy, dw, dh);

3. ctx.drawImage(img, sx, sy, sw, sh, dx, dy, dw, dh);

What is this?

Page 33: HTML5 Canvas API
Page 34: HTML5 Canvas API

Using HTML img tags

<img id="scream" src=”my_scream_image.jpg” />

<canvas> </canvas>

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

var img=document.getElementById("scream");ctx.drawImage(img,10,10);

Page 35: HTML5 Canvas API

Capturing pixel datavar c=document.getElementById("myCanvas");var ctx=c.getContext("2d");

var formElement = document.getElementById("createImageData");formElement.addEventListener('click', createImageDataPressed, false);

function createImageDataPressed(e) {window.open( c.toDataURL() );

}

<input type="button" id="createImageData" value="Export Image" />

Page 36: HTML5 Canvas API

Window parameters

function createImageDataPressed(e) {

window.open(c.toDataURL(),"canvasImage","left=0,top=0,width=" + c.width + ",height=" + c.height +",toolbar=0,resizable=0");

}

Page 37: HTML5 Canvas API

The Canvas State

• Each canvas context can save and restore multiple states• A state can be pushed onto a stack using the save() command• A state can be restored using the restore() command• A state has several properties:– Values of lineWIdth, fillStyle, strokeStyle… etc– The transformation matrix– Current clipping region

Page 38: HTML5 Canvas API

The Canvas State…ctx.strokeStyle = "red";ctx.fillStyle = "yellow";ctx.lineWidth = 10;ctx.fillRect(25,25,100,125);ctx.strokeRect(25,25,100,125);ctx.save();

ctx.strokeStyle = "green";ctx.fillStyle = "blue";ctx.lineWidth = 5;ctx.fillRect(175, 25, 100, 125);ctx.strokeRect(175, 25, 100, 125);

ctx.restore(); ctx.fillRect(325, 25, 100, 125);ctx.strokeRect(325,25,100,125);

1. How many rectangles will there be?

2. What fill colour will the third rectangles have?

Page 39: HTML5 Canvas API

• Why is a stack of states useful?

Page 40: HTML5 Canvas API

Shadows

var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); ctx.shadowBlur=10; ctx.shadowOffsetX=20; ctx.shadowColor="black"; ctx.fillStyle="red"; ctx.fillRect(20,20,100,80);

Page 41: HTML5 Canvas API

Patterns

var c=document.getElementById("myCanvas"); var ctx=c.getContext("2d"); var img=document.getElementById("lamp"); var pat=ctx.createPattern(img,"repeat"); ctx.rect(0,0,150,100); ctx.fillStyle=pat; ctx.fill();

Page 42: HTML5 Canvas API

Patterns

var pat = ctx.createPattern(img,"repeat");

Page 43: HTML5 Canvas API

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

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

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

Page 44: HTML5 Canvas API

Clipping paths

ctx.rect(0, 0, 50, 50);ctx.clip();

// What happens here?

// only pixel data will be rendered within the area set by the rect function

Page 45: HTML5 Canvas API

Canvas Transformations

• Three basic transformation features– Translate– Scale– Rotate

– NOTE WORTHY: • Transforms affect any subsequent drawing commands.• Transforms are additive (What does this mean?)

Page 46: HTML5 Canvas API

Translate

translate(x, y);

This function moves the 0,0 origin of the canvas.

Page 47: HTML5 Canvas API

Translate

ctx.fillStyle = "blue"; ctx.fillRect(0,0,100,50);

// translate origin to center of the canvasctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);

ctx.fillRect(0,0,100,50);

Page 48: HTML5 Canvas API

Translate

Page 49: HTML5 Canvas API

Scale

scale(x, y);

Scale subsequent drawing commands by factors of x and y.

Page 50: HTML5 Canvas API

Scale

ctx.fillRect(0, 0, 100, 50);

ctx.scale(1.5, 2);

ctx.fillRect(125, 50, 100, 50);

// What will the height of the 2nd rectangle actually be?

Page 51: HTML5 Canvas API

Scale

Page 52: HTML5 Canvas API

Scalectx.fillStyle = "blue"; ctx.fillRect(0,0,100,50); ctx.save(); ctx.scale(1.5,2); ctx.fillRect(125,50,100,50); ctx.restore(); ctx.scale(0.5,0.5); ctx.fillRect(525,50,100,50);

Page 53: HTML5 Canvas API
Page 54: HTML5 Canvas API

Rotate

rotate(angle)

This command causes subsequent operations to be rotated by a given angle (in radians).

NOTE:Rotation occurs around the current origin so a specific object will not automatically rotate using its center as the pivot/origin. To do this simply use the translate to move the origin to an objects center.

Page 55: HTML5 Canvas API

Radians

• Circle = 2π radians• That’s roughly 6 radians• 1 radian = approx. 57º

Page 56: HTML5 Canvas API

Rotate

ctx.translate(ctx.canvas.width/2, ctx.canvas.height/2);

var radian= 20 * (Math.PI / 180);

ctx.rotate(radian); ctx.beginPath(); ctx.moveTo(-100,0); ctx.lineTo(100,0); ctx.stroke();

Page 57: HTML5 Canvas API

Custom transforms

• Custom transforms allow the programmer to set transforms not available through built in commands such as scale, translate …

Page 58: HTML5 Canvas API

Custom transforms

2x3 matrix transform

2m x 3n

ctx.setTransform(a, b, c, d, e, f);

Page 59: HTML5 Canvas API

ctx.setTransform(a, b, c, d, tx, ty)

Page 61: HTML5 Canvas API

1 0 tx 0 1 ty

var tx = ctx.canvas.width / 2; var ty = ctx.canvas.height / 2;

ctx.setTransform(1, 0, 0, 1, tx, ty);

ctx.fillRect(0, 0, 100, 50);

Custom transforms

Translate through transform

Page 62: HTML5 Canvas API

1 sx 0 sy 1 0

var sx = 0; var sy = 0.3;

ctx.setTransform(1, sy, sx, 1, 0, 0);

ctx.fillRect(250, 20, 100, 50);

Custom transforms

Skew

Page 63: HTML5 Canvas API

Global alpha

• Sets transparency of all canvas elements, hence the global

• ctx.globalAlpha can be given a value between 0 and 1

• Default value is 1

Page 64: HTML5 Canvas API

Global alphavar c=document.getElementById("myCanvas");var ctx=c.getContext("2d");

var helloWorldImage = new Image();helloWorldImage.src = "helloworld.gif";

helloWorldImage.onload = function () {ctx.drawImage(helloWorldImage, 160, 130);

}

ctx.globalAlpha = 0.1;

Page 65: HTML5 Canvas API

Global Compositing

• Defines how new drawing operations should interact with existing drawings/pixels…

Page 66: HTML5 Canvas API

Global Compositingctx.globalCompositeOperation = “source over”;

POSSIBLE VALUES"source-over”"source-in”"source-out”"source-atop”"lighter”"xor”"destination-over”"destination-in”"destination-out”"destination-atop” "darker”"copy"

Page 67: HTML5 Canvas API

Global Compositing

Page 68: HTML5 Canvas API

Manipulating Raw Pixels

• Canvas provides access to pixels through individual bytes

• Pixels can then be processed/manipulated and drawn back onto the canvas

• Canvas facilitates image processing in the browser

Page 69: HTML5 Canvas API

Manipulating Raw Pixels

//returns an objectvar imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);

//array of bytes var pixels = imgData.data;

Page 70: HTML5 Canvas API

Manipulating Raw Pixels

[byte1, byte2, byte3, byte4, byte5…]

Matrix of pixels to a 1*n (or 1 dimensional) array

Pixel 1

Red, Green, Blue, Alpha, Red …

Page 71: HTML5 Canvas API

Manipulating Raw Pixelsvar imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height); var pixels = imgData.data;

while (curRow < maxRow) {

var thisRowBytes = curRow * ctx.canvas.width * 4;for (var j = 0; j < ctx.canvas.width * 4; j += 4) {

pixels[thisRowBytes + j] = 255 - pixels[thisRowBytes + j]; // red pixels[thisRowBytes + j + 1] = 255 - pixels[thisRowBytes + j + 1]; // greenpixels[thisRowBytes + j + 2] = 255 - pixels[thisRowBytes + j + 2]; // blue }

curRow++; } ctx.putImageData(imgData, 0, 0);

Page 72: HTML5 Canvas API

Manipulating Raw Pixels

Page 73: HTML5 Canvas API

Manipulating Raw Pixelsvar imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height); var pixels = imgData.data;

while (curRow < maxRow) {

var thisRowBytes = curRow * ctx.canvas.width * 4;for (var j = 0; j < ctx.canvas.width * 4; j += 4) {

pixels[thisRowBytes + j] = 255 - pixels[thisRowBytes + j]; // red pixels[thisRowBytes + j + 1] = 255 - pixels[thisRowBytes + j + 1]; // greenpixels[thisRowBytes + j + 2] = 255 - pixels[thisRowBytes + j + 2]; // blue }

curRow++; } ctx.putImageData(imgData, 0, 0, 50, 50, 500, 200);

Page 74: HTML5 Canvas API

Manipulating Raw Pixels

Page 75: HTML5 Canvas API

Manipulating Raw Pixels

for (var j = 0; j < ctx.canvas.width * 4; j += 4) {

pixels[thisRowBytes + j] = pixels[thisRowBytes + j] - 50; // red pixels[thisRowBytes + j + 1] = pixels[thisRowBytes +

j + 1] - 50; // green pixels[thisRowBytes + j + 2] = pixels[thisRowBytes + j + 2] - 50; // blue

}

// What will happen here?

Page 76: HTML5 Canvas API

Manipulating Raw Pixels

Page 77: HTML5 Canvas API

Manipulating Raw Pixels

for (var j = 0; j < ctx.canvas.width * 4; j += 4) {

pixels[thisRowBytes + j] = pixels[thisRowBytes + j] + 50; // red pixels[thisRowBytes + j + 1] = pixels[thisRowBytes +

j + 1] + 50; // green pixels[thisRowBytes + j + 2] = pixels[thisRowBytes + j + 2] + 50; // blue

}

// What will happen here?

Page 78: HTML5 Canvas API

Manipulating Raw Pixels

Page 79: HTML5 Canvas API

Manipulating Raw Pixels

for (var j = 0; j < ctx.canvas.width * 4; j += 4) {

pixels[thisRowBytes + j] = pixels[thisRowBytes + j] / 3; // red pixels[thisRowBytes + j + 1] = pixels[thisRowBytes +

j + 1] / 3; // green pixels[thisRowBytes + j + 2] = pixels[thisRowBytes + j + 2] * 3; // blue }

// What will happen here?

Page 80: HTML5 Canvas API

Manipulating Raw Pixels

Page 81: HTML5 Canvas API

Manipulating Raw Pixels

for (var j = 0; j < ctx.canvas.width * 4; j += 4) {

pixels[thisRowBytes + j + 3] = 255 * 0.5;

}

// What will happen here?

Page 82: HTML5 Canvas API

Manipulating Raw Pixels

Page 83: HTML5 Canvas API

Manipulating Raw Pixels

for (var j = 0; j < ctx.canvas.width * 4; j += 4) { var aColour = pixels[thisRowBytes + j];

pixels[thisRowBytes + j] = aColour; pixels[thisRowBytes + j + 1] = aColour; pixels[thisRowBytes + j + 2] = aColour; }

// What happens here?

Page 84: HTML5 Canvas API

Manipulating Raw Pixels

Page 85: HTML5 Canvas API

• Video Canvas Code Demo in Chrome.

ctx.putImageData(imgData, 0, 0);

Page 86: HTML5 Canvas API

So, when using canvas, should we load in PNGs or JPEGs?

Page 88: HTML5 Canvas API

HTML5 Canvas and Accessibility

<canvas id="canvasOne" width="500" height="300">

<div>A yellow background with an image and text on top:<ol><li>The text says "Hello World"</li><li>The image is of the planet earth.</li></ol></div>

</canvas>

Page 89: HTML5 Canvas API

Debugging with Canvas

• Using Console.log();

Console.log(“Hello World”);

Page 90: HTML5 Canvas API
Page 91: HTML5 Canvas API
Page 92: HTML5 Canvas API

Some browsers throw errors when using

console.log();

Page 93: HTML5 Canvas API

var Debugger = function () { };Debugger.log = function (message) {

try {console.log(message);

} catch (exception) {return;

}}

Debugger.log("Drawing Canvas");

Page 94: HTML5 Canvas API

Resources

• http://www.w3schools.com/tags/ref_canvas.asp

Page 95: HTML5 Canvas API

What could canvas be used for?

Page 96: HTML5 Canvas API

Canvas APIs

• Canvas Query (helpful for games dev)

http://canvasquery.com/#canvas-query

• CreateJShttp://www.createjs.com/

Page 99: HTML5 Canvas API

Assignment ideas• Canvas based game• Children's drawing book• An online graphing tool • Photo effects app… instagram• Custom Design applications– T-Shirt design application– Badge designs– E-card designer…

Page 100: HTML5 Canvas API

Announcements

• Next weeks lecture will be a video on Blackboard– Canvas and HTML5 animation

• Very important for the class test in week 6

Page 101: HTML5 Canvas API