HTML5 Canvas API

Post on 23-Feb-2016

81 Views

Category:

Documents

0 Downloads

Preview:

Click to see full reader

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

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 <canvas> element is used to draw graphics, on the fly, via scripting (usually JavaScript).”

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

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

Oreilly, HTML5 Canvas

Support

Testing for Support

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

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

//browser does not support canvas}

Canvas Element

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

</canvas>

NOTE: Need id for script access.

• 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

Adding a Border

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

</canvas>

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

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>

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?

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);

}

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);

}

Jquery onload event

$(function() {

// insert code

});

Canvas Coordinate system

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

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.”

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

Immediate mode:low level operationsmore control

Responsive mode:high level operationsless control

Pros and cons

- W3C Schools

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

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

ctx.font = "30px Arial";

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

Text on the Canvas

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

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

ctx.font="30px Arial";

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

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()

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?

The arc function

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

Combination

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

Bezier Curves

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

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

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);

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?

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?

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);

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" />

Window parameters

function createImageDataPressed(e) {

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

}

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

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?

• Why is a stack of states useful?

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);

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();

Patterns

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

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);

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

Canvas Transformations

• Three basic transformation features– Translate– Scale– Rotate

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

Translate

translate(x, y);

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

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);

Translate

Scale

scale(x, y);

Scale subsequent drawing commands by factors of x and y.

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?

Scale

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);

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.

Radians

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

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();

Custom transforms

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

Custom transforms

2x3 matrix transform

2m x 3n

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

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

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

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

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

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;

Global Compositing

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

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"

Global Compositing

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

Manipulating Raw Pixels

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

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

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 …

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);

Manipulating Raw Pixels

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);

Manipulating Raw Pixels

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?

Manipulating Raw Pixels

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?

Manipulating Raw Pixels

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?

Manipulating Raw Pixels

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?

Manipulating Raw Pixels

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?

Manipulating Raw Pixels

• Video Canvas Code Demo in Chrome.

ctx.putImageData(imgData, 0, 0);

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

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>

Debugging with Canvas

• Using Console.log();

Console.log(“Hello World”);

Some browsers throw errors when using

console.log();

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

try {console.log(message);

} catch (exception) {return;

}}

Debugger.log("Drawing Canvas");

Resources

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

What could canvas be used for?

Canvas APIs

• Canvas Query (helpful for games dev)

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

• CreateJShttp://www.createjs.com/

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…

Announcements

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

• Very important for the class test in week 6

top related