Top Banner
HTML-5 Canvas
18

Canvas

May 11, 2015

Download

Technology

Ganesh Gembali

This presentation shows different features HTML
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: Canvas

HTML-5 Canvas

Page 2: Canvas

Agenda Where it has started What change can it bring? Understanding the lingo Basic usage Drawing shapes Using images Applying styles and colors Transformations Compositing Basic animations

Page 3: Canvas

History

Page 4: Canvas

Canvas vs SVG

High performance Everything is a pixel. Save the resulting image

as a .png or .jpg. For generating raster

graphics where pixel-level manipulation is needed.

Resolution independence Elements can be animated

using a declarative syntax, or via JavaScript.

Full control over each element

Page 5: Canvas

Lingo

Page 6: Canvas

What it is not

Page 7: Canvas

First kicks

<canvas id="stockGraph" width="150" height="150">

You browser doesn't support canvas.</canvas>

var canvas = document.getElementById('tutorial');if (canvas.getContext){

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

Page 8: Canvas

Basic shapes

Rectangle :fillRect(x,y,width,height)

strokeRect(x,y,width,height) clearRect(x,y,width,height)

Circle:arc(x, y, radius, startAngle,

endAngle, anticlockwise)

Page 9: Canvas

Paths

beginPath()closePath()stroke()Fill()moveTo(x, y)lineTo(x, y)

Page 10: Canvas

Exercise - 1

Page 11: Canvas

Solution

ctx.beginPath();ctx.arc(75,75,50,0,Math.PI*2,true); //

Outer circlectx.moveTo(110,75);ctx.arc(75,75,35,0,Math.PI,false); //

Mouth(clockwise)ctx.moveTo(40,75);ctx.lineTo(110,75);

ctx.moveTo(65,65);ctx.arc(60,65,5,0,Math.PI*2,true); // Left

eyectx.moveTo(95,65);ctx.arc(90,65,5,0,Math.PI*2,true); // Right

eyectx.stroke();

Page 12: Canvas

Beziere curves

quadraticCurveTo(cp1x, cp1y, x, y) bezierCurveTo(cp1x, cp1y, cp2x,

cp2y, x, y)

Page 13: Canvas

Styling

lineWidth = valuelineCap = typelineJoin = typemiterLimit = value

fillStyle = colorstrokeStyle = color

ctx.globalAlpha = 0...1;

createLinearGradient(x1,y1,x2,y2)createRadialGradient(x1,y1,r1,x2,y2,r2)addColorStop(position, color)

var ptrn =ctx.createPattern(img,'repeat');ctx.fillStyle = ptrn;

Page 14: Canvas

Images

var img = new Image(); img.src = 'myImage.png'; // Set source path

OR

Img = 'data:image/gif;base64,R0lGO......'

drawImage(image, sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight)

Page 15: Canvas

Transformations

translate(x, y)

rotate(alpha)

Page 16: Canvas

Compositing

globalCompositeOperation = [type]

ctx.beginPath();drawAPath(); ctx.clip();

Page 17: Canvas

Animate

Clear the canvas Save the canvas state Draw animated shapes Restore the canvas state

setInterval(animateShape,500);setTimeout(animateShape,500);

Page 18: Canvas

Canvas vs Flash