-
Notifications
You must be signed in to change notification settings - Fork 0
/
clickableCanvas.js
55 lines (51 loc) · 1.9 KB
/
clickableCanvas.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/** Creates a tile-based grid and associates it to a canvas element
* @param {object} canvas - The canvas element object obtained from document.getElementById
*/
var ClickableCanvas = Object.create({}, {
'extend': {
value: clickableCanvas
}
});
function clickableCanvas(canvas) {
// Validate that the canvas parameter is indeed an existing canvas element
if (canvas.nodeName !== 'CANVAS') {
console.log('ERROR: The element provided is not a canvas element.');
return;
}
// Define the canvas object interface
var properties = {
'onClick': {
value: function (callback) {
var container = canvas.getBoundingClientRect();
canvas.addEventListener('mousedown', function (event) {
callback(event.clientX - container.left, event.clientY - container.top);
});
}
},
'onMouseMove': {
value: function (callback) {
var container = canvas.getBoundingClientRect();
canvas.addEventListener('mousemove', function (event) {
callback(event.clientX - container.left, event.clientY - container.top);
});
}
},
'onMouseUp': {
value: function (callback) {
var container = canvas.getBoundingClientRect();
canvas.addEventListener('mouseup', function (event) {
callback(event.clientX - container.left, event.clientY - container.top);
});
}
},
'setSize': {
writable: true,
value: function (newWidth, newHeight) {
canvas.width = newWidth || window.innerWidth;
canvas.height = newHeight || window.innerHeight;
}
}
}
Object.defineProperties(canvas, properties);
return Object.create({}, properties);
}