1. Cameron Brown
  2. canvas

Overview

HTTPS SSH

Canvas is a utility extension for the HTML canvas, with plug and play interactive navigation, a controlled animation loop, layering, and a full suite of existig functions and missing ones (strokeArc, fillArc, circle,..)

Usage

Instializing this as an object with the new keyword is necesarry, but saving the object to a variable is not, since all functions will be applied to the DomElement directly.

var DomElement = document.getElementById('myCanvas'),
    ConfigObject = {};
new Canvas(DomElement, ConfigObject);

If no element is given a canvas will be created and appended to the body. If the element is not a canvas it will be taken as a container, and any canvases within it will be used as layers. All functions will be applied to the container element given, not the canvases within.

To set the draw loop function, simply define a .draw, .beforeDraw, or .afterDraw function.

var canvas = document.getElementById('myCanvas');
new Canvas(canvas);
canvas.draw = function () {
    canvas.beginPath();
    canvas.rect(0,0,50,40);
    canvas.fill('#0f0');
}

Because the .draw function is in the same scope as the context functions they can be called using this.

canvas.draw = function () {
    this.fillRect(0,0,50,40,'#0f0');
    this.fillCircle(100,120,30,'#00f');
}

Options

Name Default Values Description
zoom 1 Number between 0 and... infinity (zoom > 0) Zoom level, or scale factor of the canvas drawing.
center {x:0,y:0} x, y coordinate object The offset, or translation of the canvas drawing. This should only be gotten after initialization, and should be set using canvas.setCenter({x:0,y:0}) after that.
inverseY false Boolean: true/false Inverts the Y axis, as the pre-flipping of it can be an annoyance
inverseZ false Boolean: true/false Inverts the scrolling direction, for those who prefer OSx style scrolling. This does not effect touch-screen pinch zooming.
zoomMin 1/34000 Number between 0 and 1 The minimum magnification (zoom out) of the canvas.
zoomMax 34000 Number between 1 and infinity The maximum magnification (zoom in) of the canvas. At values greater than 34000 lines begin to disappear, text acts funny and the zoom algorithm may jitter.
scrollSpeed 1/1000 Number between 0 and 1 The magnification factor of scrolling
shapeOrigin false "top", "bottom", "left", "right", "center" or any pair of horizontal and vertical positions The position of the point given to a shape function relative to the shape drawn. Normal value for rectangles and text would be "top left". If only one position is defined, e.g. "left" then the other position will be the shape's default: center for arcs; and the top for rectangles and text.
clearBeforeDraw true Boolean: true/false Clearing the canvas before the draw loop can be disabled if you require a difference-based render method.
panning true Boolean: true/false The ability to pan the canvas can be disabled by this switch
zooming true Boolean: true/false The ability to zoom the canvas can be disabled by this switch
zoomPanning true Boolean: true/false The ability to change the center of origin while zooming can be disabled by this switch.If this is off while panning is on, then you will always zoom into the center of the current view, regardless of mouse position, while still being able to change the center by panning.
minShapeZoom 0 Number between 0 and 1 The zoom (out) level that objects will begin to retain their size at, instead of continuing to get smaller.

Functions

All functions are applied to the canvas or container element.

New Functions

Utility functions to handle canvas animation, size, translation, and layering.

Function Arguments Description
$el.animate none Begin animating
$el.stop none Stops animating
$el.drawSpace none Re-draws the canvas, this should be used outside of the animation loop to force a redraw
$el.clear none Clear all canvas contexts, should be called before .drawSpace
$el.reset none Reset canvas transformations (zoom & pan)
$el.setCenter (position) position object like {x:0, y:0} Set the real position that appears in the center of the canvas
$el.setLayer (index) Sets the current drawing context by a zero-index or element ID
$el.size (none OR Object OR property, value) Will return the size as an object if no arguments are passed. Will set the width or height individually if a property and value are both passed, the value can be a function which will set the width or height on resize. Will set all property:value pairs in the object.
$el.Width (none OR val) Will return the width if no value is given. Will se the width if a value is given, the value can be a function that will set the width on resize.
$el.Height (none OR val) Will return the height if no value is given. Will set the height if a value is given, the value can be a function that will set the height on resize.

