konva 10.9.0 → 10.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/README.md +22 -10
  2. package/konva.js +18996 -18838
  3. package/konva.min.js +50 -50
  4. package/lib/Animation.js +3 -3
  5. package/lib/Canvas.js +11 -3
  6. package/lib/Container.js +3 -3
  7. package/lib/Context.d.ts +2 -2
  8. package/lib/Context.js +17 -20
  9. package/lib/Core.js +2 -2
  10. package/lib/DragAndDrop.js +1 -1
  11. package/lib/Factory.js +2 -2
  12. package/lib/FastLayer.js +3 -3
  13. package/lib/Global.d.ts +0 -1
  14. package/lib/Global.js +13 -7
  15. package/lib/Group.js +5 -5
  16. package/lib/Layer.d.ts +1 -1
  17. package/lib/Layer.js +8 -8
  18. package/lib/Node.d.ts +2 -0
  19. package/lib/Node.js +76 -76
  20. package/lib/PointerEvents.js +1 -1
  21. package/lib/Shape.d.ts +5 -1
  22. package/lib/Shape.js +37 -43
  23. package/lib/Stage.js +8 -8
  24. package/lib/Tween.js +4 -4
  25. package/lib/Util.d.ts +67 -3
  26. package/lib/Util.js +124 -41
  27. package/lib/Validators.js +2 -2
  28. package/lib/_CoreInternals.d.ts +15 -11
  29. package/lib/_CoreInternals.js +16 -14
  30. package/lib/_FullInternals.d.ts +14 -10
  31. package/lib/_FullInternals.js +38 -38
  32. package/lib/canvas-backend.js +6 -15
  33. package/lib/filters/Blur.js +27 -3
  34. package/lib/filters/Brighten.js +3 -3
  35. package/lib/filters/Brightness.js +9 -3
  36. package/lib/filters/Contrast.js +9 -5
  37. package/lib/filters/Emboss.js +17 -9
  38. package/lib/filters/Enhance.js +3 -3
  39. package/lib/filters/HSL.js +3 -3
  40. package/lib/filters/HSV.js +3 -3
  41. package/lib/filters/Kaleidoscope.js +3 -3
  42. package/lib/filters/Mask.js +3 -3
  43. package/lib/filters/Noise.js +3 -3
  44. package/lib/filters/Pixelate.js +4 -4
  45. package/lib/filters/Posterize.js +3 -3
  46. package/lib/filters/RGB.js +3 -3
  47. package/lib/filters/RGBA.js +3 -3
  48. package/lib/filters/Threshold.js +3 -3
  49. package/lib/index.js +1 -1
  50. package/lib/napi-backend.d.ts +2 -0
  51. package/lib/napi-backend.js +15 -0
  52. package/lib/shapes/Arc.js +5 -5
  53. package/lib/shapes/Arrow.js +5 -5
  54. package/lib/shapes/Circle.js +4 -4
  55. package/lib/shapes/Ellipse.js +4 -4
  56. package/lib/shapes/Image.js +5 -5
  57. package/lib/shapes/Label.js +7 -7
  58. package/lib/shapes/Line.js +6 -6
  59. package/lib/shapes/Path.js +5 -5
  60. package/lib/shapes/Rect.js +5 -5
  61. package/lib/shapes/RegularPolygon.js +5 -5
  62. package/lib/shapes/Ring.js +4 -4
  63. package/lib/shapes/Sprite.js +5 -5
  64. package/lib/shapes/Star.js +4 -4
  65. package/lib/shapes/Text.d.ts +0 -1
  66. package/lib/shapes/Text.js +36 -34
  67. package/lib/shapes/TextPath.d.ts +3 -2
  68. package/lib/shapes/TextPath.js +71 -46
  69. package/lib/shapes/Transformer.js +12 -11
  70. package/lib/shapes/Wedge.js +5 -5
  71. package/lib/skia-backend.js +17 -25
  72. package/package.json +31 -34
package/lib/Shape.js CHANGED
@@ -1,10 +1,10 @@
1
- import { Konva } from "./Global.js";
2
- import { Transform, Util } from "./Util.js";
3
- import { Factory } from "./Factory.js";
4
- import { Node } from "./Node.js";
5
- import { getNumberValidator, getNumberOrAutoValidator, getStringValidator, getBooleanValidator, getStringOrGradientValidator, } from "./Validators.js";
6
- import { _boundedShapes, _registerNode } from "./Global.js";
7
- import * as PointerEvents from "./PointerEvents.js";
1
+ import { Konva } from './Global.js';
2
+ import { Transform, Util, getDummyContext } from './Util.js';
3
+ import { Factory } from './Factory.js';
4
+ import { Node } from './Node.js';
5
+ import { getNumberValidator, getNumberOrAutoValidator, getStringValidator, getBooleanValidator, getStringOrGradientValidator, } from './Validators.js';
6
+ import { _boundedShapes, _registerNode } from './Global.js';
7
+ import * as PointerEvents from './PointerEvents.js';
8
8
  const HAS_SHADOW = 'hasShadow';
