Internet‎ > ‎HTML‎ > ‎HTML 5‎ > ‎

HTML5 Canvas

HTML5 includes Canvas element, which give u power to draw graphics on canvas by using JavaScript.

It is still in the draft stage but has been implemented at least partially in Firefox, Chrome, Safari and Opera. We hope Internet Explorer also implements it soon. Till Internet Explorer supports it natively one can use the library at excanvas.sourceforge.net which can help to a large extent in converting canvas calls to VML which IE supports natively.

The canvas tag contains the following features:

// Create the ctx canvas object .
var ctx = document.getElementById('canvas').getContext('2d') ; 
  • The canvas state
    • context.save()
Pushes the current state onto the stack.
  • context.restore()
Pops the top state on the stack, restoring the context to that state.
  • Transformations
    • context.scale(x, y)
Changes the transformation matrix to apply a scaling transformation with the given characteristics.

Example:
var img = new Image(); // Create new Image object
img.src = 'test.png'; // Set source path

ctx.scale(4,10) ;
ctx.drawImage(img,10,10) ;
  • context.rotate(angle)
Changes the transformation matrix to apply a rotation transformation with the given characteristics. The angle is in radians.

Example:
var img = new Image(); // Create new Image object
img.src = 'test.png'; // Set source path

ctx.rotate(0.5) ;
ctx.drawImage(img,10,10) ;
  • context.translate(x, y)
Changes the transformation matrix to apply a translation transformation with the given characteristics.

Example:
var img = new Image(); // Create new Image object
img.src = 'test.png'; // Set source path

ctx.translate(30,50) ;
ctx.drawImage(img,10,10) ;
  • context.transform(m11, m12, m21, m22, dx, dy)
Changes the transformation matrix to apply the matrix given by the arguments as described below.

Example:
var img = new Image(); // Create new Image object
img.src = 'test.png'; // Set source path

ctx.transform(1,3,5,4,10,10) ;
ctx.drawImage(img,10,10) ;
  • context.setTransform(m11, m12, m21, m22, dx, dy)
Changes the transformation matrix to the matrix given by the arguments as described below.

Example:
var img = new Image(); // Create new Image object
img.src = 'test.png'; // Set source path

ctx.setTransform(1,3,5,4,10,10) ;
ctx.drawImage(img,10,10) ;
  • Compositing
    • context.globalAlpha [ = value ]
Returns the current alpha value applied to rendering operations. Can be set, to change the alpha value. Values outside of the range 0.0 .. 1.0 are ignored.

Example:
ctx.globalAlpha = 200 ;
ctx.fillStyle = "blue" ;
ctx.fillRect(35,35,60,60) ;
  • context.globalCompositeOperation [ = value ]
Returns the current composition operation, from the list below. Can be set, to change the composition operation. Unknown values are ignored.
  • Colors and styles
    • context.strokeStyle [ = value ]
Returns the current style used for stroking shapes. Can be set, to change the stroke style. The style can be either a string containing a CSS color, or a CanvasGradient or CanvasPattern object. Invalid values are ignored.

Example:
ctx.strokeStyle = "blue" ;
ctx.clearRect(35,35,60,60) ;
  • context.fillStyle [ = value ]
Returns the current style used for filling shapes. Can be set, to change the fill style. The style can be either a string containing a :
  • CSS color, or
  • Canvas Gradient, or
  • Canvas Pattern object. 
Invalid values are ignored.

Example:
ctx.strokeStyle = "blue" ;
ctx.fillStyle = "blue" ;
ctx.clearRect(35,35,60,60) ;
  • gradient.addColorStop(offset, color)
Adds a color stop with the given color to the gradient at the given offset. 0.0 is the offset at one end of the gradient, 1.0 is the offset at the other end. Throws an INDEX_SIZE_ERR exception if the offset it out of range. Throws a SYNTAX_ERR exception if the color cannot be parsed.

