pf-canvas
Simple jQuery canvas utility - This is a little tool that takes a DOM element and a drawing function to create a canvas.
Examples
First require the module to use it. I suggest using jQuery, too.
var canvas = ;var $ = ;
Use the module to draw a static image.
;
Use the module to draw an animated image which works by looping over the drawing function.
;
Often times the drawing function needs its own variables such as color
, size
, and theta
in the example above.
To scope those variables properly, I prefer to rewrite the above as follows
;
The element passed is also returned with a 'draw'
event that can be used to manually redraw the canvas.
;
View these examples in examples/index.html
. To build it, run
npm install browserify -g
npm run build
API
canvas(elem, draw, options)
- elem (DOM, jQuery, Array, String) - The element to turn into a canvas
elem
will be passed through jQuery's jQuery()
function to transform it into a jQuery object. Thus it can be a DOM element, a jQuery object, an array of such, a CSS selector string, or HTML string. (See http://api.jquery.com/jQuery/)
- draw (Function) - The drawing function to be looped
draw
is a function with signature function(ctx)
and ctx
being the canvas's CanvasRenderingContext2D
. To get the canvas's width and height, you may use ctx.canvas.width
and ctx.canvas.height
.
- options (Object) - Optional. An object of options
- id (String) - Default:
null
. An id to give the canvas element - class (String) - Default:
null
. A class to give the canvas element - width (String) - Default:
null
. Set the width of bothelem
and the canvas - height (String) - Default:
null
. Set the height of bothelem
and the canvas - redraw (String) - Default:
'never'
. Determine when to call thedraw
function - resize (Boolean) - Default:
false
. Determine when the canvas is resized
- id (String) - Default:
redraw
is one of 'never'
, 'always'
, 'resize'
. If set to 'never'
, draw
is only called once upon initialization. If set to always
, draw
is called constantly according to requestAnimationFrame()
. If set to 'resize'
, draw
is called when the window is resized.
resize
will update the canvas object to match the dimensions of elem
on window resize, if set to true. Note that even if the dimensions of the canvas do not change, a resize will cause the canvas to clear.
- returns (jQuery) - The jQuery wrapped
elem
variable