Config Functions

Configure canvas properties with .config, .set and .get. Set context properties using .configCtx, .setCtx and .getCtx.

Function Arguments Description
$el.config (Object OR property [, value]) If an object is passed it will be used to set the properties given. If only a property is passed it will .get the property and retun it. If a property and value are given it will .set the property to the value.
$el.set (property, value) Will set the canvas property to the value given.
$el.get (property) Returns the canvas property.
Function Arguments Description
$el.configCtx (Object OR property [, value]) If an object is passed it will be used to set the properties given. If only a property is passed it will .getCtx the property and retun it. If a property and value are given it will .setCtx the property to the value.
$el.setCtx (property, value) Will set the context property to the value given.
$el.getCtx (property) Returns the context property.
Function Arguments Description
$el.getOffset Get the current drawing offset of the canvas
$el.position (position) position object like {x:0, y:0} Take a real position and convert it into a canvas position. This should not be used in the animation loop, as all points will already have this transfromation applied.
$el.unPosition (position) position object like {x:0, y:0} Take a canvas position and convert it to a real position (for click checking against a real object)

Drawing Functions

Most of the following functions duplicate existing functionality that is available through the context. The context is not modified, and these functions are applied to the canvas or container element, while running them inside the animation loop the pan and zoom transformations are already applied, whereas they would not be when drawing to the context directly.

Function Arguments Description
$el.fill (style) Optional style argument sets the fillStyle before filling. Flags the context as dirty.
$el.stroke (style) Optional style argument sets the strokeStyle before drawing. Flags the context as dirty.

Rectangles

Function Arguments Description
$el.rect (x, y, w, h) A direct map except positions and sizes are translated and the shapeOrigin property is used.
$el.fillRect (x, y, w, h, style) Optional style argument sets the fillStyle before filling the rectangle. Flags the context as dirty.
$el.strokeRect (x, y, w, h, style) Optional style argument sets the strokeStyle before drawing the rectangle. Flags the context as dirty.
$el.clearRect (x, y, w, h) A direct map except positions and sizes are translated and the shapeOrigin property is used.
$el.paintRect (x, y, w, h, fillStyle, strokeStyle) Optional fillStyle and strokeStyle arguments. Fills, then strokes a rectangle. Flags the context as dirty.

Direct maps of the rectangle functions, except they take one size argument, the length of one side as r.

Function Arguments
$el.square (x, y, r)
$el.fillSquare (x, y, r, style)
$el.strokeSquare (x, y, r, style)
$el.clearSquare (x, y, r)
$el.paintSquare (x, y, r, fillStyle, strokeStyle)

Paths

Paths can be drawn with a pathList, the .path and .closePath functions can take many pathLists or can take maky points as a list of arguments for a path. Each point should be an array of between 2 and 6 coordinates, which will draw a line (2 coords), quadratic curve (4 coords), arc (5 coords) or bezier curve (6 coords), each pathList should be an array of 2 or more point arrays, with the first being a 2-coordinate point. A pathList may also be a list of nested pathLists, so long as at each level the data-type is the same for all members of an array, either coordinates, points or paths.

Function Arguments Description
$el.path (pathList [, pathList, pathList...]) Creates the paths passed as pathLists, running .beginPath for each.
$el.closedPath (pathList [, pathList, pathList...]) Creates the paths passed as pathLists, running .beginPath and .closePath for each.
$el.fillPath (pathList [, style]) Draws closed paths then fills them with an optional fillStyle argument. Flags the context as dirty.
$el.strokePath (pathList [, style]) Draws paths then strokes them with an optional strokeStyle argument. Flags the context as dirty.
$el.paintPath (pathList [, fillStyle, strokeStyle]) Fills then paints the paths. Flags the context as dirty.