Example:
grad.addColorStop(0, '#00ABEB');  // (gradient Starting possion, color)
grad.addColorStop(0.5, '#fff');   // (gradient end possion, color)
  • gradient = context.createLinearGradient(x0, y0, x1, y1)
Returns a CanvasGradient object that represents a linear gradient that paints along the line given by the coordinates represented by the arguments. If any of the arguments are not finite numbers, throws a NOT_SUPPORTED_ERR exception.

Example:
var grad = ctx.createLinearGradient(0, 0, 0, 150) ;
grad.addColorStop(0, '#00ABEB');  // (gradient Starting possion, color)
grad.addColorStop(0.5, '#fff');   // (gradient end possion, color)
ctx.strokeStyle = grad ;
ctx.clearRect(35,35,60,60) ;
  • gradient = context.createRadialGradient(x0, y0, r0, x1, y1, r1)
Returns a CanvasGradient object that represents a radial gradient that paints along the cone given by the circles represented by the arguments. If any of the arguments are not finite numbers, throws a NOT_SUPPORTED_ERR exception. If either of the radii are negative throws an INDEX_SIZE_ERR exception.

Example:
var grad = ctx.createRadialGradient(45,45,10,52,50,30) ;
grad.addColorStop(0, '#A7D30C');  // (gradient Starting possion, color)
grad.addColorStop(0.9, '#019F62');   // (gradient end possion, color)
grad.addColorStop(1, 'rgba(1,159,98,0)');
ctx.fillStyle = grad ;
ctx.fillRect(0,0,150,150) ;
  • pattern = context.createPattern(image, repetition)
Returns a CanvasPattern object that uses the given image and repeats in the direction(s) given by the repetition argument. The allowed values for repeat are :
  • repeat (both directions)
  • repeat-x (horizontal only)
  • repeat-y (vertical only)
  • no-repeat (neither)
If the repetition argument is left empty or is null, the value repeat is used.

Example:
var ptrn = ctx.createPattern(img,'repeat');
ctx.fillStyle = ptrn ;
ctx.fillRect(0,0,150,150) ;
  • Line Styles
    • context.lineWidth [ = value ]
Returns the current line width. Can be set, to change the line width. Values that are not finite values greater than zero are ignored.

Example:
ctx.lineWidth = 5 ;
ctx.beginPath() ;
ctx.moveTo(50,50) ;
ctx.lineTo(100,100) ;
ctx.closePath() ;
ctx.stroke() ;
  • context.lineCap [ = round, bevel, square ]
Returns the current line cap style. Can be set, to change the line cap style. The possible line cap styles are butt, round, and square. Other values are ignored.

Example:
ctx.lineWidth = 5 ;
ctx.lineCap = 'round' ;
ctx.beginPath() ;
ctx.moveTo(50,50) ;
ctx.lineTo(100,100) ;
ctx.stroke() ;
  • context.lineJoin = [round, butt, square]
Returns the current line join style. Can be set, to change the line join style. The possible line join styles are bevel, round, and miter. Other values are ignored.

Example:
ctx.lineWidth = 30 ;
ctx.lineJoin = 'round' ;
ctx.beginPath() ;
ctx.moveTo(50,50) ;
ctx.lineTo(100,100) ;
ctx.lineTo(150,100) ;ctx.stroke() ;
  • context.miterLimit [ = value ]
Returns the current miter limit ratio. Can be set, to change the miter limit ratio. Values that are not finite values greater than zero are ignored.
  • Shadows
    • context.shadowColor [ = value ]
Returns the current shadow color. Can be set, to change the shadow color. Values that cannot be parsed as CSS colors are ignored.

Example:
ctx.shadowColor = "black" ; // also support RGB(R,G,B)
  • context.shadowOffsetX [ = value ]
  • context.shadowOffsetY [ = value ]
Returns the current shadow offset. Can be set, to change the shadow offset. Values that are not finite numbers are ignored.

Example:
ctx.shadowColor = "black" ; // also support RGB(R,G,B)
ctx.shadowOffsetX = 2 ; // X Position width
ctx.shadowOffsetY = 2 ; // Y Position width
ctx.drawImage(img,10,10) ;
  • context.shadowBlur [ = value ]
