Events
oCanvas offers a broad support for events — keyboard, mouse and touch — and packs all this together in one simple bind()
method. This makes it extremely easy to add support for both mouse and touch devices.
When working with both mouse and touch, and you want to access a property or method that is common for both of these, there is a special property of the core instance; pointer
. This refers to the pointer in use. On touch devices core.pointer
refers to core.touch
and otherwise to core.mouse
. So if you need the x position of the pointer, regardless of which pointing device being used, you write core.pointer.x
.
Mouse and touch events are triggered within the shape itself (read more on the page for Mouse/Touch). Since oCanvas 2.0.0, events are triggered according to a set model, very much the same as DOM events. Events are triggered first for the front object for the current pointer position, and then they bubble up along the parent chain of that object, including the canvas element. You can stop the bubbling at any point in this event phase, by calling the method stopPropagation()
on the event object. In oCanvas 1.0.0, events were triggered for all objects that the pointer was inside, not just the front object. They also didn't propagate through the parent chain.
Both the core instance and all display objects have a bind()
method. It is used for adding handlers to events on a particular object. It works across all event types for keyboard, mouse and touch.
Pages
Methods
Properties
- enabled : Boolean (since version 2.0.0)
- If set to
false
, the event system will be turned off and no events will be fired. Setting it totrue
will turn it on again.
Examples
Example 1
First we create an instance of the core object. Then we add an event handler for the click event, that will change the background color.
View Examplevar canvas = oCanvas.create({
canvas: "#canvas",
background: "#ccc"
});
canvas.bind("click tap", function () {
canvas.background.set("hsl(" + Math.random() * 360 + ", 50%, 50%)");
});
Output
Example 2
We create a core instance and a rectangle and add it to the canvas. Then we add an event handler for the click event, that will change the fill color of the rectangle.
View Examplevar canvas = oCanvas.create({
canvas: "#canvas",
background: "#ccc"
});
var button = canvas.display.rectangle({
x: 77,
y: 74,
width: 200,
height: 100,
fill: "#000"
});
canvas.addChild(button);
button.bind("click tap", function () {
this.fill = "hsl(" + Math.random() * 360 + ", 50%, 50%)";
canvas.redraw();
});
Output