The line functions are direct maps of the path functions.

Function Arguments
$el.line (pathList [, pathList, pathList...])
$el.closedLine (pathList [, pathList, pathList...])
$el.fillLine (pathList [, style])
$el.strokeLine (pathList [, style])
$el.paintLine (pathList [, fillStyle, strokeStyle])

Curves

Function Arguments Description
$el.moveTo (x, y) A direct map except positions and sizes are translated.
$el.lineTo (x, y) A direct map except positions and sizes are translated.
$el.curveTo (arguments) Pass between 2 and 6 coordinates as a list or as arguments, which will draw a lineTo (2 coords), quadraticCurveTo (4 coords), arcTo (5 coords) or bezierCurveTo (6 coords).
$el.quadraticCurveTo (cpx, cpy, x, y) A direct map except positions and sizes are translated.
$el.bezierCurveTo (cp1x, cp1y, cp2x, cp2y, x, y) A direct map except positions and sizes are translated.
$el.arcTo (x1, y1, x2, y2, r) A direct map except positions and sizes are translated.

Arcs

Function Arguments Description
$el.arc (x, y, r, a, b) A direct map except positions and sizes are translated and the shapeOrigin property is used.
$el.fillArc (x, y, r, a, b, style) Fill an arc with an optional fillStyle argument. Flags the context as dirty.
$el.strokeArc (x, y, r, a, b, style) Stroke an arc with an optional strokeStyle argument. Flags the context as dirty.
$el.paintArc (x, y, r, a, b[, fillStyle, strokeStyle]) Fill then stroke an arc. Flags the context as dirty.

Circle functions are maps to the arc functions except the start angle is 0 and the end angle is 2Pi.

Function Arguments
$el.circle (x, y, r)
$el.fillCircle (x, y, r, style)
$el.strokeCircle (x, y, r, style)
$el.paintCircle (x, y, r, fillStyle, strokeStyle)

Text

Function Arguments Description
$el.fillText (text, x, y, style, maxWidth) A direct map except positions and sizes are translated and the shapeOrigin property is used. There is also an optional fillStyle argument before the maxWidth. Flags the context as dirty.
$el.strokeText (text, x, y, style, maxWidth) A direct map except positions and sizes are translated and the shapeOrigin property is used. There is also an optional strokeStyle argument before the maxWidth. Flags the context as dirty.
$el.paintText (text, x, y, fillStyle, strokeStyle, maxWidth) Fills then strokes text, taking an optional fillStyle and strokeStyle argument before the maxWidth. Flags the context as dirty.

Other context functions

These functions are mainly identical to the existing context functions.

Function Arguments Description
$el.measureText (text) Direct map.
$el.ellipse (x, y, radiusX, radiusY, rotation, startAngle, endAngle, anticlockwise) A direct map except positions and sizes are translated and the shapeOrigin property is used.
$el.beginPath none Direct map.
$el.closePath none Direct map.
$el.clip none Direct map.
$el.scale (x, y) Direct map.
$el.rotate (angle) Direct map.
$el.translate (x, y) Direct map.
$el.transform (a, b, c, d, e, f) Direct map.
$el.setTransform (a, b, c, d, e, f) Direct map.
$el.createLinearGradient (x, y, x1, y1) A direct map except positions and sizes are translated.
$el.createRadialGradient (x, y, r, x1, y1, r1) A direct map except positions and sizes are translated.
$el.createPattern (image, repetition) Direct map.
$el.createImageData (imagedata OR width, height) Direct map.
$el.getImageData (sx, sy, sw, sh) Direct map.
$el.putImageData (imagedata, dx, dy [, dirtyX, dirtyY, dirtyWidth, dirtyHeight]) Direct map.
$el.save none Direct map.
$el.restore none Direct map.
$el.isPointInPath ([path, ] x, y [, fillRule]) Direct map.