Returns the current level of blur applied to shadows. Can be set, to change the blur level. Values that are not finite numbers greater than or equal to zero are ignored.

Example:
ctx.shadowBlur = 1 ; 
  • Simple Shapes (rectangles)
    • context.clearRect(x, y, w, h)
Clears all pixels on the canvas in the given rectangle to transparent black.

Example:
ctx.clearRect(35,35,60,60);
  • context.fillRect(x, y, w, h)
Paints the given rectangle onto the canvas, using the current fill style.

Example:
ctx.fillRect(10,10,100,100);
  • context.strokeRect(x, y, w, h)
Paints the box that outlines the given rectangle onto the canvas, using the current stroke style.

Example:
ctx.strokeRect(40,40,50,50);
  • Complex Shapes (path)
    • context.beginPath()
Resets the current path.

Example:
ctx.beginPath() ;
  • context.moveTo(x, y)
Creates a new subpath with the given point.

Example:
ctx.beginPath() ;
ctx.moveTo(75,50) ;
  • context.closePath()
Marks the current subpath as closed, and starts a new subpath with a point the same as the start and end of the newly closed subpath.

Example:
ctx.beginPath() ;
ctx.moveTo(75,50) ;
ctx.lineTo(100,75) ;
ctx.closePath() ;
ctx.fill() ;
  • context.lineTo(x, y)
Adds the given point to the current subpath, connected to the previous one by a straight line.

Example:
ctx.beginPath() ;
ctx.lineTo(100,25) ;
ctx.fill() ;
  • context.quadraticCurveTo(cpx, cpy, x, y)
Adds the given point to the current path, connected to the previous one by a quadratic Bézier curve with the given control point.

Example:
ctx.beginPath();
ctx.moveTo(275,25);
ctx.quadraticCurveTo(0,0,200,250);ctx.stroke();
  • context.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
Adds the given point to the current path, connected to the previous one by a cubic Bézier curve with the given control points.
  • context.arcTo(x1, y1, x2, y2, radius)
Adds a point to the current path, connected to the previous one by a straight line, then adds a second point to the current path, connected to the previous one by an arc whose properties are described by the arguments.
  • context.arc(x, y, radius, startAngle, endAngle, anticlockwise)
Adds points to the subpath such that the arc described by the circumference of the circle described by the arguments, starting at the given start angle and ending at the given end angle, going in the given direction, is added to the path, connected to the previous point by a straight line.

Example:
ctx.arc(10, 10, 10, 10, 100, 90) ; //x, y, radius, startAngle, endAngle, anticlockwise
ctx.stroke();
  • context.rect(x, y, w, h)
Adds a new closed subpath to the path, representing the given rectangle.

Example:
ctx.rect(10,10,100,100) ; // x, y, width, height
ctx.fill() ;
  • context.fill()
Fills the subpaths with the current fill style.

Example:
ctx.beginPath() ;
ctx.moveTo(75,50) ;
ctx.lineTo(100,75) ;
ctx.closePath() ;
ctx.fill() ;
  • context.stroke()
Strokes the subpaths with the current stroke style.

ctx.beginPath() ;
ctx.moveTo(75,50) ;
ctx.lineTo(100,75) ;
ctx.closePath() ;
ctx.stroke() ;
  • context.clip()
Further constrains the clipping region to the given path.
  • context.isPointInPath(x, y)
Returns true if the given point is in the current path.

  • Focus Managment
    • shouldDraw = context.drawFocusRing(element, x, y, [ canDrawCustom ])
If the given element is focused, draws a focus ring around the current path, following the platform conventions for focus rings. The given coordinate is used if the user's attention needs to be brought to a particular position (e.g. if a magnifier is following the editing caret in a text field).
  • Text
    • context.font [ = value ]
Returns the current font settings. Can be set, to change the font. The syntax is the same as for the CSS 'font' property; values that cannot be parsed as CSS font values are ignored.

