-
Notifications
You must be signed in to change notification settings - Fork 757
/
Stage.js
757 lines (690 loc) · 26.7 KB
/
Stage.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
/*jshint unused:false */
(function() {
// CONSTANTS
var STAGE = 'Stage',
STRING = 'string',
PX = 'px',
MOUSEOUT = 'mouseout',
MOUSELEAVE = 'mouseleave',
MOUSEOVER = 'mouseover',
MOUSEENTER = 'mouseenter',
MOUSEMOVE = 'mousemove',
MOUSEDOWN = 'mousedown',
MOUSEUP = 'mouseup',
CLICK = 'click',
DBL_CLICK = 'dblclick',
TOUCHSTART = 'touchstart',
TOUCHEND = 'touchend',
TAP = 'tap',
DBL_TAP = 'dbltap',
TOUCHMOVE = 'touchmove',
DOMMOUSESCROLL = 'DOMMouseScroll',
MOUSEWHEEL = 'mousewheel',
WHEEL = 'wheel',
CONTENT_MOUSEOUT = 'contentMouseout',
CONTENT_MOUSEOVER = 'contentMouseover',
CONTENT_MOUSEMOVE = 'contentMousemove',
CONTENT_MOUSEDOWN = 'contentMousedown',
CONTENT_MOUSEUP = 'contentMouseup',
CONTENT_CLICK = 'contentClick',
CONTENT_DBL_CLICK = 'contentDblclick',
CONTENT_TOUCHSTART = 'contentTouchstart',
CONTENT_TOUCHEND = 'contentTouchend',
CONTENT_DBL_TAP = 'contentDbltap',
CONTENT_TOUCHMOVE = 'contentTouchmove',
DIV = 'div',
RELATIVE = 'relative',
INLINE_BLOCK = 'inline-block',
KINETICJS_CONTENT = 'kineticjs-content',
SPACE = ' ',
UNDERSCORE = '_',
CONTAINER = 'container',
EMPTY_STRING = '',
EVENTS = [MOUSEDOWN, MOUSEMOVE, MOUSEUP, MOUSEOUT, TOUCHSTART, TOUCHMOVE, TOUCHEND, MOUSEOVER, DOMMOUSESCROLL, MOUSEWHEEL, WHEEL],
// cached variables
eventsLength = EVENTS.length;
function addEvent(ctx, eventName) {
ctx.content.addEventListener(eventName, function(evt) {
ctx[UNDERSCORE + eventName](evt);
}, false);
}
Kinetic.Util.addMethods(Kinetic.Stage, {
___init: function(config) {
this.nodeType = STAGE;
// call super constructor
Kinetic.Container.call(this, config);
this._id = Kinetic.idCounter++;
this._buildDOM();
this._bindContentEvents();
this._enableNestedTransforms = false;
Kinetic.stages.push(this);
},
_validateAdd: function(child) {
if (child.getType() !== 'Layer') {
Kinetic.Util.error('You may only add layers to the stage.');
}
},
/**
* set container dom element which contains the stage wrapper div element
* @method
* @memberof Kinetic.Stage.prototype
* @param {DomElement} container can pass in a dom element or id string
*/
setContainer: function(container) {
if( typeof container === STRING) {
var id = container;
container = Kinetic.document.getElementById(container);
if (!container) {
throw 'Can not find container in document with id ' + id;
}
}
this._setAttr(CONTAINER, container);
return this;
},
shouldDrawHit: function() {
return true;
},
draw: function() {
Kinetic.Node.prototype.draw.call(this);
return this;
},
/**
* draw layer scene graphs
* @name draw
* @method
* @memberof Kinetic.Stage.prototype
*/
/**
* draw layer hit graphs
* @name drawHit
* @method
* @memberof Kinetic.Stage.prototype
*/
/**
* set height
* @method
* @memberof Kinetic.Stage.prototype
* @param {Number} height
*/
setHeight: function(height) {
Kinetic.Node.prototype.setHeight.call(this, height);
this._resizeDOM();
return this;
},
/**
* set width
* @method
* @memberof Kinetic.Stage.prototype
* @param {Number} width
*/
setWidth: function(width) {
Kinetic.Node.prototype.setWidth.call(this, width);
this._resizeDOM();
return this;
},
/**
* clear all layers
* @method
* @memberof Kinetic.Stage.prototype
*/
clear: function() {
var layers = this.children,
len = layers.length,
n;
for(n = 0; n < len; n++) {
layers[n].clear();
}
return this;
},
clone: function(obj) {
if (!obj) {
obj = {};
}
obj.container = Kinetic.document.createElement(DIV);
return Kinetic.Container.prototype.clone.call(this, obj);
},
/**
* destroy stage
* @method
* @memberof Kinetic.Stage.prototype
*/
destroy: function() {
var content = this.content;
Kinetic.Container.prototype.destroy.call(this);
if(content && Kinetic.Util._isInDocument(content)) {
this.getContainer().removeChild(content);
}
var index = Kinetic.stages.indexOf(this);
if (index > -1) {
Kinetic.stages.splice(index, 1);
}
},
/**
* get pointer position which can be a touch position or mouse position
* @method
* @memberof Kinetic.Stage.prototype
* @returns {Object}
*/
getPointerPosition: function() {
return this.pointerPos;
},
getStage: function() {
return this;
},
/**
* get stage content div element which has the
* the class name "kineticjs-content"
* @method
* @memberof Kinetic.Stage.prototype
*/
getContent: function() {
return this.content;
},
/**
* Creates a composite data URL and requires a callback because the composite is generated asynchronously.
* @method
* @memberof Kinetic.Stage.prototype
* @param {Object} config
* @param {Function} config.callback function executed when the composite has completed
* @param {String} [config.mimeType] can be "image/png" or "image/jpeg".
* "image/png" is the default
* @param {Number} [config.x] x position of canvas section
* @param {Number} [config.y] y position of canvas section
* @param {Number} [config.width] width of canvas section
* @param {Number} [config.height] height of canvas section
* @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType,
* you can specify the quality from 0 to 1, where 0 is very poor quality and 1
* is very high quality
*/
toDataURL: function(config) {
config = config || {};
var mimeType = config.mimeType || null,
quality = config.quality || null,
x = config.x || 0,
y = config.y || 0,
canvas = new Kinetic.SceneCanvas({
width: config.width || this.getWidth(),
height: config.height || this.getHeight(),
pixelRatio: 1
}),
_context = canvas.getContext()._context,
layers = this.children;
if(x || y) {
_context.translate(-1 * x, -1 * y);
}
function drawLayer(n) {
var layer = layers[n],
layerUrl = layer.toDataURL(),
imageObj = new Kinetic.window.Image();
imageObj.onload = function() {
_context.drawImage(imageObj, 0, 0);
if(n < layers.length - 1) {
drawLayer(n + 1);
}
else {
config.callback(canvas.toDataURL(mimeType, quality));
}
};
imageObj.src = layerUrl;
}
drawLayer(0);
},
/**
* converts stage into an image.
* @method
* @memberof Kinetic.Stage.prototype
* @param {Object} config
* @param {Function} config.callback function executed when the composite has completed
* @param {String} [config.mimeType] can be "image/png" or "image/jpeg".
* "image/png" is the default
* @param {Number} [config.x] x position of canvas section
* @param {Number} [config.y] y position of canvas section
* @param {Number} [config.width] width of canvas section
* @param {Number} [config.height] height of canvas section
* @param {Number} [config.quality] jpeg quality. If using an "image/jpeg" mimeType,
* you can specify the quality from 0 to 1, where 0 is very poor quality and 1
* is very high quality
*/
toImage: function(config) {
var cb = config.callback;
config.callback = function(dataUrl) {
Kinetic.Util._getImage(dataUrl, function(img) {
cb(img);
});
};
this.toDataURL(config);
},
/**
* get visible intersection shape. This is the preferred
* method for determining if a point intersects a shape or not
* @method
* @memberof Kinetic.Stage.prototype
* @param {Object} pos
* @param {Number} pos.x
* @param {Number} pos.y
* @returns {Kinetic.Shape}
*/
getIntersection: function(pos) {
var layers = this.getChildren(),
len = layers.length,
end = len - 1,
n, shape;
for(n = end; n >= 0; n--) {
shape = layers[n].getIntersection(pos);
if (shape) {
return shape;
}
}
return null;
},
_resizeDOM: function() {
if(this.content) {
var width = this.getWidth(),
height = this.getHeight(),
layers = this.getChildren(),
len = layers.length,
n, layer;
// set content dimensions
this.content.style.width = width + PX;
this.content.style.height = height + PX;
this.bufferCanvas.setSize(width, height);
this.bufferHitCanvas.setSize(width, height);
// set layer dimensions
for(n = 0; n < len; n++) {
layer = layers[n];
layer.setSize(width, height);
layer.draw();
}
}
},
/**
* add layer or layers to stage
* @method
* @memberof Kinetic.Stage.prototype
* @param {...Kinetic.Layer} layer
* @example
* stage.add(layer1, layer2, layer3);
*/
add: function(layer) {
if (arguments.length > 1) {
for (var i = 0; i < arguments.length; i++) {
this.add(arguments[i]);
}
return;
}
Kinetic.Container.prototype.add.call(this, layer);
layer._setCanvasSize(this.width(), this.height());
// draw layer and append canvas to container
layer.draw();
this.content.appendChild(layer.canvas._canvas);
// chainable
return this;
},
getParent: function() {
return null;
},
getLayer: function() {
return null;
},
/**
* returns a {@link Kinetic.Collection} of layers
* @method
* @memberof Kinetic.Stage.prototype
*/
getLayers: function() {
return this.getChildren();
},
_bindContentEvents: function() {
for (var n = 0; n < eventsLength; n++) {
addEvent(this, EVENTS[n]);
}
},
_mouseover: function(evt) {
if (!Kinetic.UA.mobile) {
this._setPointerPosition(evt);
this._fire(CONTENT_MOUSEOVER, {evt: evt});
}
},
_mouseout: function(evt) {
if (!Kinetic.UA.mobile) {
this._setPointerPosition(evt);
var targetShape = this.targetShape;
if(targetShape && !Kinetic.isDragging()) {
targetShape._fireAndBubble(MOUSEOUT, {evt: evt});
targetShape._fireAndBubble(MOUSELEAVE, {evt: evt});
this.targetShape = null;
}
this.pointerPos = undefined;
this._fire(CONTENT_MOUSEOUT, {evt: evt});
}
},
_mousemove: function(evt) {
// workaround for mobile IE to force touch event when unhandled pointer event elevates into a mouse event
if (Kinetic.UA.ieMobile) {
return this._touchmove(evt);
}
// workaround fake mousemove event in chrome browser https://code.google.com/p/chromium/issues/detail?id=161464
if ((typeof evt.webkitMovementX !== 'undefined' || typeof evt.webkitMovementY !== 'undefined') && evt.webkitMovementY === 0 && evt.webkitMovementX === 0) {
return;
}
if (Kinetic.UA.mobile) {
return;
}
this._setPointerPosition(evt);
var dd = Kinetic.DD, shape;
if (!Kinetic.isDragging()) {
shape = this.getIntersection(this.getPointerPosition());
if(shape && shape.isListening()) {
if(!Kinetic.isDragging() && (!this.targetShape || this.targetShape._id !== shape._id)) {
if(this.targetShape) {
this.targetShape._fireAndBubble(MOUSEOUT, {evt: evt}, shape);
this.targetShape._fireAndBubble(MOUSELEAVE, {evt: evt}, shape);
}
shape._fireAndBubble(MOUSEOVER, {evt: evt}, this.targetShape);
shape._fireAndBubble(MOUSEENTER, {evt: evt}, this.targetShape);
this.targetShape = shape;
}
else {
shape._fireAndBubble(MOUSEMOVE, {evt: evt});
}
}
/*
* if no shape was detected, clear target shape and try
* to run mouseout from previous target shape
*/
else {
if(this.targetShape && !Kinetic.isDragging()) {
this.targetShape._fireAndBubble(MOUSEOUT, {evt: evt});
this.targetShape._fireAndBubble(MOUSELEAVE, {evt: evt});
this.targetShape = null;
}
}
// content event
this._fire(CONTENT_MOUSEMOVE, {evt: evt});
}
if(dd) {
dd._drag(evt);
}
// always call preventDefault for desktop events because some browsers
// try to drag and drop the canvas element
if (evt.preventDefault) {
evt.preventDefault();
}
},
_mousedown: function(evt) {
// workaround for mobile IE to force touch event when unhandled pointer event elevates into a mouse event
if (Kinetic.UA.ieMobile) {
return this._touchstart(evt);
}
if (!Kinetic.UA.mobile) {
this._setPointerPosition(evt);
var shape = this.getIntersection(this.getPointerPosition());
Kinetic.listenClickTap = true;
if (shape && shape.isListening()) {
this.clickStartShape = shape;
shape._fireAndBubble(MOUSEDOWN, {evt: evt});
}
// content event
this._fire(CONTENT_MOUSEDOWN, {evt: evt});
}
// always call preventDefault for desktop events because some browsers
// try to drag and drop the canvas element
if (evt.preventDefault) {
evt.preventDefault();
}
},
_mouseup: function(evt) {
// workaround for mobile IE to force touch event when unhandled pointer event elevates into a mouse event
if (Kinetic.UA.ieMobile) {
return this._touchend(evt);
}
if (!Kinetic.UA.mobile) {
this._setPointerPosition(evt);
var shape = this.getIntersection(this.getPointerPosition()),
clickStartShape = this.clickStartShape,
fireDblClick = false,
dd = Kinetic.DD;
if(Kinetic.inDblClickWindow) {
fireDblClick = true;
Kinetic.inDblClickWindow = false;
}
// don't set inDblClickWindow after dragging
else if (!dd || !dd.justDragged) {
Kinetic.inDblClickWindow = true;
} else if (dd) {
dd.justDragged = false;
}
setTimeout(function() {
Kinetic.inDblClickWindow = false;
}, Kinetic.dblClickWindow);
if (shape && shape.isListening()) {
shape._fireAndBubble(MOUSEUP, {evt: evt});
// detect if click or double click occurred
if(Kinetic.listenClickTap && clickStartShape && clickStartShape._id === shape._id) {
shape._fireAndBubble(CLICK, {evt: evt});
if(fireDblClick) {
shape._fireAndBubble(DBL_CLICK, {evt: evt});
}
}
}
// content events
this._fire(CONTENT_MOUSEUP, {evt: evt});
if (Kinetic.listenClickTap) {
this._fire(CONTENT_CLICK, {evt: evt});
if(fireDblClick) {
this._fire(CONTENT_DBL_CLICK, {evt: evt});
}
}
Kinetic.listenClickTap = false;
}
// always call preventDefault for desktop events because some browsers
// try to drag and drop the canvas element
if (evt.preventDefault) {
evt.preventDefault();
}
},
_touchstart: function(evt) {
this._setPointerPosition(evt);
var shape = this.getIntersection(this.getPointerPosition());
Kinetic.listenClickTap = true;
if (shape && shape.isListening()) {
this.tapStartShape = shape;
shape._fireAndBubble(TOUCHSTART, {evt: evt});
// only call preventDefault if the shape is listening for events
if (shape.isListening() && evt.preventDefault) {
evt.preventDefault();
}
}
// content event
this._fire(CONTENT_TOUCHSTART, {evt: evt});
},
_touchend: function(evt) {
this._setPointerPosition(evt);
var shape = this.getIntersection(this.getPointerPosition()),
fireDblClick = false;
if(Kinetic.inDblClickWindow) {
fireDblClick = true;
Kinetic.inDblClickWindow = false;
}
else {
Kinetic.inDblClickWindow = true;
}
setTimeout(function() {
Kinetic.inDblClickWindow = false;
}, Kinetic.dblClickWindow);
if (shape && shape.isListening()) {
shape._fireAndBubble(TOUCHEND, {evt: evt});
// detect if tap or double tap occurred
if(Kinetic.listenClickTap && shape._id === this.tapStartShape._id) {
shape._fireAndBubble(TAP, {evt: evt});
if(fireDblClick) {
shape._fireAndBubble(DBL_TAP, {evt: evt});
}
}
// only call preventDefault if the shape is listening for events
if (shape.isListening() && evt.preventDefault) {
evt.preventDefault();
}
}
// content events
if (Kinetic.listenClickTap) {
this._fire(CONTENT_TOUCHEND, {evt: evt});
if(fireDblClick) {
this._fire(CONTENT_DBL_TAP, {evt: evt});
}
}
Kinetic.listenClickTap = false;
},
_touchmove: function(evt) {
this._setPointerPosition(evt);
var dd = Kinetic.DD,
shape;
if (!Kinetic.isDragging()) {
shape = this.getIntersection(this.getPointerPosition());
if (shape && shape.isListening()) {
shape._fireAndBubble(TOUCHMOVE, {evt: evt});
// only call preventDefault if the shape is listening for events
if (shape.isListening() && evt.preventDefault) {
evt.preventDefault();
}
}
this._fire(CONTENT_TOUCHMOVE, {evt: evt});
}
if(dd) {
dd._drag(evt);
if (Kinetic.isDragging()) {
evt.preventDefault();
}
}
},
_DOMMouseScroll: function(evt) {
this._mousewheel(evt);
},
_mousewheel: function(evt) {
this._setPointerPosition(evt);
var shape = this.getIntersection(this.getPointerPosition());
if (shape && shape.isListening()) {
shape._fireAndBubble(MOUSEWHEEL, {evt: evt});
}
},
_wheel: function(evt) {
this._mousewheel(evt);
},
_setPointerPosition: function(evt) {
var contentPosition = this._getContentPosition(),
offsetX = evt.offsetX,
clientX = evt.clientX,
x = null,
y = null,
touch;
evt = evt ? evt : window.event;
// touch events
if(evt.touches !== undefined) {
// currently, only handle one finger
if (evt.touches.length > 0) {
touch = evt.touches[0];
// get the information for finger #1
x = touch.clientX - contentPosition.left;
y = touch.clientY - contentPosition.top;
}
}
// mouse events
else {
// if offsetX is defined, assume that offsetY is defined as well
if (offsetX !== undefined) {
x = offsetX;
y = evt.offsetY;
}
// we unfortunately have to use UA detection here because accessing
// the layerX or layerY properties in newer versions of Chrome
// throws a JS warning. layerX and layerY are required for FF
// when the container is transformed via CSS.
else if (Kinetic.UA.browser === 'mozilla') {
x = evt.layerX;
y = evt.layerY;
}
// if clientX is defined, assume that clientY is defined as well
else if (clientX !== undefined && contentPosition) {
x = clientX - contentPosition.left;
y = evt.clientY - contentPosition.top;
}
}
if (x !== null && y !== null) {
this.pointerPos = {
x: x,
y: y
};
}
},
_getContentPosition: function() {
var rect = this.content.getBoundingClientRect ? this.content.getBoundingClientRect() : { top: 0, left: 0 };
return {
top: rect.top,
left: rect.left
};
},
_buildDOM: function() {
var container = this.getContainer();
if (!container) {
if (Kinetic.Util.isBrowser()) {
throw 'Stage has no container. A container is required.';
} else {
// automatically create element for jsdom in nodejs env
container = Kinetic.document.createElement(DIV);
}
}
// clear content inside container
container.innerHTML = EMPTY_STRING;
// content
this.content = Kinetic.document.createElement(DIV);
this.content.style.position = RELATIVE;
this.content.style.display = INLINE_BLOCK;
this.content.className = KINETICJS_CONTENT;
this.content.setAttribute('role', 'presentation');
container.appendChild(this.content);
// the buffer canvas pixel ratio must be 1 because it is used as an
// intermediate canvas before copying the result onto a scene canvas.
// not setting it to 1 will result in an over compensation
this.bufferCanvas = new Kinetic.SceneCanvas({
pixelRatio: 1
});
this.bufferHitCanvas = new Kinetic.HitCanvas();
this._resizeDOM();
},
_onContent: function(typesStr, handler) {
var types = typesStr.split(SPACE),
len = types.length,
n, baseEvent;
for(n = 0; n < len; n++) {
baseEvent = types[n];
this.content.addEventListener(baseEvent, handler, false);
}
},
// currently cache function is now working for stage, because stage has no its own canvas element
// TODO: may be it is better to cache all children layers?
cache: function() {
Kinetic.Util.warn('Cache function is not allowed for stage. You may use cache only for layers, groups and shapes.');
},
clearCache : function() {
}
});
Kinetic.Util.extend(Kinetic.Stage, Kinetic.Container);
// add getters and setters
Kinetic.Factory.addGetter(Kinetic.Stage, 'container');
Kinetic.Factory.addOverloadedGetterSetter(Kinetic.Stage, 'container');
/**
* get container DOM element
* @name container
* @method
* @memberof Kinetic.Stage.prototype
* @returns {DomElement} container
* @example
* // get container
* var container = stage.container();
*
* // set container
* var container = document.createElement('div');
* body.appendChild(container);
* stage.container(container);
*/
})();