Events

There are only three events: Pan, Zoom and Resize For each event there are three events: Start, Step and Stop For each of those there are three more: Before, On and After

These are the logic functions that are called on each event step, you probably shouldn't call these directly unless you want to update the position without triggering the event loop itself or any of the callbacks.

Function Arguments Description
$el.panEvent (x, y) Pans the canvas by x and y considering zoom
$el.zoomEvent (x, y, z) Zooms at point x, y by factor z
$el.resizeEvent none Sets the width and height to saved values or function outputs, then updates the midpoints

Panning

$el.panStartEvent (ev)
$el.beforePanStart (ev)
$el.panStart (ev)
$el.afterPanStart (ev)
$el.panStepEvent (ev)
$el.beforePanStep (ev)
$el.panStep (ev)
$el.afterPanStep (ev)
$el.panStopEvent (ev)
$el.beforePanStop (ev)
$el.panStop (ev)
$el.afterPanStop (ev)

Zooming

The main .*Event() functions are run when the events are triggered and should probably not be overridden, the other functions are user-defined and will run if they exist. Returning false from a .before*() function will stop the main function before any logic is run.

$el.zoomStartEvent (ev)
$el.beforeZoomStart (ev)
$el.zoomStart (ev)
$el.afterZoomStart (ev)
$el.zoomStepEvent (ev)
$el.beforeZoomStep (ev)
$el.zoomStep (ev)
$el.afterZoomStep (ev)
$el.zoomStopEvent (ev)
$el.beforeZoomStop (ev)
$el.zoomStop (ev)
$el.afterZoomStop (ev)

Resizing

$el.resizeStartEvent (ev)
$el.beforeResizeStart (ev)
$el.resizeStart (ev)
$el.afterResizeStart (ev)
$el.resizeStepEvent (ev)
$el.beforeResizeStep (ev)
$el.resizeStep (ev)
$el.afterResizeStep (ev)
$el.resizeStopEvent (ev)
$el.beforeResizeStop (ev)
$el.resizeStop (ev)
$el.afterResizeStop (ev)

The events are set to the container (or the window for resize) directly instead of using addEventListener, so that they can be overridden easily.

Event Function
Pan $el.onmousedown
Zoom $el.onmousewheel
Resize window.onresize

Event run order

these are the same for all events, with optional operations in brackets

Start

  1. .beforeStart()
  2. Switch state on
  3. .Start()
  4. (events)
  5. (Step)
  6. Begin animation
  7. Prevent event default
  8. .afterStart()
  9. (Stop)

Step

  1. .beforeStep()
  2. Perform interaction logic
  3. .Step()
  4. (events)
  5. Prevent event default
  6. .afterStep()

Stop

  1. .beforeStop()
  2. Switch state off
  3. .Stop()
  4. (events)
  5. Stop animation
  6. Prevent event default
  7. .afterStop()

Property Synonyms

The config functions can take many sysnonyms for properties, mainly variations on the proper name in all cases and using regular delimeters. The synonyms cannot be used to set the properties directly to the element and their proper name should be used.

Context Property Synonyms

Context property synonyms can be set or gotten with the context config functions: .configCtx, .setCtx and .getCtx.