Example:
ctx.font = "20pt Arial" ;
  • context.textAlign [ = left, right, center, start, end ]
Returns the current text alignment settings.
  • context.textBaseline [ = top, hanging, middle, alphabetic, ideographic, bottom ]
Returns the current baseline alignment settings.
  • context.fillText(text, x, y [, maxWidth ] )
  • context.strokeText(text, x, y [, maxWidth ] )
Fills or strokes (respectively) the given text at the given position. If a maximum width is provided, the text will be scaled to fit that width if necessary.

Example:
ctx.fillText("SKJ", 10, 10,100) ; // specify text, left, right and max area
  • metrics = context.measureText(text)
Returns a TextMetrics object with the metrics of the given text in the current font.
  • metrics.width
Returns the advance width of the text that was passed to the measureText() method.
  • Images
    • context.drawImage(image, dx, dy)
    • context.drawImage(image, dx, dy, dw, dh)
    • context.drawImage(image, sx, sy, sw, sh, dx, dy, dw, dh)
Each of those three can take either an HTMLImageElement, an HTMLCanvasElement, or an HTMLVideoElement for the image argument.

Example:
var ctx = document.getElementById('canvas').getContext('2d');
var img = new Image() ;   // Create new Image object
img.src = 'test.png' ; // assign source
ctx.drawImage(img,10,10) ; // image,x,y
  • Pixel Manipulation
    • imagedata = context.createImageData(sw, sh)
Returns an ImageData object with the given dimensions in CSS pixels (which might map to a different number of actual device pixels exposed by the object itself). All the pixels in the returned object are transparent black.
  • imagedata = context.createImageData(imagedata)
Returns an ImageData object with the same dimensions as the argument. All the pixels in the returned object are transparent black.
  • imagedata = context.getImageData(sx, sy, sw, sh)
Returns an ImageData object containing the image data for the given rectangle of the canvas.
  • imagedata.width
  • imagedata.height
Returns the actual dimensions of the data in the ImageData object, in device pixels.
  • imagedata.data
Returns the one-dimensional array containing the data.
  • context.putImageData(imagedata, dx, dy [, dirtyX, dirtyY, dirtyWidth, dirtyHeight ])
Paints the data from the given ImageData object onto the canvas. If a dirty rectangle is provided, only the pixels from that rectangle are painted.

EXAMPLES
  • Canvas Gradient Button in a rounded rectangle
var ctx = document.getElementById('canvas').getContext('2d') ;

function roundedRect(x,y,width,height,radius,mode,color)
{
ctx.beginPath();
ctx.moveTo(x,y+radius);
ctx.lineTo(x,y+height-radius);
ctx.quadraticCurveTo(x,y+height,x+radius,y+height);
ctx.lineTo(x+width-radius,y+height);
ctx.quadraticCurveTo(x+width,y+height,x+width,y+height-radius);
ctx.lineTo(x+width,y+radius);
ctx.quadraticCurveTo(x+width,y,x+width-radius,y);
ctx.lineTo(x+radius,y);
ctx.quadraticCurveTo(x,y,x,y+radius);

if(mode == 'fill')
{
//ctx.fillStyle = color ;
ctx.fill() ;
}
else
{
//ctx.strokeStyle = color ;
ctx.stroke() ;
}
}

var grad = ctx.createLinearGradient(0,25,0,0) ;
grad.addColorStop(1, '#74cd64');  // (gradient Starting possion, color)
grad.addColorStop(0, '#43bf2d');   // (gradient end possion, color)
ctx.fillStyle = grad ;

var outline1 = ctx.createLinearGradient(0,25,0,0) ;
outline1.addColorStop(1, '#40bb2c');  // (gradient Starting possion, color)
outline1.addColorStop(0, '#27771b');   // (gradient end possion, color)

ctx.strokeStyle = outline1 ;
roundedRect(0,0,75,25,5,'fill') ;
roundedRect(0,0,75,25,5) ;

Useful Links:
Comments