-
Notifications
You must be signed in to change notification settings - Fork 0
/
ocanvas.js
6256 lines (5051 loc) · 176 KB
/
ocanvas.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* oCanvas v2.8.3
* http://ocanvas.org/
*
* Copyright 2011-2015, Johannes Koggdal
* Licensed under the MIT license
* http://ocanvas.org/license
*
* Including Xccessors by Eli Grey
* Including easing equations by Robert Penner
*/
(function(window, document, undefined){
// Define the oCanvas object
var oCanvas = {
// Version number of this oCanvas release.
version: "2.8.3",
// Array containing all canvases created by oCanvas on the current page
canvasList: [],
// Object containing all the registered modules
modules: {},
// Object containing all the registered init methods
inits: {},
// Object containing all the registered plugins
plugins: {},
// Define the core class
core: function (options) {
this.isCore = true;
// Add the canvas to the canvas list on the global object
this.id = oCanvas.canvasList.push(this) - 1;
// A number which is used to give new objects an ID
this.lastObjectID = 0;
// Initialize a list of all objects added directly to the canvas
this.children = [];
// Initialize a list of all DOM event handlers
this.domEventHandlers = [];
// Add the registered modules to the new instance of core
for (var m in oCanvas.modules) {
if (typeof oCanvas.modules[m] === "function") {
this[m] = oCanvas.modules[m]();
} else {
this[m] = Object.create(oCanvas.modules[m]);
}
}
// Set up default settings
this.settings = {
fps: 30, // Deprecated value, will soon be changed to 60
background: "transparent",
clearEachFrame: true,
drawEachFrame: true,
disableScrolling: false,
plugins: []
};
// Update the settings with the user specified settings
oCanvas.extend(this.settings, options);
// Save these settings in case the core instance is reset
this.originalSettings = oCanvas.extend({}, this.settings);
// Set canvas to specified element
if (this.settings.canvas.nodeName && this.settings.canvas.nodeName.toLowerCase() === "canvas") {
this.canvasElement = this.settings.canvas;
}
// Set canvas to the element specified using a selector
else if (typeof this.settings.canvas === "string") {
this.canvasElement = document.querySelector(this.settings.canvas);
}
// Return false if no canvas was specified
else {
return false;
}
// Get the canvas context and dimensions
this.canvas = this.canvasElement.getContext("2d");
var width = this.canvasElement.width;
var height = this.canvasElement.height;
Object.defineProperty(this, "width", {
enumerable: true,
configurable: true,
set: function (value) {
width = !isNaN(parseFloat(value)) ? parseFloat(value) : width;
this.canvasElement.width = width;
this.background.set(this.settings.background);
this.redraw();
},
get: function () {
return width;
}
});
Object.defineProperty(this, "height", {
enumerable: true,
configurable: true,
set: function (value) {
height = !isNaN(parseFloat(value)) ? parseFloat(value) : height;
this.canvasElement.height = height;
this.background.set(this.settings.background);
this.redraw();
},
get: function () {
return height;
}
});
// Set the core instance in all modules to enable access of core properties inside of modules
for (var m in oCanvas.modules) {
// Add core access to modules in a wrapper module (like display objects that reside in the wrapper display)
if (this[m].wrapper === true) {
for (var wm in this[m]) {
if (typeof this[m][wm] === "object" && typeof this[m][wm].setCore === "function") {
this[m][wm] = this[m][wm].setCore(this);
}
else if (typeof this[m][wm].setCore === "function") {
this[m][wm].setCore(this);
}
this[m].core = this;
}
}
// Add core access to modules that reside directly in the core
this[m].core = this;
}
// Initialize added modules that have registered init methods
for (var name in oCanvas.inits) {
// Modules directly on the oCanvas object
if ((typeof oCanvas.inits[name] === "string") && (typeof this[name][oCanvas.inits[name]] === "function")) {
this[name][oCanvas.inits[name]]();
}
// Modules that are parts of a wrapper module
else if (oCanvas.inits[name] === "object") {
for (var subname in oCanvas.inits[name]) {
if (typeof this[name][oCanvas.inits[name][subname]] === "function") {
this[name][oCanvas.inits[name][subname]]();
}
}
}
}
// Run plugins if any have been specified
var plugins = this.settings.plugins;
if (plugins.length > 0) {
for (var i = 0, l = plugins.length; i < l; i++) {
if (typeof oCanvas.plugins[plugins[i]] === "function") {
oCanvas.plugins[plugins[i]].call(this);
}
}
}
},
// Method for registering a new module
registerModule: function (name, module, init) {
if (~name.indexOf(".")) {
var parts = name.split(".");
oCanvas.modules[parts[0]][parts[1]] = module;
if (init !== undefined) {
if (!oCanvas.inits[parts[0]]) {
oCanvas.inits[parts[0]] = {};
}
oCanvas.inits[parts[0]][parts[1]] = init;
}
} else {
oCanvas.modules[name] = module;
if (init !== undefined) {
oCanvas.inits[name] = init;
}
}
},
// Method for registering a new plugin
// The plugin will not be run until a new core instance is being created,
// and the instance requests the plugin, thus allowing a plugin to change
// things in the library for just one instance
registerPlugin: function (name, plugin) {
oCanvas.plugins[name] = plugin;
},
// Function for creating a new instance of oCanvas
create: function (settings) {
// Create the new instance and return it
return new oCanvas.core(settings);
},
// Function for checking when the DOM is ready for interaction
domReady: function (func) {
func = func || function () {};
this.domReadyHandlers.push(func);
if (this.isDomReadyListening) {
return false;
}
if (this.isDomReady) {
oCanvas.triggerDomReadyHandlers();
return true;
}
var checkState = function (e) {
if (document.readyState === "complete" || (e && e.type === "DOMContentLoaded")) {
oCanvas.isDomReadyListening = false;
oCanvas.isDomReady = true;
oCanvas.triggerDomReadyHandlers();
document.removeEventListener("readystatechange", checkState, false);
document.removeEventListener("DOMContentLoaded", checkState, false);
}
};
if (checkState()) {
return true;
} else if (!this.isDomReadyListening) {
oCanvas.isDomReadyListening = true;
document.addEventListener("readystatechange", checkState, false);
document.addEventListener("DOMContentLoaded", checkState, false);
return false;
}
},
isDomReady: false,
isDomReadyListening: false,
domReadyHandlers: [],
triggerDomReadyHandlers: function () {
var handlers, i, l, handler;
handlers = this.domReadyHandlers;
for (i = 0, l = handlers.length; i < l; i++) {
handler = handlers[i];
if (handler) {
delete handlers[i];
handler();
}
}
}
};
// Methods the core instances will have access to
oCanvas.core.prototype = {
// Method for adding an object to the canvas
addChild: function (displayobj, redraw) {
displayobj.add(redraw);
return this;
},
// Method for removing an object from the canvas
removeChild: function (displayobj, redraw) {
displayobj.remove(redraw);
return this;
},
// Shorthand method for clearing the canvas
clear: function (keepBackground) {
this.draw.clear(keepBackground);
return this;
},
// Shorthand method for redrawing the canvas
redraw: function () {
this.draw.redraw();
return this;
},
// Method for binding an event to the canvas
bind: function (types, handler) {
this.events.bind(this.canvasElement, types.split(" "), handler);
return this;
},
// Method for unbinding an event from the object
unbind: function (types, handler) {
this.events.unbind(this.canvasElement, types.split(" "), handler);
return this;
},
// Method for triggering all events added to the object
trigger: function (types, eventObject) {
var events = this.events;
events.triggerHandlers(this.canvasElement, types.split(" "), events.fixEventObject(eventObject));
return this;
},
// Method for resetting the core instance to its initial state
reset: function () {
// Remove all objects
var children = this.children;
for (var i = 0, l = children.length; i < l; i++) {
children[i].remove();
i--; l--;
}
children.length = 0;
this.lastObjectID = 0;
// Remove all oCanvas event handlers
var eventTypes = this.canvasElement.events;
for (var type in eventTypes) {
if (eventTypes[type] instanceof Array) {
this.unbind(type, eventTypes[type]);
}
}
// Reset the settings
this.settings = oCanvas.extend({}, this.originalSettings);
},
// Method for destroying the core instance, to clear up memory etc
destroy: function () {
this.reset();
// Remove all DOM event handlers
for (var i = 0, l = this.domEventHandlers.length; i < l; i++) {
oCanvas.removeDOMEventHandler(this, i);
}
this.domEventHandlers.length = 0;
// Remove the core instance from the global list of core instances
oCanvas.canvasList[this.id] = null;
}
};
// Attach the oCanvas object to the window object for access outside of this file
window.oCanvas = oCanvas;
oCanvas.domReady();
// Extend an object with new properties and replace values for existing properties
oCanvas.extend = function () {
// Get first two args
var args = Array.prototype.slice.call(arguments),
last = args[args.length - 1],
destination = args.splice(0, 1)[0],
current = args.splice(0, 1)[0],
x, exclude = [],
descriptor;
// If the last object is an exclude object, get the properties
if (last.exclude && (JSON.stringify(last) === JSON.stringify({exclude:last.exclude}))) {
exclude = last.exclude;
}
// Do the loop unless this object is an exclude object
if (current !== last || exclude.length === 0) {
// Add members from second object to the first
for (x in current) {
// Exclude specified properties
if (~exclude.indexOf(x)) {
continue;
}
descriptor = Object.getOwnPropertyDescriptor(current, x);
if (descriptor.get || descriptor.set) {
Object.defineProperty(destination, x, descriptor);
} else {
destination[x] = current[x];
}
}
}
// If there are more objects passed in, run once more, otherwise return the first object
if (args.length > 0) {
return oCanvas.extend.apply(this, [destination].concat(args));
} else {
return destination;
}
};
oCanvas.addDOMEventHandler = function (core, domObject, eventName, handler, useCapture) {
core.domEventHandlers.push({
obj: domObject,
event: eventName,
handler: handler,
useCapture: !!useCapture
});
domObject.addEventListener(eventName, handler, useCapture);
};
oCanvas.removeDOMEventHandler = function (core, index) {
var data = core.domEventHandlers[index];
data.obj.removeEventListener(data.event, data.handler, data.useCapture);
};
oCanvas.isNumber = function (n) {
return !isNaN(parseFloat(n)) && isFinite(n);
};
// Define Object.create if not available
if (typeof Object.create !== "function") {
Object.create = function (o) {
function F() {}
F.prototype = o;
return new F();
};
}
// Define Object.getPropertyDescriptor if not available.
// This function will check for the descriptor in the whole prototype chain.
if (typeof Object.getPropertyDescriptor !== "function") {
Object.getPropertyDescriptor = function(object, property) {
var descriptor = Object.getOwnPropertyDescriptor(object, property);
var proto = Object.getPrototypeOf(object);
while (descriptor === undefined && proto !== null) {
descriptor = Object.getOwnPropertyDescriptor(proto, property);
proto = Object.getPrototypeOf(proto);
}
return descriptor;
};
}
// requestAnimationFrame polyfill by Erik Möller
// fixes from Paul Irish and Tino Zijdel
// http://paulirish.com/2011/requestanimationframe-for-smart-animating/
// http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating
(function () {
var lastTime = 0;
var vendors = ['ms', 'moz', 'webkit', 'o'];
for (var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) {
window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame'];
window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame']
|| window[vendors[x] + 'CancelRequestAnimationFrame'];
}
if (!window.requestAnimationFrame) {
window.requestAnimationFrame = function (callback, element) {
var currTime = new Date().getTime();
var timeToCall = Math.max(0, 16 - (currTime - lastTime));
var id = window.setTimeout(function () { callback(currTime + timeToCall); }, timeToCall);
lastTime = currTime + timeToCall;
return id;
};
}
if (!window.cancelAnimationFrame) {
window.cancelAnimationFrame = function (id) {
clearTimeout(id);
};
}
}());
// usage: log('inside coolFunc',this,arguments);
// http://paulirish.com/2009/log-a-lightweight-wrapper-for-consolelog/
window.log = function () {
log.history = log.history || []; // store logs to an array for reference
log.history.push(arguments);
if (this.console) {
var i, args = Array.prototype.slice.call(arguments), l = args.length;
for (i = 0; i < l; i++) {
console.log(args[i]);
}
}
};
// Define the timeline class
var timeline = function () {
// Return an object when instantiated
var module = {
init: function () {
var _this = this;
// Method for setting the function to be called for each frame
this.core.setLoop = function (callback) {
_this.userLoop = callback;
// Return the timeline object to enable methods like start() to be called directly
return _this;
};
},
// Set default values when initialized
currentFrame: 1,
timeline: 0,
running: false,
set fps (value) {
this.core.settings.fps = value;
// Restart the timer if the timeline is running
if (this.running) {
this.start();
}
},
get fps () {
return this.core.settings.fps;
},
// Method that will be called for each frame
loop: function () {
if (!this.running) {
return;
}
// Set up a timer to respect the chosen fps,
// but use RAF to decide when the next call should be made.
setTimeout(function () {
module.timeline = requestAnimationFrame(module.loopBound);
var core = module.core;
// If mainLoop has been defined
if (typeof module.userLoop === "function") {
// Clear the canvas if specified
if (core.settings.clearEachFrame === true) {
core.draw.clear();
}
// Trigger the user defined function mainLoop and set this to the current core instance
module.userLoop.call(core, core.canvas);
// Redraw the canvas if specified
if (core.settings.drawEachFrame === true) {
core.draw.redraw();
}
// Increment the frame count
module.currentFrame++;
}
}, 1000 / module.fps);
},
// A wrapper function for the loop to bind this keyword
loopBound: function () {
module.loop();
},
// Method that starts the timeline
start: function () {
cancelAnimationFrame(module.timeline);
module.running = true;
module.loop();
return this;
},
// Method that stops the timeline
stop: function () {
this.running = false;
cancelAnimationFrame(module.timeline);
return this;
}
};
return module;
};
// Register the timeline module
oCanvas.registerModule("timeline", timeline, "init");
// Define the class
var keyboard = function () {
// Return an object when instantiated
return {
keysDown: {},
keyPressTimers: {},
modifiedKeys: [],
// Method for initializing the keyboard object
init: function () {
var self = this;
oCanvas.addDOMEventHandler(this.core, document, "keydown", function (e) { self.docHandler(e); }, false);
oCanvas.addDOMEventHandler(this.core, document, "keyup", function (e) { self.docHandler(e); }, false);
oCanvas.addDOMEventHandler(this.core, document, "keypress", function (e) { self.preventDefault(e); }, false);
},
docHandler: function (e) {
var keyCode, events, canvasElement, eventObject;
events = this.core.events;
canvasElement = this.core.canvasElement;
// Abort if events are disabled
if (!events.enabled) {
return;
}
// Only trigger events if the pointer has set focus to the canvas
// or if there are no pointers registered
if (this.core.pointer && this.core.pointer.canvasFocused !== true) {
return;
}
keyCode = this.getKeyCode(e);
// Prevent default for keys that have been added to the prevent list
this.preventDefault(e);
// Cancel event if the key is already pressed down
// (some browsers repeat even keydown when held down)
if (e.type === "keydown" && this.keysDown[keyCode] === true) {
return;
}
// Set the key states when pressed down
if (e.type === "keydown") {
this.keysDown[keyCode] = true;
} else if (e.type === "keyup") {
delete this.keysDown[keyCode];
}
// Get a fixed event object
eventObject = events.fixEventObject(e, "keyboard");
events.lastKeyboardEventObject = eventObject;
// Trigger events
events.triggerHandlers(canvasElement, [e.type]);
// Set the timer to trigger keypress events continuously until released
if (e.type === "keydown") {
this.keyPressTimers[keyCode] = setInterval(function () {
events.triggerHandlers(canvasElement, ["keypress"], eventObject);
}, 1000 / this.core.settings.fps);
}
// If there are no more keys pressed down, cancel the keypress timers
if (e.type === "keyup") {
if (!this.anyKeysDown()) {
for (keyCode in this.keyPressTimers) {
clearInterval(this.keyPressTimers[keyCode]);
}
} else {
clearInterval(this.keyPressTimers[keyCode]);
}
}
},
// Method for preventing the default behavior of the assigned keys
preventDefault: function (e) {
if ((this.core.mouse && this.core.mouse.canvasFocused === true) || !this.core.mouse) {
var keyCode = this.getKeyCode(e);
if (~this.modifiedKeys.indexOf(keyCode)) {
e.preventDefault();
}
}
},
// Method for adding keys that will have the default actions prevented
addPreventDefaultFor: function (keys) {
// Fix the keys array
keys = (typeof keys === "number") ? [keys] : ((keys instanceof Array) ? keys : []);
// Add the keys
for (var i = 0; i < keys.length; i++) {
this.modifiedKeys.push(keys[i]);
}
},
// Method for removing keys that will no longer have the default actions prevented
removePreventDefaultFor: function (keys) {
// Fix the keys array
keys = (typeof keys === "number") ? [keys] : ((keys instanceof Array) ? keys : []);
// Remove the keys
var i, index;
for (i = 0; i < keys.length; i++) {
index = this.modifiedKeys.indexOf(keys[i]);
if (~index) {
this.modifiedKeys.splice(index, 1);
}
}
},
// Method for getting the key code from current event
getKeyCode: function (e) {
return e.keyCode === 0 ? e.which : e.keyCode;
},
// Method for getting how many keys are currently pressed down
numKeysDown: function () {
var numKeys, keysDown, keyCode;
numKeys = 0;
keysDown = this.keysDown;
// Go through all the keys that are currently pressed down
for (keyCode in keysDown) {
if (keysDown[keyCode] === true) {
numKeys++;
}
}
return numKeys;
},
// Method for checking if any keys are pressed down
anyKeysDown: function () {
return this.numKeysDown() > 0;
},
// Method for getting which keys are currently pressed down
getKeysDown: function () {
var keysDown, currentlyDown, keyCode;
keysDown = this.keysDown;
currentlyDown = [];
// Go through all the keys that are currently pressed down
for (keyCode in keysDown) {
if (keysDown[keyCode] === true) {
currentlyDown.push(parseInt(keyCode, 10));
}
}
return currentlyDown;
},
ARROW_UP:38, ARROW_DOWN:40, ARROW_LEFT:37, ARROW_RIGHT:39, SPACE:32, ENTER:13, ESC:27
};
};
// Register the module
oCanvas.registerModule("keyboard", keyboard, "init");
// Define the class
var mouse = function () {
// Return an object when instantiated
return {
x: 0,
y: 0,
buttonState: "up",
canvasFocused: false,
canvasHovered: false,
cursorValue: "default",
init: function () {
this.core.events.addEventTypes("mouse", {
move: "mousemove",
enter: "mouseenter",
leave: "mouseleave",
down: "mousedown",
up: "mouseup",
singleClick: "click",
doubleClick: "dblclick"
});
this.types = {
"mousemove": "move",
"mousedown": "down",
"mouseup": "up",
"dblclick": "doubleClick"
};
this.core.pointer = this;
// Only bind events for mouse if touch is not available
// This is to enable developers to bind to both touch and mouse,
// but still only trigger handlers once (for the right input device)
if (!this.core.touch || !this.core.touch.isTouch) {
this.bindHandlers();
}
},
bindHandlers: function () {
var self, core, canvasElement, type;
self = this;
core = this.core;
canvasElement = core.canvasElement;
for (type in this.types) {
// Add event listeners to the canvas element
oCanvas.addDOMEventHandler(core, canvasElement, type, function (e) {
self.canvasHandler(e);
}, false);
// Add event listeners to the document (used for setting states and trigger mouseup events)
if (type === "mousemove") {
type = "mouseover";
}
oCanvas.addDOMEventHandler(core, document, type, function (e) {
self.docHandler(e);
}, false);
var a = document.createElement('a');
a.href = document.referrer;
if (a.host === window.location.host && window.parent !== window) {
oCanvas.addDOMEventHandler(core, window.parent.document, type, function (e) {
self.docHandler(e);
}, false);
}
}
},
canvasHandler: function (e, fromDoc) {
var events, onCanvas, type, frontObject;
events = this.core.events;
onCanvas = this.onCanvas(e);
// Trigger only mouseup events if pointer is outside the canvas
if (e.type === "mouseup" && !onCanvas && !this.canvasUpEventTriggered) {
events.triggerPointerEvent(this.types["mouseup"], events.frontObject, "mouse", e);
events.triggerPointerEvent(this.types["mouseup"], this.core.canvasElement, "mouse", e);
this.canvasUpEventTriggered = true;
return;
}
// Abort the handler if the pointer started inside the canvas and is now outside
if (!fromDoc && !onCanvas) {
return;
}
type = (fromDoc && e.type === "mouseover") ? "mousemove" : e.type;
if (!fromDoc) {
this.canvasHovered = true;
}
if (type === "mousedown") {
this.canvasUpEventTriggered = false;
this.canvasFocused = true;
this.buttonState = "down";
}
if (type === "mouseup") {
this.buttonState = "up";
}
// Get the front object for pointer position, among all added objects
frontObject = (fromDoc || !onCanvas) ? undefined : events.getFrontObject("mouse");
// Trigger events
if (fromDoc && events.frontObject) {
events.triggerChain(events.getParentChain(events.frontObject, true, true), ["mouseleave"]);
events.frontObject = null;
} else if (fromDoc) {
events.triggerHandlers(this.core.canvasElement, ["mouseleave"]);
} else {
events.triggerPointerEvent(this.types[type], frontObject, "mouse", e);
}
},
docHandler: function (e) {
var onCanvas = this.onCanvas(e);
if (!onCanvas) {
if (this.core.canvasElement.events.hasEntered) {
if (e.type === "mouseover") {
this.canvasHandler(e, true);
}
} else {
if (e.type === "mouseup") {
if (this.buttonState === "down") {
this.canvasHandler(e, true);
}
}
if (e.type === "mousedown") {
this.canvasFocused = false;
}
}
}
},
getPos: function (e) {
var canvas = this.core.canvasElement;
var boundingRect = canvas.getBoundingClientRect();
var scaleX = canvas.width / canvas.clientWidth;
var scaleY = canvas.height / canvas.clientHeight;
// Calculate the mouse position relative to the viewport.
// e.clientX exists, but has been incorrect in older versions of webkit.
var clientX = e.pageX - window.pageXOffset;
var clientY = e.pageY - window.pageYOffset;
var x = scaleX * (clientX - Math.round(boundingRect.left));
var y = scaleY * (clientY - Math.round(boundingRect.top));
return { x: x, y: y };
},
updatePos: function (e) {
var pos = this.getPos(e);
this.x = pos.x;
this.y = pos.y;
},
onCanvas: function (e) {
e = e || (this.core.events.lastPointerEventObject && this.core.events.lastPointerEventObject.originalEvent);
// Get pointer position
var pos = e ? this.getPos(e) : { x: this.x, y: this.y };
// Check boundaries => (left) && (right) && (top) && (bottom)
if ( (pos.x >= 0) && (pos.x <= this.core.width) && (pos.y >= 0) && (pos.y <= this.core.height) ) {
this.canvasHovered = true;
if (e) this.updatePos(e);
return true;
} else {
this.canvasHovered = false;
return false;
}
},
cancel: function () {
this.core.events.lastDownObject = null;
},
hide: function () {
this.core.canvasElement.style.cursor = "none";
},
show: function () {
this.core.canvasElement.style.cursor = this.cursorValue;
},
cursor: function (value) {
if (~value.indexOf("url(")) {
var m = /url\((.*?)\)(\s(.*?)\s(.*?)|)($|,.*?$)/.exec(value),
options = m[5] ? m[5] : "";
value = "url(" + m[1] + ") " + (m[3] ? m[3] : 0) + " " + (m[4] ? m[4] : 0) + (options !== "" ? options : ", default");
}
this.core.canvasElement.style.cursor = value;
this.cursorValue = value;
}
};
};
// Register the module
oCanvas.registerModule("mouse", mouse, "init");
// Define the class
var touch = function () {
// Return an object when instantiated
return {
x: 0,
y: 0,
touchState: "up",
canvasFocused: false,
canvasHovered: false,
isTouch: ("ontouchstart" in window || "createTouch" in document),
dblTapInterval: 500,
init: function () {
var core, canvasElement;
core = this.core;