Property Synonyms
fillStyle fill, fill-style, fillstyle, fill_style, fillStyle, fill_Style
strokeStyle stroke, line, stroke-style, line-style, strokestyle, stroke_style, strokeStyle, stroke_Style, linestyle, line_style, lineStyle, line_Style
shadowColor shadow-color, shadowcolor, shadow_color, shadowColor, shadow_Color
shadowBlur shadow-blur, shadowblur, shadow_blur, shadowBlur, shadow_Blur
shadowOffsetX shadow-offset-x, shadowoffsetx, shadow_offset_x, shadowOffsetX, shadow_Offset_X
shadowOffsetY shadow-offset-y, shadowoffsety, shadow_offset_y, shadowOffsetY, shadow_Offset_Y
lineCap line-cap, stroke-cap, linecap, line_cap, lineCap, line_Cap, strokecap, stroke_cap, strokeCap, stroke_Cap
lineJoin line-join, stroke-join, linejoin, line_join, lineJoin, line_Join, strokejoin, stroke_join, strokeJoin, stroke_Join
lineWidth line-width, stroke-width, linewidth, line_width, lineWidth, line_Width, strokewidth, stroke_width, strokeWidth, stroke_Width
miterLimit miter-limit, line-miter, stroke-miter, miterlimit, miter_limit, miterLimit, miter_Limit, linemiter, line_miter, lineMiter, line_Miter, strokemiter, stroke_miter, strokeMiter, stroke_Miter
font font, font-style, text, text-style, fontstyle, font_style, fontStyle, font_Style, textstyle, text_style, textStyle, text_Style
textAlign text-align, font-align, textalign, text_align, textAlign, text_Align, fontalign, font_align, fontAlign, font_Align
textBaseline text-baseline, font-baseline, textbaseline, text_baseline, textBaseline, text_Baseline, fontbaseline, font_baseline, fontBaseline, font_Baseline
globalAlpha global-alpha, globalalpha, global_alpha, globalAlpha, global_Alpha
globalCompositeOperation global-composite-operation, globalcompositeoperation, global_composite_operation, globalCompositeOperation, global_Composite_Operation
data data

Canvas Property Synonyms

New canvas property synonyms that can be set or gotte with the main config functions: .config, .set and .get.

Property Synonyms
center center
midpoint midpoint
focus focus
dirty dirty
zoom zoom
inverseY inverse-y, invert-y, inversey, inverse_y, inverseY, inverse_Y, inverty, invert_y, invertY, invert_Y
inverseZ inverse-z, invert-z, inversez, inverse_z, inverseZ, inverse_Z, invertz, invert_z, invertZ, invert_Z
context context
zoomMin zoom-min, zoommin, zoom_min, zoomMin, zoom_Min
zoomMax zoom-max, zoommax, zoom_max, zoomMax, zoom_Max
scrollSpeed scroll-speed, scrollspeed, scroll_speed, scrollSpeed, scroll_Speed
scaled scaled
shapeOrigin shape-origin, shapeorigin, shape_origin, shapeOrigin, shape_Origin
clearBeforeDraw clear-before-draw, clearbeforedraw, clear_before_draw, clearBeforeDraw, clear_Before_Draw
panning panning
zoomPanning zoom-panning, zoompanning, zoom_panning, zoomPanning, zoom_Panning
zooming zooming
minShapeZoom min-shape-zoom, minshapezoom, min_shape_zoom, minShapeZoom, min_Shape_Zoom

Function Property Synonyms

Function properties can also be set via the main config functions and have several synonyms.

