Debian Codegraph @

dojox/gfx/canvasWithEvents.js

raw symbols SCIP
1 define(["dojo/_base/lang", "dojo/_base/declare", "dojo/has", "dojo/on", "dojo/aspect", "dojo/touch", "dojo/_base/Color", "dojo/dom",
2 "dojo/dom-geometry", "dojo/_base/window", "./_base","./canvas", "./shape", "./matrix"],
3 function(lang, declare, has, on, aspect, touch, Color, dom, domGeom, win, g, canvas, shapeLib, m){
4 function makeFakeEvent(event){
5 // summary:
6 // Generates a "fake", fully mutable event object by copying the properties from an original host Event
7 // object to a new standard JavaScript object.
8
9 var fakeEvent = {};
10 for(var k in event){
11 if(typeof event[k] === "function"){
12 // Methods (like preventDefault) must be invoked on the original event object, or they will not work
13 fakeEvent[k] = lang.hitch(event, k);
14 }
15 else{
16 fakeEvent[k] = event[k];
17 }
18 }
19 return fakeEvent;
20 }
21
22 // Browsers that implement the current (January 2013) WebIDL spec allow Event object properties to be mutated
23 // using Object.defineProperty; some older WebKits (Safari 6-) and at least IE10- do not follow the spec. Direct
24 // mutation is, of course, much faster when it can be done.
25 has.add("dom-mutableEvents", function(){
26 var event = document.createEvent("UIEvents");
27 try {
28 if(Object.defineProperty){
29 Object.defineProperty(event, "type", { value: "foo" });
30 }else{
31 event.type = "foo";
32 }
33 return event.type === "foo";
34 }catch(e){
35 return false;
36 }
37 });
38
39 var canvasWithEvents = g.canvasWithEvents = {
40 // summary:
41 // This the graphics rendering bridge for W3C Canvas compliant browsers which extends
42 // the basic canvas drawing renderer bridge to add additional support for graphics events
43 // on Shapes.
44 // Since Canvas is an immediate mode graphics api, with no object graph or
45 // eventing capabilities, use of the canvas module alone will only add in drawing support.
46 // This additional module, canvasWithEvents extends this module with additional support
47 // for handling events on Canvas. By default, the support for events is now included
48 // however, if only drawing capabilities are needed, canvas event module can be disabled
49 // using the dojoConfig option, canvasEvents:true|false.
50 };
51
52 canvasWithEvents.Shape = declare("dojox.gfx.canvasWithEvents.Shape", canvas.Shape, {
53 _testInputs: function(/* Object */ ctx, /* Array */ pos){
54 if(this.clip || (!this.canvasFill && this.strokeStyle)){
55 // pixel-based until a getStrokedPath-like api is available on the path
56 this._hitTestPixel(ctx, pos);
57 }else{
58 this._renderShape(ctx);
59 var length = pos.length,
60 t = this.getTransform();
61
62 for(var i = 0; i < length; ++i){
63 var input = pos[i];
64 // already hit
65 if(input.target){continue;}
66 var x = input.x,
67 y = input.y,
68 p = t ? m.multiplyPoint(m.invert(t), x, y) : { x: x, y: y };
69 input.target = this._hitTestGeometry(ctx, p.x, p.y);
70 }
71 }
72 },
73
74 _hitTestPixel: function(/* Object */ ctx, /* Array */ pos){
75 for(var i = 0; i < pos.length; ++i){
76 var input = pos[i];
77 if(input.target){continue;}
78 var x = input.x,
79 y = input.y;
80 ctx.clearRect(0,0,1,1);
81 ctx.save();
82 ctx.translate(-x, -y);
83 this._render(ctx, true);
84 input.target = ctx.getImageData(0, 0, 1, 1).data[0] ? this : null;
85 ctx.restore();
86 }
87 },
88
89 _hitTestGeometry: function(ctx, x, y){
90 return ctx.isPointInPath(x, y) ? this : null;
91 },
92
93 _renderFill: function(/* Object */ ctx, /* Boolean */ apply){
94 // summary:
95 // render fill for the shape
96 // ctx:
97 // a canvas context object
98 // apply:
99 // whether ctx.fill() shall be called
100 if(ctx.pickingMode){
101 if("canvasFill" in this && apply){
102 ctx.fill();
103 }
104 return;
105 }
106 this.inherited(arguments);
107 },
108
109 _renderStroke: function(/* Object */ ctx){
110 // summary:
111 // render stroke for the shape
112 // ctx:
113 // a canvas context object
114 // apply:
115 // whether ctx.stroke() shall be called
116 if(this.strokeStyle && ctx.pickingMode){
117 var c = this.strokeStyle.color;
118 try{
119 this.strokeStyle.color = new Color(ctx.strokeStyle);
120 this.inherited(arguments);
121 }finally{
122 this.strokeStyle.color = c;
123 }
124 }else{
125 this.inherited(arguments);
126 }
127 },
128
129 // events
130
131 getEventSource: function(){
132 return this.surface.rawNode;
133 },
134
135 on: function(type, listener){
136 // summary:
137 // Connects an event to this shape.
138
139 var expectedTarget = this.rawNode;
140
141 // note that event listeners' targets are automatically fixed up in the canvas's addEventListener method
142 return on(this.getEventSource(), type, function(event){
143 if(dom.isDescendant(event.target, expectedTarget)){
144 listener.apply(expectedTarget, arguments);
145 }
146 });
147 },
148
149 connect: function(name, object, method){
150 // summary:
151 // Deprecated. Connects a handler to an event on this shape. Use `on` instead.
152
153 if(name.substring(0, 2) == "on"){
154 name = name.substring(2);
155 }
156 return this.on(name, method ? lang.hitch(object, method) : lang.hitch(null, object));
157 },
158
159 disconnect: function(handle){
160 // summary:
161 // Deprecated. Disconnects an event handler. Use `handle.remove` instead.
162
163 handle.remove();
164 }
165 });
166
167 canvasWithEvents.Group = declare("dojox.gfx.canvasWithEvents.Group", [canvasWithEvents.Shape, canvas.Group], {
168 _testInputs: function(/*Object*/ ctx, /*Array*/ pos){
169 var children = this.children,
170 t = this.getTransform(),
171 i,
172 j,
173 input;
174
175 if(children.length === 0){
176 return;
177 }
178 var posbk = [];
179 for(i = 0; i < pos.length; ++i){
180 input = pos[i];
181 // backup position before transform applied
182 posbk[i] = {
183 x: input.x,
184 y: input.y
185 };
186 if(input.target){continue;}
187 var x = input.x, y = input.y;
188 var p = t ? m.multiplyPoint(m.invert(t), x, y) : { x: x, y: y };
189 input.x = p.x;
190 input.y = p.y;
191 }
192 for(i = children.length - 1; i >= 0; --i){
193 children[i]._testInputs(ctx, pos);
194 // does it need more hit tests ?
195 var allFound = true;
196 for(j = 0; j < pos.length; ++j){
197 if(pos[j].target == null){
198 allFound = false;
199 break;
200 }
201 }
202 if(allFound){
203 break;
204 }
205 }
206 if(this.clip){
207 // filter positive hittests against the group clipping area
208 for(i = 0; i < pos.length; ++i){
209 input = pos[i];
210 input.x = posbk[i].x;
211 input.y = posbk[i].y;
212 if(input.target){
213 ctx.clearRect(0,0,1,1);
214 ctx.save();
215 ctx.translate(-input.x, -input.y);
216 this._render(ctx, true);
217 if(!ctx.getImageData(0, 0, 1, 1).data[0]){
218 input.target = null;
219 }
220 ctx.restore();
221 }
222 }
223 }else{
224 for(i = 0; i < pos.length; ++i){
225 pos[i].x = posbk[i].x;
226 pos[i].y = posbk[i].y;
227 }
228 }
229 }
230
231 });
232
233 canvasWithEvents.Image = declare("dojox.gfx.canvasWithEvents.Image", [canvasWithEvents.Shape, canvas.Image], {
234 _renderShape: function(/* Object */ ctx){
235 // summary:
236 // render image
237 // ctx:
238 // a canvas context object
239 var s = this.shape;
240 if(ctx.pickingMode){
241 ctx.fillRect(s.x, s.y, s.width, s.height);
242 }else{
243 this.inherited(arguments);
244 }
245 },
246 _hitTestGeometry: function(ctx, x, y){
247 // TODO: improve hit testing to take into account transparency
248 var s = this.shape;
249 return x >= s.x && x <= s.x + s.width && y >= s.y && y <= s.y + s.height ? this : null;
250 }
251 });
252
253 canvasWithEvents.Text = declare("dojox.gfx.canvasWithEvents.Text", [canvasWithEvents.Shape, canvas.Text], {
254 _testInputs: function(ctx, pos){
255 return this._hitTestPixel(ctx, pos);
256 }
257 });
258
259 canvasWithEvents.Rect = declare("dojox.gfx.canvasWithEvents.Rect", [canvasWithEvents.Shape, canvas.Rect], {});
260 canvasWithEvents.Circle = declare("dojox.gfx.canvasWithEvents.Circle", [canvasWithEvents.Shape, canvas.Circle], {});
261 canvasWithEvents.Ellipse = declare("dojox.gfx.canvasWithEvents.Ellipse", [canvasWithEvents.Shape, canvas.Ellipse],{});
262 canvasWithEvents.Line = declare("dojox.gfx.canvasWithEvents.Line", [canvasWithEvents.Shape, canvas.Line],{});
263 canvasWithEvents.Polyline = declare("dojox.gfx.canvasWithEvents.Polyline", [canvasWithEvents.Shape, canvas.Polyline],{});
264 canvasWithEvents.Path = declare("dojox.gfx.canvasWithEvents.Path", [canvasWithEvents.Shape, canvas.Path],{});
265 canvasWithEvents.TextPath = declare("dojox.gfx.canvasWithEvents.TextPath", [canvasWithEvents.Shape, canvas.TextPath],{});
266
267 // When events are dispatched using on.emit, certain properties of these events (like target) get overwritten by
268 // the DOM. The only real way to deal with this at the moment, short of never using any standard event properties,
269 // is to store this data out-of-band and fix up the event object passed to the listener by wrapping the listener.
270 // The out-of-band data is stored here.
271 var fixedEventData = null;
272
273 canvasWithEvents.Surface = declare("dojox.gfx.canvasWithEvents.Surface", canvas.Surface, {
274 constructor: function(){
275 this._elementUnderPointer = null;
276 },
277
278 fixTarget: function(listener){
279 // summary:
280 // Corrects the `target` properties of the event object passed to the actual listener.
281 // listener: Function
282 // An event listener function.
283
284 var surface = this;
285
286 return function(event){
287 var k;
288 if(fixedEventData){
289 if(has("dom-mutableEvents")){
290 Object.defineProperties(event, fixedEventData);
291 }else{
292 event = makeFakeEvent(event);
293 for(k in fixedEventData){
294 event[k] = fixedEventData[k].value;
295 }
296 }
297 }else{
298 // non-synthetic events need to have target correction too, but since there is no out-of-band
299 // data we need to figure out the target ourselves
300 var canvas = surface.getEventSource(),
301 target = canvas._dojoElementFromPoint(
302 // touch events may not be fixed at this point, so clientX/Y may not be set on the
303 // event object
304 (event.changedTouches ? event.changedTouches[0] : event).pageX,
305 (event.changedTouches ? event.changedTouches[0] : event).pageY
306 );
307 if(has("dom-mutableEvents")){
308 Object.defineProperties(event, {
309 target: {
310 value: target,
311 configurable: true,
312 enumerable: true
313 },
314 gfxTarget: {
315 value: target.shape,
316 configurable: true,
317 enumerable: true
318 }
319 });
320 }else{
321 event = makeFakeEvent(event);
322 event.target = target;
323 event.gfxTarget = target.shape;
324 }
325 }
326
327 // fixTouchListener in dojo/on undoes target changes by copying everything from changedTouches even
328 // if the value already exists on the event; of course, this canvas implementation currently only
329 // supports one pointer at a time. if we wanted to make sure all the touches arrays' targets were
330 // updated correctly as well, we could support multi-touch and this workaround would not be needed
331 if(has("touch")){
332 // some standard properties like clientX/Y are not provided on the main touch event object,
333 // so copy them over if we need to
334 if(event.changedTouches && event.changedTouches[0]){
335 var changedTouch = event.changedTouches[0];
336 for(k in changedTouch){
337 if(!event[k]){
338 if(has("dom-mutableEvents")){
339 Object.defineProperty(event, k, {
340 value: changedTouch[k],
341 configurable: true,
342 enumerable: true
343 });
344 }else{
345 event[k] = changedTouch[k];
346 }
347 }
348 }
349 }
350 event.corrected = event;
351 }
352
353 return listener.call(this, event);
354 };
355 },
356
357 _checkPointer: function(event){
358 // summary:
359 // Emits enter/leave/over/out events in response to the pointer entering/leaving the inner elements
360 // within the canvas.
361
362 function emit(types, target, relatedTarget){
363 // summary:
364 // Emits multiple synthetic events defined in `types` with the given target `target`.
365
366 var oldBubbles = event.bubbles;
367
368 for(var i = 0, type; (type = types[i]); ++i){
369 // targets get reset when the event is dispatched so we need to give information to fixTarget to
370 // restore the target on the dispatched event through a back channel
371 fixedEventData = {
372 target: { value: target, configurable: true, enumerable: true},
373 gfxTarget: { value: target.shape, configurable: true, enumerable: true },
374 relatedTarget: { value: relatedTarget, configurable: true, enumerable: true }
375 };
376
377 // bubbles can be set directly, though.
378 Object.defineProperty(event, "bubbles", {
379 value: type.bubbles,
380 configurable: true,
381 enumerable: true
382 });
383
384 on.emit(canvas, type.type, event);
385 fixedEventData = null;
386 }
387
388 Object.defineProperty(event, "bubbles", { value: oldBubbles, configurable: true, enumerable: true });
389 }
390
391 // Types must be arrays because hash map order is not guaranteed but we must fire in order to match normal
392 // event behaviour
393 var TYPES = {
394 out: [
395 { type: "mouseout", bubbles: true },
396 { type: "MSPointerOut", bubbles: true },
397 { type: "pointerout", bubbles: true },
398 { type: "mouseleave", bubbles: false },
399 { type: "dojotouchout", bubbles: true}
400 ],
401 over: [
402 { type: "mouseover", bubbles: true },
403 { type: "MSPointerOver", bubbles: true },
404 { type: "pointerover", bubbles: true },
405 { type: "mouseenter", bubbles: false },
406 { type: "dojotouchover", bubbles: true}
407 ]
408 },
409 elementUnderPointer = event.target,
410 oldElementUnderPointer = this._elementUnderPointer,
411 canvas = this.getEventSource();
412
413 if(oldElementUnderPointer !== elementUnderPointer){
414 if(oldElementUnderPointer && oldElementUnderPointer !== canvas){
415 emit(TYPES.out, oldElementUnderPointer, elementUnderPointer);
416 }
417
418 this._elementUnderPointer = elementUnderPointer;
419
420 if(elementUnderPointer && elementUnderPointer !== canvas){
421 emit(TYPES.over, elementUnderPointer, oldElementUnderPointer);
422 }
423 }
424 },
425
426 getEventSource: function(){
427 return this.rawNode;
428 },
429
430 on: function(type, listener){
431 // summary:
432 // Connects an event to this surface.
433
434 return on(this.getEventSource(), type, listener);
435 },
436
437 connect: function(/*String*/ name, /*Object*/ object, /*Function|String*/ method){
438 // summary:
439 // Deprecated. Connects a handler to an event on this surface. Use `on` instead.
440 // name: String
441 // The event name
442 // object: Object
443 // The object that method will receive as "this".
444 // method: Function
445 // A function reference, or name of a function in context.
446
447 if(name.substring(0, 2) == "on"){
448 name = name.substring(2);
449 }
450 return this.on(name, method ? lang.hitch(object, method) : object);
451 },
452
453 disconnect: function(handle){
454 // summary:
455 // Deprecated. Disconnects a handler. Use `handle.remove` instead.
456
457 handle.remove();
458 },
459
460 _initMirrorCanvas: function(){
461 // summary:
462 // Initialises a mirror canvas used for event hit detection.
463
464 this._initMirrorCanvas = function(){};
465
466 var canvas = this.getEventSource(),
467 mirror = this.mirrorCanvas = canvas.ownerDocument.createElement("canvas");
468
469 mirror.width = 1;
470 mirror.height = 1;
471 mirror.style.position = "absolute";
472 mirror.style.left = mirror.style.top = "-99999px";
473 canvas.parentNode.appendChild(mirror);
474
475 var moveEvt = "mousemove";
476 if(has("pointer-events")){
477 moveEvt = "pointermove";
478 }else if(has("MSPointer")){
479 moveEvt = "MSPointerMove";
480 }else if(has("touch-events")){
481 moveEvt = "touchmove";
482 }
483 on(canvas, moveEvt, lang.hitch(this, "_checkPointer"));
484 },
485
486 destroy: function(){
487 if(this.mirrorCanvas){
488 this.mirrorCanvas.parentNode.removeChild(this.mirrorCanvas);
489 this.mirrorCanvas = null;
490 }
491 this.inherited(arguments);
492 }
493 });
494
495 canvasWithEvents.createSurface = function(parentNode, width, height){
496 // summary:
497 // creates a surface (Canvas)
498 // parentNode: Node
499 // a parent node
500 // width: String
501 // width of surface, e.g., "100px"
502 // height: String
503 // height of surface, e.g., "100px"
504
505 if(!width && !height){
506 var pos = domGeom.position(parentNode);
507 width = width || pos.w;
508 height = height || pos.h;
509 }
510 if(typeof width === "number"){
511 width = width + "px";
512 }
513 if(typeof height === "number"){
514 height = height + "px";
515 }
516
517 var surface = new canvasWithEvents.Surface(),
518 parent = dom.byId(parentNode),
519 canvas = parent.ownerDocument.createElement("canvas");
520
521 canvas.width = g.normalizedLength(width); // in pixels
522 canvas.height = g.normalizedLength(height); // in pixels
523
524 parent.appendChild(canvas);
525 surface.rawNode = canvas;
526 surface._parent = parent;
527 surface.surface = surface;
528
529 g._base._fixMsTouchAction(surface);
530
531 // any event handler added to the canvas needs to have its target fixed.
532 var oldAddEventListener = canvas.addEventListener,
533 oldRemoveEventListener = canvas.removeEventListener,
534 listeners = [];
535
536 var addEventListenerImpl = function(type, listener, useCapture){
537 surface._initMirrorCanvas();
538
539 var actualListener = surface.fixTarget(listener);
540 listeners.push({ original: listener, actual: actualListener });
541 oldAddEventListener.call(this, type, actualListener, useCapture);
542 };
543 var removeEventListenerImpl = function(type, listener, useCapture){
544 for(var i = 0, record; (record = listeners[i]); ++i){
545 if(record.original === listener){
546 oldRemoveEventListener.call(this, type, record.actual, useCapture);
547 listeners.splice(i, 1);
548 break;
549 }
550 }
551 };
552 try{
553 Object.defineProperties(canvas, {
554 addEventListener: {
555 value: addEventListenerImpl,
556 enumerable: true,
557 configurable: true
558 },
559 removeEventListener: {
560 value: removeEventListenerImpl
561 }
562 });
563 }catch(e){
564 // Object.defineProperties fails on iOS 4-5. "Not supported on DOM objects").
565 canvas.addEventListener = addEventListenerImpl;
566 canvas.removeEventListener = removeEventListenerImpl;
567 }
568
569
570 canvas._dojoElementFromPoint = function(x, y){
571 // summary:
572 // Returns the shape under the given (x, y) coordinate.
573 // evt:
574 // mouse event
575
576 if(!surface.mirrorCanvas){
577 return this;
578 }
579
580 var surfacePosition = domGeom.position(this, true);
581
582 // use canvas-relative positioning
583 x -= surfacePosition.x;
584 y -= surfacePosition.y;
585
586 var mirror = surface.mirrorCanvas,
587 ctx = mirror.getContext("2d"),
588 children = surface.children;
589
590 ctx.clearRect(0, 0, mirror.width, mirror.height);
591 ctx.save();
592 ctx.strokeStyle = "rgba(127,127,127,1.0)";
593 ctx.fillStyle = "rgba(127,127,127,1.0)";
594 ctx.pickingMode = true;
595
596 // TODO: Make inputs non-array
597 var inputs = [ { x: x, y: y } ];
598
599 // process the inputs to find the target.
600 for(var i = children.length - 1; i >= 0; i--){
601 children[i]._testInputs(ctx, inputs);
602
603 if(inputs[0].target){
604 break;
605 }
606 }
607 ctx.restore();
608 return inputs[0] && inputs[0].target ? inputs[0].target.rawNode : this;
609 };
610
611
612 return surface; // dojox/gfx.Surface
613 };
614
615 var Creator = {
616 createObject: function(){
617 // summary:
618 // Creates a synthetic, partially-interoperable Element object used to uniquely identify the given
619 // shape within the canvas pseudo-DOM.
620
621 var shape = this.inherited(arguments),
622 listeners = {};
623
624 shape.rawNode = {
625 shape: shape,
626 ownerDocument: shape.surface.rawNode.ownerDocument,
627 parentNode: shape.parent ? shape.parent.rawNode : null,
628 addEventListener: function(type, listener){
629 var listenersOfType = listeners[type] = (listeners[type] || []);
630 for(var i = 0, record; (record = listenersOfType[i]); ++i){
631 if(record.listener === listener){
632 return;
633 }
634 }
635
636 listenersOfType.push({
637 listener: listener,
638 handle: aspect.after(this, "on" + type, shape.surface.fixTarget(listener), true)
639 });
640 },
641 removeEventListener: function(type, listener){
642 var listenersOfType = listeners[type];
643 if(!listenersOfType){
644 return;
645 }
646 for(var i = 0, record; (record = listenersOfType[i]); ++i){
647 if(record.listener === listener){
648 record.handle.remove();
649 listenersOfType.splice(i, 1);
650 return;
651 }
652 }
653 }
654 };
655 return shape;
656 }
657 };
658
659 canvasWithEvents.Group.extend(Creator);
660 canvasWithEvents.Surface.extend(Creator);
661
662 return canvasWithEvents;
663 });