Utility functions for working with the HTML5 canvas
var canvasUtils = require('canvas-utils');This function returns the coordinates of mouse events relative to a DOM element. For example a Canvas.
e is a MouseEvent.
canvas is a a DOM element.
returns an Object with a x and y property representing the
pixel on the canvas that the event was fired on.
canvas.addEventListener('click', function(event) {
var xy = convertEventCoords(event, canvas);
canvas.getContext('2d').fillRect(xy.x,xy.y,10,10)
});This is a little verbose. For a nicer way to do this have a look at the CanvasEventEmitter
Rotates a context around a point.
ctx is a CanvasRenderingContext2D.
(That's the thing you get when you do canvas.getContext('2d'))
x is the x-coordinate of the rotation.
y is the y-coordinate.
rotation is the rotation in radians.
Returns the ctx passed in.
Converts radiansto degrees.
Converts degreesto radians.
var createCanvasEventEmitter = require('canvas-utils').createCanvasEventEmitter;target is the canvas for which events should be emitted.
eventSource is the element where the event listeners are attached. It defaults to window.document.
Demo for the CanvasEventEmitter on requirebin
A CanvasEventEmitter is a jvent EventEmitter. jvent is a small EventEmitter that behaves pretty much like a standard node EventEmitter. It emits the following events:
| Events with synonyms |
|---|
mouseup |
mousedown |
mousemove |
mouseover, mousein |
mouseleave, mouseout |
click |
leftclick |
contextmenu, rightclick |
The event object you get for all of these looks like this:
| Property | Description |
|---|---|
| x | the x coordinate of the event relative to the canvas |
| y | the y coordinate of the event relative to the canvas |
| target | the canvas the event belongs to (The target you passed into the constructor) |
| event | the original DOM event emitted on the eventSource |
| button | the button property from the event |
| preventDefault | a function that calles preventDefault on the event |
cee.on('click',function(e){
e.preventDefault();
ctx.fillRect(e.x-5,e.y-5,10,10);
});- 2018-02-16 v0.8.0 Use
jventand add synonyms for some events. - 2018-02-08 v0.7.0 Add imageDataHelper.
- 2015-03-07 v0.6.0 Is now written in ES6.
- 2014-11-02 v0.5.0 Add
radiansToDegreesanddegreesToRadians. - 2014-10-13 v0.4.0 Add
mouseoverandmouseoutevents. - 2014-10-06 v0.3.2 Fix README typo.
- 2014-10-06 v0.3.1 Fix e.button and e.preventDefault().
- 2014-10-06 v0.3.0 Improve convertEventCoords.
- 2014-09-26 v0.2.0 Add contextmenu event.
- 2014-09-12 v0.1.0 Add CanvasEventEmitter.
- 2014-08-16 v0.0.1 Initial version.