9
9
  const HAS_FILL = 'hasFill';
10
10
  const HAS_STROKE = 'hasStroke';
@@ -12,14 +12,6 @@ const SHADOW_RGBA = 'shadowRGBA';
12
12
  const patternImage = 'patternImage';
13
13
  const linearGradient = 'linearGradient';
14
14
  const radialGradient = 'radialGradient';
15
- let dummyContext;
16
- function getDummyContext() {
17
- if (dummyContext) {
18
- return dummyContext;
19
- }
20
- dummyContext = Util.createCanvasElement().getContext('2d');
21
- return dummyContext;
22
- }
23
15
  export const shapes = {};
24
16
  function _fillFunc(context) {
25
17
  const fillRule = this.attrs.fillRule;
@@ -138,44 +130,43 @@ export class Shape extends Node {
138
130
  this.shadowOffsetX() ||
139
131
  this.shadowOffsetY()));
140
132
  }
133
+ _toStyleSpace(point) {
134
+ return this._styleTransform ? this._styleTransform.point(point) : point;
135
+ }
136
+ // Unlike a gradient, a pattern can be moved after it is created, so one
137
+ // pattern serves every space it is drawn in (see _styleTransform).
141
138
  _getFillPattern() {
142
- return this._getCache(patternImage, this.__getFillPattern);
139
+ const pattern = this._getCache(patternImage, this._createFillPattern);
140
+ return pattern && this._setFillPatternTransform(pattern);
143
141
  }