Property Synonyms
draw draw
beforeDraw before-draw, pre-draw, beforedraw, before_draw, beforeDraw, before_Draw, predraw, pre_draw, preDraw, pre_Draw
afterDraw after-draw, post-draw, afterdraw, after_draw, afterDraw, after_Draw, postdraw, post_draw, postDraw, post_Draw
beforePanStart before-pan-start, pre-pan-start, beforepanstart, before_pan_start, beforePanStart, before_Pan_Start, prepanstart, pre_pan_start, prePanStart, pre_Pan_Start
panStart pan-start, panstart, pan_start, panStart, pan_Start
afterPanStart after-pan-start, post-pan-start, afterpanstart, after_pan_start, afterPanStart, after_Pan_Start, postpanstart, post_pan_start, postPanStart, post_Pan_Start
beforePanStep before-pan-step, pre-pan-step, beforepanstep, before_pan_step, beforePanStep, before_Pan_Step, prepanstep, pre_pan_step, prePanStep, pre_Pan_Step
panStep pan-step, panstep, pan_step, panStep, pan_Step
afterPanStep after-pan-step, post-pan-step, afterpanstep, after_pan_step, afterPanStep, after_Pan_Step, postpanstep, post_pan_step, postPanStep, post_Pan_Step
beforePanStop before-pan-stop, pre-pan-stop, beforepanstop, before_pan_stop, beforePanStop, before_Pan_Stop, prepanstop, pre_pan_stop, prePanStop, pre_Pan_Stop
panStop pan-stop, panstop, pan_stop, panStop, pan_Stop
afterPanStop after-pan-stop, post-pan-stop, afterpanstop, after_pan_stop, afterPanStop, after_Pan_Stop, postpanstop, post_pan_stop, postPanStop, post_Pan_Stop
beforeZoomStart before-zoom-start, pre-zoom-start, beforezoomstart, before_zoom_start, beforeZoomStart, before_Zoom_Start, prezoomstart, pre_zoom_start, preZoomStart, pre_Zoom_Start
zoomStart zoom-start, zoomstart, zoom_start, zoomStart, zoom_Start
afterZoomStart after-zoom-start, post-zoom-start, afterzoomstart, after_zoom_start, afterZoomStart, after_Zoom_Start, postzoomstart, post_zoom_start, postZoomStart, post_Zoom_Start
beforeZoomStep before-zoom-step, pre-zoom-step, beforezoomstep, before_zoom_step, beforeZoomStep, before_Zoom_Step, prezoomstep, pre_zoom_step, preZoomStep, pre_Zoom_Step
zoomStep zoom-step, zoomstep, zoom_step, zoomStep, zoom_Step
afterZoomStep after-zoom-step, post-zoom-step, afterzoomstep, after_zoom_step, afterZoomStep, after_Zoom_Step, postzoomstep, post_zoom_step, postZoomStep, post_Zoom_Step
beforeZoomStop before-zoom-stop, pre-zoom-stop, beforezoomstop, before_zoom_stop, beforeZoomStop, before_Zoom_Stop, prezoomstop, pre_zoom_stop, preZoomStop, pre_Zoom_Stop
zoomStop zoom-stop, zoomstop, zoom_stop, zoomStop, zoom_Stop
afterZoomStop after-zoom-stop, post-zoom-stop, afterzoomstop, after_zoom_stop, afterZoomStop, after_Zoom_Stop, postzoomstop, post_zoom_stop, postZoomStop, post_Zoom_Stop
beforeResizeStart before-resize-start, pre-resize-start, beforeresizestart, before_resize_start, beforeResizeStart, before_Resize_Start, preresizestart, pre_resize_start, preResizeStart, pre_Resize_Start
resizeStart resize-start, resizestart, resize_start, resizeStart, resize_Start
afterResizeStart after-resize-start, post-resize-start, afterresizestart, after_resize_start, afterResizeStart, after_Resize_Start, postresizestart, post_resize_start, postResizeStart, post_Resize_Start
beforeResizeStep before-resize-step, pre-resize-step, beforeresizestep, before_resize_step, beforeResizeStep, before_Resize_Step, preresizestep, pre_resize_step, preResizeStep, pre_Resize_Step
resizeStep resize-step, resizestep, resize_step, resizeStep, resize_Step
afterResizeStep after-resize-step, post-resize-step, afterresizestep, after_resize_step, afterResizeStep, after_Resize_Step, postresizestep, post_resize_step, postResizeStep, post_Resize_Step
beforeResizeStop before-resize-stop, pre-resize-stop, beforeresizestop, before_resize_stop, beforeResizeStop, before_Resize_Stop, preresizestop, pre_resize_stop, preResizeStop, pre_Resize_Stop
resizeStop resize-stop, resizestop, resize_stop, resizeStop, resize_Stop
afterResizeStop after-resize-stop, post-resize-stop, afterresizestop, after_resize_stop, afterResizeStop, after_Resize_Stop, postresizestop, post_resize_stop, postResizeStop, post_Resize_Stop