HTML 5_Canvas

Post on 13-Apr-2017

165 views 4 download

Transcript of HTML 5_Canvas

HTML 5Canvas

<canvas id="tutorial" width="150" height="150"></canvas>

This looks a lot like the <img> element, the only difference is that it doesn't have the src and alt attributes. The <canvas> element has only two attributes - width andheight. These are both optional and can also be set using DOM properties. When no width and height attributes are specified, the canvas will initially be 300 pixelswide and 150 pixels high. 

Fallback content<canvas id="stockGraph" width="150" height="150">    current stock price: $3.15 +0.15  </canvas>    <canvas id="clock" width="150" height="150">    <img src="images/clock.png" width="150" height="150" alt=""/>  </canvas>  

The rendering context

2D rendering context.  3D context  ("experimental-webgl") based on 

OpenGL ES.

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

Checking for support

var canvas = document.getElementById('tutorial');  if (canvas.getContext){    var ctx = canvas.getContext('2d');    // drawing code here  } else {    // canvas-unsupported code here  }  

A skeleton template<html>    <head>      <title>Canvas tutorial</title>      <script type="text/javascript">        function draw(){          var canvas = document.getElementById('tutorial');          if (canvas.getContext){            var ctx = canvas.getContext('2d');          }        }      </script>      <style type="text/css">        canvas { border: 1px solid black; }      </style>    </head>    <body onload="draw();">      <canvas id="tutorial" width="150" height="150"></canvas>    </body>  </html>

Drawing shapes The grid Top left is 0,0 canvas only supports one primitive shape - rectangles. All other shapes must be

created by combining one or more paths fillRect(x,y,width,height) : Draws a filled rectangle

strokeRect(x,y,width,height) : Draws a rectangular outlineclearRect(x,y,width,height) : Clears the specified area and makes it fully transparent

Drawing paths beginPath()closePath()stroke()fill()moveTo(x, y)lineTo(x, y)arc(x, y, radius, startAngle, endAngle, anticlockwise)

Bezier and quadratic curvesquadraticCurveTo(cp1x, cp1y, x, y)bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)

Rectanglesrect(x, y, width, height)

Using images Importing images

Importing images is basically a two step process: Firstly we need a reference to a JavaScript Image object or

other canvas element as a source. It isn't possible to use images by simply providing a URL/path to them.

Secondly we draw the image on the canvas using the drawImage function.

drawImage drawImage(image, x, y, width, height) var img = new Image();   // Create new img element   img.src = 'myImage.png'; // Set source path  

Slicing drawImage(image, sx, sy, sWidth, sHeight, dx, dy,

dWidth, dHeight)

function draw() {      var ctx = document.getElementById('canvas').getContext('2d');      var img = new Image();      img.onload = function(){        ctx.drawImage(img,0,0);        ctx.beginPath();        ctx.moveTo(30,96);        ctx.lineTo(70,66);        ctx.lineTo(103,76);        ctx.lineTo(170,15);        ctx.stroke();      };      img.src = 'images/img.png';    } 

Applying styles and colors fillStyle = color

strokeStyle = color ctx.fillStyle = "orange";   ctx.fillStyle = "#FFA500";   ctx.fillStyle = "rgb(255,165,0)";  

Transparency globalAlpha = transparency value

ctx.fillStyle = "rgba(255,165,0,1)"; ctx.globalAlpha = 0.2;  

Line styles lineWidth = value

lineCap = type ('butt','round','square')lineJoin = type ['round','bevel','miter']miterLimit = value

Gradients createLinearGradient(x1,y1,x2,y2)

createRadialGradient(x1,y1,r1,x2,y2,r2) var lineargradient = ctx.createLinearGradient(0,0,150,15

0);   var radialgradient = ctx.createRadialGradient(75,75,0,75,

75,100); addColorStop(position, color)

Patterns createPattern(image,type) Type [repeat, repeat-x, repeat-y and no-repeat.]

var img = new Image();   img.src = 'someimage.png';   var ptrn = ctx.createPattern(img,'repeat');

Shadows shadowOffsetX = float

shadowOffsetY = floatshadowBlur = floatshadowColor = color

Transformations save()

restore() Translating

translate(x, y) Rotating

rotate(angle) Scaling

scale(x, y) Transforms

transform(m11, m12, m21, m22, dx, dy)

Compositing globalCompositeOperation

source-over (default) source-in source-out source-atop Lighter Xor destination-over destination-in destination-out destination-atop darker  Copy

Clipping paths Clip()

Basic animationsBasic animation steps

These are the steps you need to take to draw a frame: Clear the canvas

Unless the shapes you'll be drawing fill the complete canvas (for instance a backdrop image), you need to clear any shapes that have been drawn previously. The easiest way to do this is using the clearRect method.

Save the canvas stateIf you're changing any setting (styles, transformations, etc) which affect the canvas state and want to make sure the original state is used each time a frame is drawn, you need to save it.

Draw animated shapesThe step where you do the actual frame rendering.

Restore the canvas stateIf you've saved the state, restore it before drawing a new frame.

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

The new method requestAnimationFrame() allows modern browsers to stop

drawing graphics when a tab or window is not visible. Improving overall performance and batteries on mobile devices.