Quickie Canvas

Background

Use w for canvas width, h for canvas height.

I developed the Quickie Canvas tool to easily generate images with the canvas element. You can read more about the benefits of this tool and some examples at Prototyping with the canvas element.

You can Right Click to save the canvas as a PNG, just like you would for any other image (Firefox only).

To get the data URI of the canvas, right click the canvas and select View Image. The Data URI will be in the URL address for that image.

Mozilla Developer Center - Canvas Tutorial

Properties and Methods

Drawing Shapes

//Rectangles
ctx.fillRect(x,y,width,height); 
ctx.strokeRect(x,y,width,height); 
ctx.clearRect(x,y,width,height); 

//Drawing paths 
ctx.beginPath();
ctx.closePath();
ctx.stroke();
ctx.fill();
ctx.moveTo(x, y);
ctx.lineTo(x, y);
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
ctx.quadraticCurveTo(cp1x, cp1y, x, y); 
ctx.bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y);
ctx.rect(x, y, width, height);

Styles and Colors

//Colors
ctx.fillStyle = color ;
ctx.strokeStyle = color ;

//Transparency
ctx.globalAlpha = transparency value ;

//Line styles
ctx.lineWidth = value ;
ctx.lineCap = type ;
ctx.lineJoin = type ;
ctx.miterLimit = value ;

//Gradients
var varname = ctx.createLinearGradient(x1,y1,x2,y2);
var varname = ctx.createRadialGradient(x1,y1,r1,x2,y2,r2);
varname.addColorStop(position, color);

//Shadows (Firefox 3.1, Webkit browsers)
ctx.shadowOffsetX = float ;
ctx.shadowOffsetY = float ;
ctx.shadowBlur = float ;
ctx.shadowColor = color ;

Transformations

//Save and Restore state
ctx.save();
ctx.restore();

//Translating 
ctx.translate(x, y);

//Rotating 
ctx.rotate(angle);

//Scaling 
ctx.scale(x, y);

The above examples were originally published in the Mozilla Developer's Center Canvas Tutorial under a Creative Commons Attribution-Share Alike license.

Examples

Gradient

var grad = ctx.createLinearGradient(0,0,0,h);
grad.addColorStop(0, '#000');
grad.addColorStop(.3, '#00F');
grad.addColorStop(1, '#FFF');
ctx.fillStyle = grad;
ctx.fillRect( 0, 0, w, h);

Rounded Rectangle

var r = 10; // corner radius of 10
ctx.fillStyle = "#468";
ctx.beginPath();
ctx.arc( r,     r, r, Math.PI, Math.PI*(3/2),false); 
ctx.arc( w-r,   r, r, Math.PI*(3/2), 0,false); 
ctx.arc( w-r, h-r, r, 0, Math.PI*(1/2),false); 
ctx.arc( r,   h-r, r, Math.PI*(1/2), Math.PI,false); 
ctx.fill();
ctx.closePath();

Function

function colorSquare( x, y, size, color) {
  ctx.fillStyle = color;
  ctx.fillRect(x,y,size,size);
}

colorSquare( 5, 5, 20, '#F00');
colorSquare( 10, 10, 40, 'rgba( 0, 128, 0, .5)' );
colorSquare( 40, 40, 30, '#0FF' );
colorSquare( 80, 20, 10, '#FC3' );