-
-
Notifications
You must be signed in to change notification settings - Fork 916
/
Layer.ts
540 lines (505 loc) · 14 KB
/
Layer.ts
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
import { Util } from './Util';
import { Container, ContainerConfig } from './Container';
import { Node } from './Node';
import { Factory } from './Factory';
import { SceneCanvas, HitCanvas } from './Canvas';
import { Stage } from './Stage';
import { getBooleanValidator } from './Validators';
import { GetSet, Vector2d } from './types';
import { Group } from './Group';
import { Shape, shapes } from './Shape';
import { _registerNode } from './Global';
export interface LayerConfig extends ContainerConfig {
clearBeforeDraw?: boolean;
hitGraphEnabled?: boolean;
imageSmoothingEnabled?: boolean;
}
// constants
var HASH = '#',
BEFORE_DRAW = 'beforeDraw',
DRAW = 'draw',
/*
* 2 - 3 - 4
* | |
* 1 - 0 5
* |
* 8 - 7 - 6
*/
INTERSECTION_OFFSETS = [
{ x: 0, y: 0 }, // 0
{ x: -1, y: -1 }, // 2
{ x: 1, y: -1 }, // 4
{ x: 1, y: 1 }, // 6
{ x: -1, y: 1 }, // 8
],
INTERSECTION_OFFSETS_LEN = INTERSECTION_OFFSETS.length;
/**
* Layer constructor. Layers are tied to their own canvas element and are used
* to contain groups or shapes.
* @constructor
* @memberof Konva
* @augments Konva.Container
* @param {Object} config
* @param {Boolean} [config.clearBeforeDraw] set this property to false if you don't want
* to clear the canvas before each layer draw. The default value is true.
* @@nodeParams
* @@containerParams
* @example
* var layer = new Konva.Layer();
* stage.add(layer);
* // now you can add shapes, groups into the layer
*/
export class Layer extends Container<Group | Shape> {
canvas = new SceneCanvas();
hitCanvas = new HitCanvas({
pixelRatio: 1,
});
_waitingForDraw = false;
constructor(config?: LayerConfig) {
super(config);
this.on('visibleChange.konva', this._checkVisibility);
this._checkVisibility();
this.on('imageSmoothingEnabledChange.konva', this._setSmoothEnabled);
this._setSmoothEnabled();
}
// for nodejs?
createPNGStream() {
const c = this.canvas._canvas as any;
return c.createPNGStream();
}
/**
* get layer canvas wrapper
* @method
* @name Konva.Layer#getCanvas
*/
getCanvas() {
return this.canvas;
}
/**
* get native canvas element
* @method
* @name Konva.Layer#getNativeCanvasElement
*/
getNativeCanvasElement() {
return this.canvas._canvas;
}
/**
* get layer hit canvas
* @method
* @name Konva.Layer#getHitCanvas
*/
getHitCanvas() {
return this.hitCanvas;
}
/**
* get layer canvas context
* @method
* @name Konva.Layer#getContext
*/
getContext() {
return this.getCanvas().getContext();
}
// TODO: deprecate this method
clear(bounds?) {
this.getContext().clear(bounds);
this.getHitCanvas().getContext().clear(bounds);
return this;
}
// extend Node.prototype.setZIndex
setZIndex(index) {
super.setZIndex(index);
var stage = this.getStage();
if (stage && stage.content) {
stage.content.removeChild(this.getNativeCanvasElement());
if (index < stage.children.length - 1) {
stage.content.insertBefore(
this.getNativeCanvasElement(),
stage.children[index + 1].getCanvas()._canvas
);
} else {
stage.content.appendChild(this.getNativeCanvasElement());
}
}
return this;
}
moveToTop() {
Node.prototype.moveToTop.call(this);
var stage = this.getStage();
if (stage && stage.content) {
stage.content.removeChild(this.getNativeCanvasElement());
stage.content.appendChild(this.getNativeCanvasElement());
}
return true;
}
moveUp() {
var moved = Node.prototype.moveUp.call(this);
if (!moved) {
return false;
}
var stage = this.getStage();
if (!stage || !stage.content) {
return false;
}
stage.content.removeChild(this.getNativeCanvasElement());
if (this.index < stage.children.length - 1) {
stage.content.insertBefore(
this.getNativeCanvasElement(),
stage.children[this.index + 1].getCanvas()._canvas
);
} else {
stage.content.appendChild(this.getNativeCanvasElement());
}
return true;
}
// extend Node.prototype.moveDown
moveDown() {
if (Node.prototype.moveDown.call(this)) {
var stage = this.getStage();
if (stage) {
var children = stage.children;
if (stage.content) {
stage.content.removeChild(this.getNativeCanvasElement());
stage.content.insertBefore(
this.getNativeCanvasElement(),
children[this.index + 1].getCanvas()._canvas
);
}
}
return true;
}
return false;
}
// extend Node.prototype.moveToBottom
moveToBottom() {
if (Node.prototype.moveToBottom.call(this)) {
var stage = this.getStage();
if (stage) {
var children = stage.children;
if (stage.content) {
stage.content.removeChild(this.getNativeCanvasElement());
stage.content.insertBefore(
this.getNativeCanvasElement(),
children[1].getCanvas()._canvas
);
}
}
return true;
}
return false;
}
getLayer() {
return this;
}
remove() {
var _canvas = this.getNativeCanvasElement();
Node.prototype.remove.call(this);
if (_canvas && _canvas.parentNode && Util._isInDocument(_canvas)) {
_canvas.parentNode.removeChild(_canvas);
}
return this;
}
getStage() {
return this.parent as Stage;
}
setSize({ width, height }) {
this.canvas.setSize(width, height);
this.hitCanvas.setSize(width, height);
this._setSmoothEnabled();
return this;
}
_validateAdd(child) {
var type = child.getType();
if (type !== 'Group' && type !== 'Shape') {
Util.throw('You may only add groups and shapes to a layer.');
}
}
_toKonvaCanvas(config) {
config = config || {};
config.width = config.width || this.getWidth();
config.height = config.height || this.getHeight();
config.x = config.x !== undefined ? config.x : this.x();
config.y = config.y !== undefined ? config.y : this.y();
return Node.prototype._toKonvaCanvas.call(this, config);
}
_checkVisibility() {
const visible = this.visible();
if (visible) {
this.canvas._canvas.style.display = 'block';
} else {
this.canvas._canvas.style.display = 'none';
}
}
_setSmoothEnabled() {
this.getContext()._context.imageSmoothingEnabled =
this.imageSmoothingEnabled();
}
/**
* get/set width of layer. getter return width of stage. setter doing nothing.
* if you want change width use `stage.width(value);`
* @name Konva.Layer#width
* @method
* @returns {Number}
* @example
* var width = layer.width();
*/
getWidth() {
if (this.parent) {
return this.parent.width();
}
}
setWidth() {
Util.warn(
'Can not change width of layer. Use "stage.width(value)" function instead.'
);
}
/**
* get/set height of layer.getter return height of stage. setter doing nothing.
* if you want change height use `stage.height(value);`
* @name Konva.Layer#height
* @method
* @returns {Number}
* @example
* var height = layer.height();
*/
getHeight() {
if (this.parent) {
return this.parent.height();
}
}
setHeight() {
Util.warn(
'Can not change height of layer. Use "stage.height(value)" function instead.'
);
}
/**
* batch draw. this function will not do immediate draw
* but it will schedule drawing to next tick (requestAnimFrame)
* @method
* @name Konva.Layer#batchDraw
* @return {Konva.Layer} this
*/
batchDraw() {
if (!this._waitingForDraw) {
this._waitingForDraw = true;
Util.requestAnimFrame(() => {
this.draw();
this._waitingForDraw = false;
});
}
return this;
}
/**
* get visible intersection shape. This is the preferred
* method for determining if a point intersects a shape or not
* also you may pass optional selector parameter to return ancestor of intersected shape
* @method
* @name Konva.Layer#getIntersection
* @param {Object} pos
* @param {Number} pos.x
* @param {Number} pos.y
* @returns {Konva.Node}
* @example
* var shape = layer.getIntersection({x: 50, y: 50});
*/
getIntersection(pos: Vector2d) {
if (!this.isListening() || !this.isVisible()) {
return null;
}
// in some cases antialiased area may be bigger than 1px
// it is possible if we will cache node, then scale it a lot
var spiralSearchDistance = 1;
var continueSearch = false;
while (true) {
for (let i = 0; i < INTERSECTION_OFFSETS_LEN; i++) {
const intersectionOffset = INTERSECTION_OFFSETS[i];
const obj = this._getIntersection({
x: pos.x + intersectionOffset.x * spiralSearchDistance,
y: pos.y + intersectionOffset.y * spiralSearchDistance,
});
const shape = obj.shape;
if (shape) {
return shape;
}
// we should continue search if we found antialiased pixel
// that means our node somewhere very close
continueSearch = !!obj.antialiased;
// stop search if found empty pixel
if (!obj.antialiased) {
break;
}
}
// if no shape, and no antialiased pixel, we should end searching
if (continueSearch) {
spiralSearchDistance += 1;
} else {
return null;
}
}
}
_getIntersection(pos: Vector2d): { shape?: Shape; antialiased?: boolean } {
const ratio = this.hitCanvas.pixelRatio;
const p = this.hitCanvas.context.getImageData(
Math.round(pos.x * ratio),
Math.round(pos.y * ratio),
1,
1
).data;
const p3 = p[3];
// fully opaque pixel
if (p3 === 255) {
const colorKey = Util._rgbToHex(p[0], p[1], p[2]);
const shape = shapes[HASH + colorKey];
if (shape) {
return {
shape: shape,
};
}
return {
antialiased: true,
};
} else if (p3 > 0) {
// antialiased pixel
return {
antialiased: true,
};
}
// empty pixel
return {};
}
drawScene(can?: SceneCanvas, top?: Node) {
var layer = this.getLayer(),
canvas = can || (layer && layer.getCanvas());
this._fire(BEFORE_DRAW, {
node: this,
});
if (this.clearBeforeDraw()) {
canvas.getContext().clear();
}
Container.prototype.drawScene.call(this, canvas, top);
this._fire(DRAW, {
node: this,
});
return this;
}
drawHit(can?: HitCanvas, top?: Node) {
var layer = this.getLayer(),
canvas = can || (layer && layer.hitCanvas);
if (layer && layer.clearBeforeDraw()) {
layer.getHitCanvas().getContext().clear();
}
Container.prototype.drawHit.call(this, canvas, top);
return this;
}
/**
* enable hit graph. **DEPRECATED!** Use `layer.listening(true)` instead.
* @name Konva.Layer#enableHitGraph
* @method
* @returns {Layer}
*/
enableHitGraph() {
this.hitGraphEnabled(true);
return this;
}
/**
* disable hit graph. **DEPRECATED!** Use `layer.listening(false)` instead.
* @name Konva.Layer#disableHitGraph
* @method
* @returns {Layer}
*/
disableHitGraph() {
this.hitGraphEnabled(false);
return this;
}
setHitGraphEnabled(val) {
Util.warn(
'hitGraphEnabled method is deprecated. Please use layer.listening() instead.'
);
this.listening(val);
}
getHitGraphEnabled(val) {
Util.warn(
'hitGraphEnabled method is deprecated. Please use layer.listening() instead.'
);
return this.listening();
}
/**
* Show or hide hit canvas over the stage. May be useful for debugging custom hitFunc
* @name Konva.Layer#toggleHitCanvas
* @method
*/
toggleHitCanvas() {
if (!this.parent || !this.parent['content']) {
return;
}
var parent = this.parent as any;
var added = !!this.hitCanvas._canvas.parentNode;
if (added) {
parent.content.removeChild(this.hitCanvas._canvas);
} else {
parent.content.appendChild(this.hitCanvas._canvas);
}
}
destroy(): this {
Util.releaseCanvas(this.getNativeCanvasElement(), this.getHitCanvas()._canvas);
return super.destroy();
}
hitGraphEnabled: GetSet<boolean, this>;
clearBeforeDraw: GetSet<boolean, this>;
imageSmoothingEnabled: GetSet<boolean, this>;
}
Layer.prototype.nodeType = 'Layer';
_registerNode(Layer);
/**
* get/set imageSmoothingEnabled flag
* For more info see https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/imageSmoothingEnabled
* @name Konva.Layer#imageSmoothingEnabled
* @method
* @param {Boolean} imageSmoothingEnabled
* @returns {Boolean}
* @example
* // get imageSmoothingEnabled flag
* var imageSmoothingEnabled = layer.imageSmoothingEnabled();
*
* layer.imageSmoothingEnabled(false);
*
* layer.imageSmoothingEnabled(true);
*/
Factory.addGetterSetter(Layer, 'imageSmoothingEnabled', true);
/**
* get/set clearBeforeDraw flag which determines if the layer is cleared or not
* before drawing
* @name Konva.Layer#clearBeforeDraw
* @method
* @param {Boolean} clearBeforeDraw
* @returns {Boolean}
* @example
* // get clearBeforeDraw flag
* var clearBeforeDraw = layer.clearBeforeDraw();
*
* // disable clear before draw
* layer.clearBeforeDraw(false);
*
* // enable clear before draw
* layer.clearBeforeDraw(true);
*/
Factory.addGetterSetter(Layer, 'clearBeforeDraw', true);
Factory.addGetterSetter(Layer, 'hitGraphEnabled', true, getBooleanValidator());
/**
* get/set hitGraphEnabled flag. **DEPRECATED!** Use `layer.listening(false)` instead.
* Disabling the hit graph will greatly increase
* draw performance because the hit graph will not be redrawn each time the layer is
* drawn. This, however, also disables mouse/touch event detection
* @name Konva.Layer#hitGraphEnabled
* @method
* @param {Boolean} enabled
* @returns {Boolean}
* @example
* // get hitGraphEnabled flag
* var hitGraphEnabled = layer.hitGraphEnabled();
*
* // disable hit graph
* layer.hitGraphEnabled(false);
*
* // enable hit graph
* layer.hitGraphEnabled(true);
*/