Δ.js

Graphics2D.Context

Graphics2D.Context — the library's context, can be got one of these ways:

var ctx = Graphics2D.id('element'); // canvas with id="element"
var ctx = Graphics2D.query('canvas', 0); // the first canvas on the page
// query also receives the dom element
var ctx = Graphics2D.query( document.getElementById('foo') );

Methods

All the methods return the context (so you can use jQuery-like chaining), if not otherwise required.

getObjectInPoint(x, y)

ctx.getObjectInPoint(10, 10);

Returns an object in point (x; y), or null, if there's not. If the third argument is true, will ignore objects with mouse processing turned off (interaction attr).

on(event, func)

ctx.on('click', function(e){
    if(e.targetObject){
        e.targetObject.attr('fill', 'red');
    }
    x = e.contextX;
    y = e.contextY;
});

Adds an event listener to canvas. Extends event object (variable e in the example above) by 3 properties:

off(event, [func])

ctx.on('click', anyfunc);
ctx.off('click', anyfunc);
ctx.off('click'); // removes all the click listeners

Removes event listener(s) from canvas.

Note: ctx.off('click') will only remove context listeners (set with ctx.on), but not the elements'.

fire(event, [data])

ctx.on('click', function(data){ console.log(data.text); });
ctx.fire('click', {text:'anytext'});

Fires all the event listeners.

update

ctx.update();

Internal method, updates the canvas. Use it only if you update internal object parameters or something like.

Event aliases

ctx.click(function(){ console.log(3); }); // = on('click', function(){ console.log(3); });
ctx.click(); // = fire('click');

click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, mousewheel, focus, blur.

Elements

You can create obs directly on the canvas:

Rectangle:

ctx.rect(x, y, width, height, [fill, stroke]);

Circle:

ctx.circle(centerX, centerY, radius, [fill, stroke]);

Path:

ctx.path(data, [fill, stroke]);

Image:

ctx.image(image, x, y, [width, height, crop]);

Text:

ctx.text(text, font, x, y, [fill, stroke]);

Gradient:

ctx.gradient([type], colors, [from, to]);

Pattern:

ctx.pattern(image, [repeat]);