144
- __getFillPattern() {
142
+ _createFillPattern() {
145
143
  if (this.fillPatternImage()) {
146
- const ctx = getDummyContext();
147
- const pattern = ctx.createPattern(this.fillPatternImage(), this.fillPatternRepeat() || 'repeat');
148
- if (pattern && pattern.setTransform) {
149
- const tr = new Transform();
150
- tr.translate(this.fillPatternX(), this.fillPatternY());
151
- tr.rotate(Konva.getAngle(this.fillPatternRotation()));
152
- tr.scale(this.fillPatternScaleX(), this.fillPatternScaleY());
153
- tr.translate(-1 * this.fillPatternOffsetX(), -1 * this.fillPatternOffsetY());
154
- const m = tr.getMatrix();
155
- const matrix = typeof DOMMatrix === 'undefined'
156
- ? {
157
- a: m[0], // Horizontal scaling. A value of 1 results in no scaling.
158
- b: m[1], // Vertical skewing.
159
- c: m[2], // Horizontal skewing.
160
- d: m[3],
161
- e: m[4], // Horizontal translation (moving).
162
- f: m[5], // Vertical translation (moving).
163
- }
164
- : new DOMMatrix(m);
165
- pattern.setTransform(matrix);
166
- }
167
- return pattern;
144
+ return getDummyContext().createPattern(this.fillPatternImage(), this.fillPatternRepeat() || 'repeat');
145
+ }
146
+ }
147
+ _setFillPatternTransform(pattern) {
148
+ var _a;
149
+ if (pattern.setTransform) {
150
+ const tr = ((_a = this._styleTransform) === null || _a === void 0 ? void 0 : _a.copy()) || new Transform();
151
+ tr.translate(this.fillPatternX(), this.fillPatternY());
152
+ tr.rotate(Konva.getAngle(this.fillPatternRotation()));
153
+ tr.scale(this.fillPatternScaleX(), this.fillPatternScaleY());
154
+ tr.translate(-1 * this.fillPatternOffsetX(), -1 * this.fillPatternOffsetY());
155
+ pattern.setTransform(Util.createDOMMatrix(tr.getMatrix()));
168
156
  }
157
+ return pattern;
169
158
  }
170
159
  _getLinearGradient() {
160
+ if (this._styleTransform)
161
+ return this.__getLinearGradient();
171
162
  return this._getCache(linearGradient, this.__getLinearGradient);
172
163
  }
173
164
  __getLinearGradient() {
174
165
  const colorStops = this.fillLinearGradientColorStops();
175
166
  if (colorStops) {
176
167
  const ctx = getDummyContext();
177
- const start = this.fillLinearGradientStartPoint();
178
- const end = this.fillLinearGradientEndPoint();
168
+ const start = this._toStyleSpace(this.fillLinearGradientStartPoint());
169
+ const end = this._toStyleSpace(this.fillLinearGradientEndPoint());
179
170
  const grd = ctx.createLinearGradient(start.x, start.y, end.x, end.y);
180
171
  // build color stops
181
172
  for (let n = 0; n < colorStops.length; n += 2) {
@@ -185,14 +176,17 @@ export class Shape extends Node {
185
176
  }
186
177
  }
187
178
  _getRadialGradient() {
179
+ if (this._styleTransform)
180
+ return this.__getRadialGradient();
188
181
  return this._getCache(radialGradient, this.__getRadialGradient);
189
182
  }
190
183
  __getRadialGradient() {
191
184
  const colorStops = this.fillRadialGradientColorStops();
192
185
  if (colorStops) {
193
186
  const ctx = getDummyContext();
194
- const start = this.fillRadialGradientStartPoint();
195
- const end = this.fillRadialGradientEndPoint();
187
+ // a rigid transform keeps the radii
188
+ const start = this._toStyleSpace(this.fillRadialGradientStartPoint());
189
+ const end = this._toStyleSpace(this.fillRadialGradientEndPoint());
196
190
  const grd = ctx.createRadialGradient(start.x, start.y, this.fillRadialGradientStartRadius(), end.x, end.y, this.fillRadialGradientEndRadius());
197
191
  // build color stops
198
192
  for (let n = 0; n < colorStops.length; n += 2) {
package/lib/Stage.js CHANGED
@@ -1,11 +1,11 @@
1
- import { Util } from "./Util.js";
2
- import { Factory } from "./Factory.js";
3
- import { Container } from "./Container.js";
4
- import { Konva } from "./Global.js";
5
- import { SceneCanvas, HitCanvas } from "./Canvas.js";
6
- import { DD } from "./DragAndDrop.js";
7
- import { _registerNode } from "./Global.js";
8
- import * as PointerEvents from "./PointerEvents.js";
1
+ import { Util } from './Util.js';
2
+ import { Factory } from './Factory.js';
3
+ import { Container } from './Container.js';
4
+ import { Konva } from './Global.js';
5
+ import { SceneCanvas, HitCanvas } from './Canvas.js';
6
+ import { DD } from './DragAndDrop.js';
7
+ import { _registerNode } from './Global.js';
8
+ import * as PointerEvents from './PointerEvents.js';
9
9
  // CONSTANTS
10
10
  const STAGE = 'Stage', STRING = 'string', PX = 'px', MOUSEOUT = 'mouseout', MOUSELEAVE = 'mouseleave', MOUSEOVER = 'mouseover', MOUSEENTER = 'mouseenter', MOUSEMOVE = 'mousemove', MOUSEDOWN = 'mousedown', MOUSEUP = 'mouseup', POINTERMOVE = 'pointermove', POINTERDOWN = 'pointerdown', POINTERUP = 'pointerup', POINTERCANCEL = 'pointercancel', LOSTPOINTERCAPTURE = 'lostpointercapture', POINTEROUT = 'pointerout', POINTERLEAVE = 'pointerleave', POINTEROVER = 'pointerover', POINTERENTER = 'pointerenter', CONTEXTMENU = 'contextmenu', TOUCHSTART = 'touchstart', TOUCHEND = 'touchend', TOUCHMOVE = 'touchmove', TOUCHCANCEL = 'touchcancel', WHEEL = 'wheel', MAX_LAYERS_NUMBER = 5, EVENTS = [
11
11
  [MOUSEENTER, '_pointerenter'],
package/lib/Tween.js CHANGED
@@ -1,7 +1,7 @@
1
- import { Util } from "./Util.js";
2
- import { Animation } from "./Animation.js";
3
- import { Node } from "./Node.js";
4
- import { Konva } from "./Global.js";
1
+ import { Util } from './Util.js';
2
+ import { Animation } from './Animation.js';
3
+ import { Node } from './Node.js';
4
+ import { Konva } from './Global.js';
5
5
  // every config key that is not an attribute to tween
6
6
  const blacklist = {
7
7
  node: 1,
package/lib/Util.d.ts CHANGED
@@ -130,10 +130,28 @@ export declare const Util: {
130
130
  _isBoolean(obj: any): obj is boolean;
131
131
  isObject(val: any): val is object;
132
132
  isValidSelector(selector: any): boolean;
133
- _sign(number: number): 1 | -1;
133
+ _sign(number: number): -1 | 1;
134
134
  requestAnimFrame(callback: Function, win?: Window | null): void;
135
135
  createCanvasElement(): HTMLCanvasElement;
136
136
  createImageElement(): HTMLImageElement;
137
+ /**
138
+ * Make a DOMMatrix of the canvas library Konva draws with. Without a createDOMMatrix
139
+ * in Konva.setCanvasBackend(), the class comes from the library's own context.
140
+ * @method
141
+ * @memberof Konva.Util
142
+ * @param {Array} [init] the six numbers a, b, c, d, e, f
143
+ * @returns {DOMMatrix}
144
+ */
145
+ createDOMMatrix(init?: number[]): DOMMatrix;
146
+ /**
147
+ * Make a Path2D of the canvas library Konva draws with, for example for a clipFunc.
148
+ * Without a createPath2D in Konva.setCanvasBackend(), it is the global Path2D.
149
+ * @method
150
+ * @memberof Konva.Util
151
+ * @param {String} [path] SVG path data
152
+ * @returns {Path2D}
153
+ */
154
+ createPath2D(path?: string): Path2D;
137
155
  _urlToImage(url: string, callback: Function, onError?: (error: Error) => void): void;
138
156
  _rgbToHex(r: number, g: number, b: number): string;
139
157
  _hexToRgb(hex: string): RGB;
@@ -151,7 +169,7 @@ export declare const Util: {
151
169
  * @memberof Konva.Util
152
170
  * @returns {Boolean}
153
171
  */
154
- isCanvasFarblingActive(): boolean;
172
+ isCanvasFarblingActive: () => boolean;
155
173
  /**
156
174
  * Get a random color for hit detection (snapped to the hit color grid)
157
175
  * @method
@@ -266,11 +284,57 @@ export declare const Util: {
266
284
  _prepareArrayForTween(startArray: any, endArray: any, isClosed: any): number[];
267
285
  _prepareToStringify<T>(obj: any, ancestors?: Set<object>): T;
268
286
  _assign<T, U>(target: T, source: U): T & U;
269
- _getEventType(type: string): "mouse" | "touch" | "pointer";
287
+ _getEventType(type: string): 'mouse' | 'touch' | 'pointer';
270
288
  _getFirstPointerId(evt: any): any;
271
289
  releaseCanvas(...canvases: HTMLCanvasElement[]): void;
272
290
  _cornerRadii(cornerRadius: number | number[], width: number, height: number): [number, number, number, number];
273
291
  drawRoundedRectPath(context: Context, width: number, height: number, cornerRadius: number | number[]): void;
274
292
  drawRoundedPolygonPath(context: Context, points: Vector2d[], sides: number, radius: number, cornerRadius: number | number[]): void;
275
293
  };
294
+ export interface CanvasBackend {
295
+ /** what Konva.getCanvasBackend() reports */
296
+ name: string;
297
+ /** makes a canvas with a 2d context; Konva sets its size */
298
+ createCanvas: () => object;
299
+ /** makes an image that loads from its src; without it Konva can not load images */
300
+ createImage?: () => object;
301
+ /** makes a DOMMatrix; by default its class comes from the canvas */
302
+ createDOMMatrix?: (init?: number[]) => object;
303
+ /** makes a Path2D; by default the global Path2D */
304
+ createPath2D?: (path?: string) => object;
305
+ }
306
+ /**
307
+ * Set the canvas library Konva draws with: Konva makes every canvas and image through it.
308
+ * Applies to everything Konva creates afterwards, including the context it measures text
309
+ * and makes gradients with. Stages and nodes created before keep their canvases, so
310
+ * create them again after a switch.
311
+ * @method
312
+ * @name Konva.setCanvasBackend
313
+ * @param {Object} backend
314
+ * @param {String} backend.name reported by Konva.getCanvasBackend()
315
+ * @param {Function} backend.createCanvas returns a new canvas
316
+ * @param {Function} [backend.createImage] returns a new image
317
+ * @param {Function} [backend.createDOMMatrix] returns a new DOMMatrix, see Konva.Util.createDOMMatrix
318
+ * @param {Function} [backend.createPath2D] returns a new Path2D, see Konva.Util.createPath2D
319
+ * @example
320
+ * import { Canvas, Image } from '@napi-rs/canvas';
321
+ * Konva.setCanvasBackend({
322
+ * name: 'my-napi-rs',
323
+ * createCanvas: () => new Canvas(300, 150),
324
+ * createImage: () => new Image(),
325
+ * });
326
+ */
327
+ export declare function setCanvasBackend(backend: CanvasBackend): void;
328
+ /**
329
+ * The name of the canvas backend Konva draws with: "web" in a browser, "offscreen-canvas" in a
330
+ * Web Worker, the name given to Konva.setCanvasBackend(), "custom" when
331
+ * Konva.Util.createCanvasElement was replaced directly, or null when there is none, as in
332
+ * Node.js before a backend is set.
333
+ * @method
334
+ * @name Konva.getCanvasBackend
335
+ * @returns {String|null}
336
+ */
337
+ export declare function getCanvasBackend(): string | null;
338
+ export declare function _perCanvasBackend<T>(compute: () => T): () => T;
339
+ export declare const getDummyContext: () => CanvasRenderingContext2D;
276
340
  export type AnyString<T> = T | (string & {});
package/lib/Util.js CHANGED
@@ -1,18 +1,5 @@
1
- import { Konva } from "./Global.js";
2
- const NODE_ERROR = `Konva.js unsupported environment.
3
-
4
- Looks like you are trying to use Konva.js in Node.js environment (or in a Web Worker), because "document" object is undefined.
5
-
6
- To use Konva.js in Node.js environment, you need to use the "canvas-backend" or "skia-backend" module.
7
-
8
- bash: npm install canvas
9
- js: import "konva/canvas-backend";
10
-
11
- or
12
-
13
- bash: npm install skia-canvas
14
- js: import "konva/skia-backend";
15
- `;
1
+ import { Konva } from './Global.js';
2
+ const NODE_ERROR = 'Konva needs a canvas outside the browser. Import "konva/canvas-backend", "konva/skia-backend" or "konva/napi-backend", or call Konva.setCanvasBackend().';
16
3
  const ensureBrowser = () => {
17
4
  if (typeof document === 'undefined') {
18
5
  throw new Error(NODE_ERROR);
@@ -282,13 +269,11 @@ export class Transform {
282
269
  result.skewY = 0;
283
270
  }
284
271
  else if (c != 0 || d != 0) {
285
- const s = Math.sqrt(c * c + d * d);
286
- result.rotation =
287
- Math.PI / 2 - (d > 0 ? Math.acos(-c / s) : -Math.acos(c / s));
288
- result.scaleX = delta / s;
289
- result.scaleY = s;
290
- result.skewX = 0;
291
- result.skewY = delta && (a * c + b * d) / delta;
272
+ // a = b = 0: the x axis is collapsed, so scaleX and the skew stay 0 and
273
+ // only the y axis, the scaled unit vector (-sin, cos), carries the
274
+ // rotation. "+ 0" turns the -0 that atan2 gives for a zero angle into 0
275
+ result.rotation = Math.atan2(-c, d) + 0;
276
+ result.scaleY = Math.sqrt(c * c + d * d);
292
277
  }
293
278
  else {
294
279
  // a = b = c = d = 0
@@ -449,8 +434,6 @@ const OBJECT_ARRAY = '[object Array]', OBJECT_NUMBER = '[object Number]', OBJECT
449
434
  yellow: [255, 255, 0],
450
435
  yellowgreen: [154, 205, 50],
451
436
  };
452
- // Cache for canvas farbling detection
453
- let _isCanvasFarblingActive = null;
454
437
  // A stage may be rendered in another window than the one Konva was imported
455
438
  // into, and a window that is not visible gives almost no frames. So frames are
456
439
  // asked from the window of the stage, and the callbacks are kept per window
@@ -590,18 +573,36 @@ export const Util = {
590
573
  },
591
574
  createCanvasElement() {
592
575
  ensureBrowser();
593
- const canvas = document.createElement('canvas');
594
- // on some environments canvas.style is readonly
595
- try {
596
- canvas.style = canvas.style || {};
597
- }
598
- catch (e) { }
599
- return canvas;
576
+ return document.createElement('canvas');
600
577
  },
601
578
  createImageElement() {
602
579
  ensureBrowser();
603
580
  return document.createElement('img');
604
581
  },
582
+ /**
583
+ * Make a DOMMatrix of the canvas library Konva draws with. Without a createDOMMatrix
584
+ * in Konva.setCanvasBackend(), the class comes from the library's own context.
585
+ * @method
586
+ * @memberof Konva.Util
587
+ * @param {Array} [init] the six numbers a, b, c, d, e, f
588
+ * @returns {DOMMatrix}
589
+ */
590
+ createDOMMatrix(init) {
591
+ // node-canvas accepts only its own DOMMatrix, so the global one may not fit
592
+ const Matrix = getDummyContext().getTransform().constructor;
593
+ return new Matrix(init);
594
+ },
595
+ /**
596
+ * Make a Path2D of the canvas library Konva draws with, for example for a clipFunc.
597
+ * Without a createPath2D in Konva.setCanvasBackend(), it is the global Path2D.
598
+ * @method
599
+ * @memberof Konva.Util
600
+ * @param {String} [path] SVG path data
601
+ * @returns {Path2D}
602
+ */
603
+ createPath2D(path) {
604
+ return new Path2D(path);
605
+ },
605
606
  /*
606
607
  * arg can be an image object or image data
607
608
  */
@@ -648,15 +649,15 @@ export const Util = {
648
649
  * @memberof Konva.Util
649
650
  * @returns {Boolean}
650
651
  */
651
- isCanvasFarblingActive() {
652
- if (_isCanvasFarblingActive !== null) {
653
- return _isCanvasFarblingActive;
652
+ isCanvasFarblingActive: _perCanvasBackend(() => {
653
+ let c;
654
+ try {
655
+ c = Util.createCanvasElement();
654
656
  }
655
- if (typeof document === 'undefined') {
656
- _isCanvasFarblingActive = false;
657
+ catch (e) {
658
+ // no canvas to read, e.g. Node.js without a backend
657
659
  return false;
658
660
  }
659
- const c = this.createCanvasElement();
660
661
  c.width = 10;
661
662
  c.height = 10;
662
663
  const ctx = c.getContext('2d', {
@@ -676,10 +677,9 @@ export const Util = {
676
677
  break;
677
678
  }
678
679
  }
679
- _isCanvasFarblingActive = isFarbling;
680
- this.releaseCanvas(c);
681
- return _isCanvasFarblingActive;
682
- },
680
+ Util.releaseCanvas(c);
681
+ return isFarbling;
682
+ }),
683
683
  /**
684
684
  * Get a random color for hit detection (snapped to the hit color grid)
685
685
  * @method
@@ -1194,6 +1194,8 @@ export const Util = {
1194
1194
  else {
1195
1195
  currCornerRadius = i < cornerRadius.length ? cornerRadius[i] : 0;
1196
1196
  }
1197
+ // a negative corner radius would throw in context.arcTo()
1198
+ currCornerRadius = Math.max(currCornerRadius, 0);
1197
1199
  const maxCornerRadius = radius * Math.cos(Math.PI / sides);
1198
1200
  // cornerRadius creates perfect circle at 1/2 radius
1199
1201
  currCornerRadius =
@@ -1218,3 +1220,84 @@ export const Util = {
1218
1220
  }
1219
1221
  },
1220
1222
  };
1223
+ let activeBackend = { name: 'web', createCanvas: Util.createCanvasElement };
1224
+ const { createDOMMatrix, createPath2D } = Util;
1225
+ /**
1226
+ * Set the canvas library Konva draws with: Konva makes every canvas and image through it.
1227
+ * Applies to everything Konva creates afterwards, including the context it measures text
1228
+ * and makes gradients with. Stages and nodes created before keep their canvases, so
1229
+ * create them again after a switch.
1230
+ * @method
1231
+ * @name Konva.setCanvasBackend
1232
+ * @param {Object} backend
1233
+ * @param {String} backend.name reported by Konva.getCanvasBackend()
1234
+ * @param {Function} backend.createCanvas returns a new canvas
1235
+ * @param {Function} [backend.createImage] returns a new image
1236
+ * @param {Function} [backend.createDOMMatrix] returns a new DOMMatrix, see Konva.Util.createDOMMatrix
1237
+ * @param {Function} [backend.createPath2D] returns a new Path2D, see Konva.Util.createPath2D
1238
+ * @example
1239
+ * import { Canvas, Image } from '@napi-rs/canvas';
1240
+ * Konva.setCanvasBackend({
1241
+ * name: 'my-napi-rs',
1242
+ * createCanvas: () => new Canvas(300, 150),
1243
+ * createImage: () => new Image(),
1244
+ * });
1245
+ */
1246
+ export function setCanvasBackend(backend) {
1247
+ var _a, _b;
1248
+ const { name, createCanvas, createImage } = backend;
1249
+ Util.createCanvasElement = createCanvas;
1250
+ Util.createDOMMatrix = ((_a = backend.createDOMMatrix) !== null && _a !== void 0 ? _a : createDOMMatrix);
1251
+ Util.createPath2D = ((_b = backend.createPath2D) !== null && _b !== void 0 ? _b : createPath2D);
1252
+ Util.createImageElement = createImage
1253
+ ? createImage
1254
+ : () => {
1255
+ throw new Error(`Konva: the "${name}" canvas backend has no createImage(), so it can not load images.`);
1256
+ };
1257
+ activeBackend = { name, createCanvas: Util.createCanvasElement };
1258
+ }
1259
+ /**
1260
+ * The name of the canvas backend Konva draws with: "web" in a browser, "offscreen-canvas" in a
1261
+ * Web Worker, the name given to Konva.setCanvasBackend(), "custom" when
1262
+ * Konva.Util.createCanvasElement was replaced directly, or null when there is none, as in
1263
+ * Node.js before a backend is set.
1264
+ * @method
1265
+ * @name Konva.getCanvasBackend
1266
+ * @returns {String|null}
1267
+ */
1268
+ export function getCanvasBackend() {
1269
+ if (Util.createCanvasElement !== activeBackend.createCanvas) {
1270
+ return 'custom';
1271
+ }
1272
+ // checked on each call: a document can appear after Konva loads (jsdom)
1273
+ return activeBackend.name === 'web' && typeof document === 'undefined'
1274
+ ? null
1275
+ : activeBackend.name;
1276
+ }
1277
+ // a Web Worker has no document, but it has OffscreenCanvas
1278
+ if (typeof document === 'undefined' && typeof OffscreenCanvas !== 'undefined') {
1279
+ setCanvasBackend({
1280
+ name: 'offscreen-canvas',
1281
+ createCanvas: () => new OffscreenCanvas(300, 150),
1282
+ createImage: () => {
1283
+ throw new Error('Konva: a Web Worker has no image element. Load the image with createImageBitmap() and pass the ImageBitmap to Konva.Image.');
1284
+ },
1285
+ });
1286
+ }
1287
+ // A value Konva computes from a canvas, such as a feature check, belongs to
1288
+ // the library that made the canvas. It is recomputed when the canvas factory
1289
+ // changes, by setCanvasBackend() or by assigning Util.createCanvasElement
1290
+ export function _perCanvasBackend(compute) {
1291
+ let factory;
1292
+ let value;
1293
+ return () => {
1294
+ if (factory !== Util.createCanvasElement) {
1295
+ value = compute();
1296
+ factory = Util.createCanvasElement;
1297
+ }
1298
+ return value;
1299
+ };
1300
+ }
1301
+ // The context Konva measures text and makes gradients and patterns with. A
1302
+ // gradient from one canvas library is ignored by the context of another
1303
+ export const getDummyContext = _perCanvasBackend(() => Util.createCanvasElement().getContext('2d'));
package/lib/Validators.js CHANGED
@@ -1,5 +1,5 @@
1
- import { Konva } from "./Global.js";
2
- import { TypedArray, Util } from "./Util.js";
1
+ import { Konva } from './Global.js';
2
+ import { TypedArray, Util } from './Util.js';
3
3
  function _formatValue(val) {
4
4
  if (Util._isString(val)) {
5
5
  return '"' + val + '"';
@@ -1,4 +1,4 @@
1
- import { Transform } from './Util.ts';
1
+ import { Transform, setCanvasBackend, getCanvasBackend } from './Util.ts';
2
2
  import { Node } from './Node.ts';
3
3
  import { Container } from './Container.ts';
4
4
  import { Stage } from './Stage.ts';
@@ -22,7 +22,6 @@ export declare const Konva: {
22
22
  autoDrawEnabled: boolean;
23
23
  hitOnDragEnabled: boolean;
24
24
  capturePointerEventsEnabled: boolean;
25
- _renderBackend: string;
26
25
  legacyTextRendering: boolean;
27
26
  pixelRatio: number;
28
27
  dragDistance: number;
@@ -62,6 +61,8 @@ export declare const Konva: {
62
61
  * }
63
62
  */
64
63
  beginUpdateBatch: typeof Node._beginUpdateBatch;
64
+ setCanvasBackend: typeof setCanvasBackend;
65
+ getCanvasBackend: typeof getCanvasBackend;
65
66
  Util: {
66
67
  _isElement(obj: any): obj is Element;
67
68
  _isFunction(obj: any): boolean;
@@ -72,15 +73,17 @@ export declare const Konva: {
72
73
  _isBoolean(obj: any): obj is boolean;
73
74
  isObject(val: any): val is object;
74
75
  isValidSelector(selector: any): boolean;
75
- _sign(number: number): 1 | -1;
76
+ _sign(number: number): -1 | 1;
76
77
  requestAnimFrame(callback: Function, win?: Window | null): void;
77
78
  createCanvasElement(): HTMLCanvasElement;
78
79
  createImageElement(): HTMLImageElement;
80
+ createDOMMatrix(init?: number[]): DOMMatrix;
81
+ createPath2D(path?: string): Path2D;
79
82
  _urlToImage(url: string, callback: Function, onError?: (error: Error) => void): void;
80
83
  _rgbToHex(r: number, g: number, b: number): string;
81
84
  _hexToRgb(hex: string): import("./types.ts").RGB;
82
85
  getRandomColor(): string;
83
- isCanvasFarblingActive(): boolean;
86
+ isCanvasFarblingActive: () => boolean;
84
87
  getHitColor(): string;
85
88
  getHitColorKey(r: number, g: number, b: number): string;
86
89
  getSnappedHexColor(hex: string): string;
@@ -153,7 +156,7 @@ export declare const Konva: {
153
156
  _prepareArrayForTween(startArray: any, endArray: any, isClosed: any): number[];
154
157
  _prepareToStringify<T>(obj: any, ancestors?: Set<object>): T;
155
158
  _assign<T, U>(target: T, source: U): T & U;
156
- _getEventType(type: string): "mouse" | "touch" | "pointer";
159
+ _getEventType(type: string): 'mouse' | 'touch' | 'pointer';
157
160
  _getFirstPointerId(evt: any): any;
158
161
  releaseCanvas(...canvases: HTMLCanvasElement[]): void;
159
162
  _cornerRadii(cornerRadius: number | number[], width: number, height: number): [number, number, number, number];
@@ -176,10 +179,10 @@ export declare const Konva: {
176
179
  startPointerPos: import("./types.ts").Vector2d;
177
180
  offset: import("./types.ts").Vector2d;
178
181
  pointerId?: number;
179
- pointerEventType?: Stage["_pointerEventType"];
182
+ pointerEventType?: Stage['_pointerEventType'];
180
183
  lastPos?: import("./types.ts").Vector2d;
181
184
  startEvent?: any;
182
- dragStatus: "ready" | "dragging" | "stopped";
185
+ dragStatus: 'ready' | 'dragging' | 'stopped';
183
186
  }>;
184
187
  _listenToWindow(win: Window): void;
185
188
  _batchEvents(callback: () => void, win?: Window): void;
@@ -189,20 +192,20 @@ export declare const Konva: {
189
192
  startPointerPos: import("./types.ts").Vector2d;
190
193
  offset: import("./types.ts").Vector2d;
191
194
  pointerId?: number;
192
- pointerEventType?: Stage["_pointerEventType"];
195
+ pointerEventType?: Stage['_pointerEventType'];
193
196
  lastPos?: import("./types.ts").Vector2d;
194
197
  startEvent?: any;
195
- dragStatus: "ready" | "dragging" | "stopped";
198
+ dragStatus: 'ready' | 'dragging' | 'stopped';
196
199
  }): void;
197
200
  _endDragAfter(evt: any, only?: {
198
201
  node: Node;
199
202
  startPointerPos: import("./types.ts").Vector2d;
200
203
  offset: import("./types.ts").Vector2d;
201
204
  pointerId?: number;
202
- pointerEventType?: Stage["_pointerEventType"];
205
+ pointerEventType?: Stage['_pointerEventType'];
203
206
  lastPos?: import("./types.ts").Vector2d;
204
207
  startEvent?: any;
205
- dragStatus: "ready" | "dragging" | "stopped";
208
+ dragStatus: 'ready' | 'dragging' | 'stopped';
206
209
  }): void;
207
210
  };
208
211
  Shape: typeof Shape;
@@ -234,6 +237,7 @@ export declare const Konva: {
234
237
  };
235
238
  export declare namespace Konva {
236
239
  type Vector2d = import('./types.ts').Vector2d;
240
+ type CanvasBackend = import('./Util.ts').CanvasBackend;
237
241
  type IRect = import('./types.ts').IRect;
238
242
  type GetSet<Type, This> = import('./types.ts').GetSet<Type, This>;
239
243
  type Filter = import('./Node.ts').Filter;
@@ -1,18 +1,18 @@
1
1
  // what is core parts of Konva?
2
- import { Konva as Global } from "./Global.js";
3
- import { Util, Transform } from "./Util.js";
4
- import { Node } from "./Node.js";
5
- import { Container } from "./Container.js";
6
- import { Stage, stages } from "./Stage.js";
7
- import { Layer } from "./Layer.js";
8
- import { FastLayer } from "./FastLayer.js";
9
- import { Group } from "./Group.js";
10
- import { DD } from "./DragAndDrop.js";
11
- import { Shape, shapes } from "./Shape.js";
12
- import { Animation } from "./Animation.js";
13
- import { Tween, Easings } from "./Tween.js";
14
- import { Context } from "./Context.js";
15
- import { Canvas } from "./Canvas.js";
2
+ import { Konva as Global } from './Global.js';
3
+ import { Util, Transform, setCanvasBackend, getCanvasBackend } from './Util.js';
4
+ import { Node } from './Node.js';
5
+ import { Container } from './Container.js';
6
+ import { Stage, stages } from './Stage.js';
7
+ import { Layer } from './Layer.js';
8
+ import { FastLayer } from './FastLayer.js';
9
+ import { Group } from './Group.js';
10
+ import { DD } from './DragAndDrop.js';
11
+ import { Shape, shapes } from './Shape.js';
12
+ import { Animation } from './Animation.js';
13
+ import { Tween, Easings } from './Tween.js';
14
+ import { Context } from './Context.js';
15
+ import { Canvas } from './Canvas.js';
16
16
  export const Konva = Util._assign(Global, {
17
17
  /**
18
18
  * Defer automatic Konva.Transformer updates across many synchronous node changes
@@ -40,6 +40,8 @@ export const Konva = Util._assign(Global, {
40
40
  * }
41
41
  */
42
42
  beginUpdateBatch: Node._beginUpdateBatch,
43
+ setCanvasBackend,
44
+ getCanvasBackend,
43
45
  Util,
44
46
  Transform,
45
47
  Node,