2D graphics

The CanvasRenderingContext2D interface provides the 2D rendering context for the drawing surface of a <canvas> element. It is used for drawing shapes, text, images, and other objects.


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

// draw something
ctx.lineWidth = 1;
ctx.strokeStyle = 'black';  
    
ctx.beginPath();
ctx.ellipse(100, 50, 80, 20, 0, 0, 2*Math.PI);
ctx.stroke();

See also some examples of how to draw on canvas.

axis

X-axis of canvas is from left to right.

Y-axis of canvas is from top to bottom.

state of canvas

State of canvas includes:

  • current transformation matrix
  • current clipping region
  • current dash pattern
  • properties of canvas such lineWidth, shadowOffsetX, globalCompositeOperation, font and etc
method description
save() Saves the entire state of the canvas by pushing the current state onto a stack.
restore() Restores the most recently saved canvas state by popping the top entry in the drawing state stack. If there is no saved state, this method does nothing.

fill and stroke

property description
strokeStyle Specifies the color, gradient, or pattern to use for the strokes around shapes. The default is "#000" (black).
fillStyle Specifies the color, gradient, or pattern to use inside shapes. The default style is "#000" (black).
lineCap Specifies the shape used to draw the end points of lines. Possible values:
  • "butt" - the ends of lines are squared off at the endpoints. This is default value.
  • "round" - the ends of lines are rounded.
  • "square" - the ends of lines are squared off by adding a box with an equal width and half the height of the line's thickness.
lineWidth Sets the thickness of lines. Zero, negative, Infinity, and NaN values are ignored. Default value is 1.0.
lineDashOffset Sets the line dash offset. Default value is 0.0.
miterLimit Sets the miter limit ratio. Default value is 10.0.
lineJoin determines the shape used to join two line segments where they meet. Possible values:
  • "miter" - connected segments are joined by extending their outside edges to connect at a single point, with the effect of filling an additional lozenge-shaped area. This setting is affected by the miterLimit property. This is default value.
  • "round" - rounds off the corners of a shape by filling an additional sector of disc centered at the common endpoint of connected segments.
  • "bevel" - fills an additional triangular area between the common endpoint of connected segments, and the separate outside rectangular corners of each segment.
method description
setLineDash(segments)

Sets the line dash pattern used when stroking lines. Parameter segments is array of numbers where odd elements specify the stroke length and even elements define the gap between strokes.

If the number of elements in the array is odd, the elements of the array get copied and concatenated.

To return to using solid lines, pass an empty array.

getLineDash() Gets the current line dash pattern.
fill( [fillRule] ) fill(path [, fillRule]) Fills the current or given path. Parameter fillRule specifies the algorithm by which to determine if a point is inside or outside the filling region:
  • "nonzero" - this is default value.
  • "evenodd"
stroke()stroke(path) Strokes the current or given path.

path creation

Following methods don't directly render anything, only modify current path. Use the stroke() or fill() methods for rendering.

method description
beginPath() Starts a new path. To create a new sub-path you can use the moveTo() method.
closePath() Attempts to add a straight line from the current point to the start of the current sub-path. If the shape has already been closed or has only one point, this function does nothing.
moveTo(x, y) Begins a new sub-path at the point specified by the given (x, y) coordinates.
lineTo(x, y) Adds a straight line to the current sub-path by connecting the sub-path's last point to the specified (x, y) coordinates.
arcTo(x, y) Adds a circular arc to the current sub-path, using the given control points and radius. See example of rounded rectangle.
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y) Adds a cubic Bézier curve to the current sub-path. It requires three points: the first two are control points and the third one is the end point. The starting point is the latest point in the current path, which can be changed using moveTo() before creating the Bézier curve.
quadraticCurveTo(cpx, cpy, x, y) Adds a quadratic Bézier curve to the current sub-path. It requires two points: the first one is a control point and the second one is the end point. The starting point is the latest point in the current path, which can be changed using moveTo() before creating the quadratic Bézier curve.
shapes
ellipse(x, y, rX, rY, rot, startAngle, endAngle [, anticlockwise]) Creates an elliptical arc centered at (x, y) with the radius rX and rY. The path starts at startAngle and ends at endAngle, and travels in the direction given by anticlockwise (default clockwise).
arc(x, y, r, startAngle, endAngle [, anticlockwise]) Creates a circular arc centered at (x, y) with a radius of r. The path starts at startAngle, ends at endAngle, and travels in the direction given by anticlockwise (default clockwise).
rect(x, y, w, h) Creates a rectangular path whose starting point is at (x, y) and whose size is specified by w and h.

There is also the Path2D class, which gives you the convenience of being able to retain and replay your path whenever desired. It implements

  1. xxxTo() methods
  2. closePath() method
  3. addPath() method for adding another path
  4. shapes

For rendering Path2D objects use the fill(path) or stroke(path) methods of the canvas context.

text

property description
font Specifies the current text style to use when drawing text. This string uses the same syntax as the font CSS specifier.
textAlign Specifies the current text alignment used when drawing text. Possible values:
  • "left"
  • "right"
  • "center"
  • "start"
  • "end"
textBaseline Specifies the current text baseline used when drawing text. Possible values:
  • "top"
  • "hanging"
  • "middle"
  • "alphabetic"
  • "ideographic"
  • "bottom"
method description
strokeText(txt, x, y [, maxWidth]) Draws text with outline characters.
fillText(txt, x, y [, maxWidth]) Draws text with filled characters.

transformation matrix

Read more about the transformation matrix if necessary.

There is the DOMMatrix class that represent the transformation matrix. It can be initialized with CSS transform string, or a string or an array of numbers a, b, c, d, e, f to get a matrix:

|a c e|
|b d f|
|0 0 1|

See example how to rotate canvas on 90°.

method description
getTransform() Retrieves the current transformation matrix.
setTransform(a, b, c, d, e, f) Overrides the current transformation with the specified transformation matrix.
setTransform(m) Overrides the current transformation with the specified DOMMatrix object.
transform(a, b, c, d, e, f) Multiplies the current transformation with given matrix.
translate(x, y) Adds a translation transformation to the current matrix.
rotate(angle) Adds a rotation to the transformation matrix. The rotation angle is clockwise in radians.
scale(x, y) adds a scaling transformation to the to the transformation matrix.