Saturday, March 5, 2016

HTML5 - Canvas

One of goals of HTML5 was to make web independant of plugins 
like flash, silverlight and other plugins

One of the key features were media and graphics

To handle this HTML5 introduces "Canvas" API

It creates drawing surface, a blank area in browser
It marks X,Y coordinates

With this you can achieve precise control over any object

2d vs 3d (webgl)
webgl only supported in browsers that implement WebGL library

Rectangle

Shape fully supported by canvas

Rectangle Methods
Stroke - draws border
Fill - fills solid color
Clear - remove solid / puts white fill

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

Drawing
Usually we don't draw directly to canvas
A path is a pattern for the "pen" to follow
Once the path is set, it is sent to the canvas

Paths

  • moveTo(x,y) - moves pen to x,y without drawing
  • lineTo(x,y) - draws line to x,y by drawing and pen moves
  • closePath - draws line from wherever pen is to start of path
  • clip - create region outside which region is clipped away
  • rect(x,y,width,height)
  • arc(x,y,radius,startAngle,endAngle,direction) - creates circle or arc of circle
  • quadraticCurveTo(cpx,cpy,x,y)
  • bezierCurveTo(cp1x,cp1y,cp,2x,cp2y,x,y)
Arc
You can draw curves and circles using "Arc"

Method:
canvas.arc(param1,param2,param3,param4,param5,param6);

Parameters are as follows:
param1:offset
param2:offset
param3:radius
param4:starting angle
param5:no.of degrees in radients
param6:draw clockwise/counter-clockwise

i.e.
canvas.arc(offset,offset,radius,starting angle,degrees,direction);