diff --git a/konva.js b/konva.js index bace17e2..2e67c917 100644 --- a/konva.js +++ b/konva.js @@ -8,7 +8,7 @@ * Konva JavaScript Framework v7.2.5 * http://konvajs.org/ * Licensed under the MIT - * Date: Wed May 05 2021 + * Date: Sun May 09 2021 * * Original work Copyright (C) 2011 - 2013 by Eric Rowell (KineticJS) * Modified work Copyright (C) 2014 - present by Anton Lavrenov (Konva) @@ -43,7 +43,7 @@ return Konva$2.angleDeg ? angle * PI_OVER_180 : angle; }, enableTrace: false, - _pointerEventsEnabled: false, + pointerEventsEnabled: true, /** * Should Konva automatically update canvas on any changes. Default is true. * @property autoDrawEnabled @@ -70,17 +70,20 @@ * The case: we touchstart on div1, then touchmove out of that element into another element div2. * DOM will continue trigger touchmove events on div1 (not div2). Because events are "captured" into initial target. * By default Konva do not do that and will trigger touchmove on another element, while pointer is moving. - * @property captureTouchEventsEnabled + * @property capturePointerEventsEnabled * @default false - * @name captureTouchEventsEnabled + * @name capturePointerEventsEnabled * @memberof Konva * @example - * Konva.captureTouchEventsEnabled = true; + * Konva.capturePointerEventsEnabled = true; */ - captureTouchEventsEnabled: false, - // TODO: move that to stage? - listenClickTap: false, - inDblClickWindow: false, + capturePointerEventsEnabled: false, + _mouseListenClick: false, + _touchListenClick: false, + _pointerListenClick: false, + _mouseInDblClickWindow: false, + _touchInDblClickWindow: false, + _pointerInDblClickWindow: false, /** * Global pixel ratio configuration. KonvaJS automatically detect pixel ratio of current device. * But you may override such property, if you want to use your value. Set this value before any components initializations. @@ -422,7 +425,7 @@ } } // CONSTANTS - var OBJECT_ARRAY = '[object Array]', OBJECT_NUMBER = '[object Number]', OBJECT_STRING = '[object String]', OBJECT_BOOLEAN = '[object Boolean]', PI_OVER_DEG180 = Math.PI / 180, DEG180_OVER_PI = 180 / Math.PI, HASH$1 = '#', EMPTY_STRING$2 = '', ZERO = '0', KONVA_WARNING = 'Konva warning: ', KONVA_ERROR = 'Konva error: ', RGB_PAREN = 'rgb(', COLORS = { + var OBJECT_ARRAY = '[object Array]', OBJECT_NUMBER = '[object Number]', OBJECT_STRING = '[object String]', OBJECT_BOOLEAN = '[object Boolean]', PI_OVER_DEG180 = Math.PI / 180, DEG180_OVER_PI = 180 / Math.PI, HASH$1 = '#', EMPTY_STRING$1 = '', ZERO = '0', KONVA_WARNING = 'Konva warning: ', KONVA_ERROR = 'Konva error: ', RGB_PAREN = 'rgb(', COLORS = { aliceblue: [240, 248, 255], antiquewhite: [250, 235, 215], aqua: [0, 255, 255], @@ -573,6 +576,10 @@ yellow: [255, 255, 0], yellowgreen: [154, 205, 5], }, RGB_REGEX = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/, animQueue = []; + const req = (typeof requestAnimationFrame !== 'undefined' && requestAnimationFrame) || + function (f) { + setTimeout(f, 60); + }; /** * @namespace Util * @memberof Konva @@ -632,10 +639,6 @@ }, requestAnimFrame(callback) { animQueue.push(callback); - const req = (typeof requestAnimationFrame !== 'undefined' && requestAnimationFrame) || - function (f) { - setTimeout(f, 60); - }; if (animQueue.length === 1) { req(function () { const queue = animQueue; @@ -666,20 +669,6 @@ } return false; }, - _simplifyArray(arr) { - var retArr = [], len = arr.length, util = Util, n, val; - for (n = 0; n < len; n++) { - val = arr[n]; - if (util._isNumber(val)) { - val = Math.round(val * 1000) / 1000; - } - else if (!util._isString(val)) { - val = val + ''; - } - retArr.push(val); - } - return retArr; - }, /* * arg can be an image object or image data */ @@ -695,7 +684,7 @@ return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); }, _hexToRgb(hex) { - hex = hex.replace(HASH$1, EMPTY_STRING$2); + hex = hex.replace(HASH$1, EMPTY_STRING$1); var bigint = parseInt(hex, 16); return { r: (bigint >> 16) & 255, @@ -717,14 +706,6 @@ } return HASH$1 + randColor; }, - get(val, def) { - if (val === undefined) { - return def; - } - else { - return val; - } - }, /** * get RGB components of a color * @method @@ -933,14 +914,22 @@ cloneArray(arr) { return arr.slice(0); }, - _degToRad(deg) { + degToRad(deg) { return deg * PI_OVER_DEG180; }, - _radToDeg(rad) { + radToDeg(rad) { return rad * DEG180_OVER_PI; }, + _degToRad(deg) { + Util.warn('Util._degToRad is removed. Please use public Util.degToRad instead.'); + return Util._degToRad(deg); + }, + _radToDeg(rad) { + Util.warn('Util._radToDeg is removed. Please use public Util.radToDeg instead.'); + return Util._radToDeg(rad); + }, _getRotation(radians) { - return Konva$2.angleDeg ? Util._radToDeg(radians) : radians; + return Konva$2.angleDeg ? Util.radToDeg(radians) : radians; }, _capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); @@ -957,42 +946,6 @@ } console.warn(KONVA_WARNING + str); }, - extend(child, parent) { - function Ctor() { - this.constructor = child; - } - Ctor.prototype = parent.prototype; - var oldProto = child.prototype; - child.prototype = new Ctor(); - for (var key in oldProto) { - if (oldProto.hasOwnProperty(key)) { - child.prototype[key] = oldProto[key]; - } - } - child.__super__ = parent.prototype; - // create reference to parent - child.super = parent; - }, - _getControlPoints(x0, y0, x1, y1, x2, y2, t) { - var d01 = Math.sqrt(Math.pow(x1 - x0, 2) + Math.pow(y1 - y0, 2)), d12 = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)), fa = (t * d01) / (d01 + d12), fb = (t * d12) / (d01 + d12), p1x = x1 - fa * (x2 - x0), p1y = y1 - fa * (y2 - y0), p2x = x1 + fb * (x2 - x0), p2y = y1 + fb * (y2 - y0); - return [p1x, p1y, p2x, p2y]; - }, - _expandPoints(p, tension) { - var len = p.length, allPoints = [], n, cp; - for (n = 2; n < len - 2; n += 2) { - cp = Util._getControlPoints(p[n - 2], p[n - 1], p[n], p[n + 1], p[n + 2], p[n + 3], tension); - if (isNaN(cp[0])) { - continue; - } - allPoints.push(cp[0]); - allPoints.push(cp[1]); - allPoints.push(p[n]); - allPoints.push(p[n + 1]); - allPoints.push(cp[2]); - allPoints.push(cp[3]); - } - return allPoints; - }, each(obj, func) { for (var key in obj) { func(key, obj[key]); @@ -1391,6 +1344,20 @@ }, }; + function simplifyArray(arr) { + var retArr = [], len = arr.length, util = Util, n, val; + for (n = 0; n < len; n++) { + val = arr[n]; + if (util._isNumber(val)) { + val = Math.round(val * 1000) / 1000; + } + else if (!util._isString(val)) { + val = val + ''; + } + retArr.push(val); + } + return retArr; + } var COMMA = ',', OPEN_PAREN = '(', CLOSE_PAREN = ')', OPEN_PAREN_BRACKET = '([', CLOSE_BRACKET_PAREN = '])', SEMICOLON = ';', DOUBLE_PAREN = '()', // EMPTY_STRING = '', EQUALS = '=', @@ -1727,6 +1694,7 @@ * @name Konva.Context#drawImage */ drawImage(a0, a1, a2, a3, a4, a5, a6, a7, a8) { + // this._context.drawImage(...arguments); var a = arguments, _context = this._context; if (a.length === 3) { _context.drawImage(a0, a1, a2); @@ -1759,8 +1727,13 @@ * @method * @name Konva.Context#fill */ - fill() { - this._context.fill(); + fill(path2d) { + if (path2d) { + this._context.fill(path2d); + } + else { + this._context.fill(); + } } /** * fillRect function. @@ -1783,8 +1756,13 @@ * @method * @name Konva.Context#fillText */ - fillText(a0, a1, a2) { - this._context.fillText(a0, a1, a2); + fillText(text, x, y, maxWidth) { + if (maxWidth) { + this._context.fillText(text, x, y, maxWidth); + } + else { + this._context.fillText(text, x, y); + } } /** * measureText function. @@ -1915,8 +1893,13 @@ * @method * @name Konva.Context#stroke */ - stroke() { - this._context.stroke(); + stroke(path2d) { + if (path2d) { + this._context.stroke(path2d); + } + else { + this._context.stroke(); + } } /** * strokeText function. @@ -1948,7 +1931,7 @@ var func = function (methodName) { var origMethod = that[methodName], ret; that[methodName] = function () { - args = Util._simplifyArray(Array.prototype.slice.call(arguments, 0)); + args = simplifyArray(Array.prototype.slice.call(arguments, 0)); ret = origMethod.apply(that, arguments); that._trace({ method: methodName, @@ -1978,9 +1961,10 @@ }; } _applyGlobalCompositeOperation(node) { - var globalCompositeOperation = node.getGlobalCompositeOperation(); - if (globalCompositeOperation !== 'source-over') { - this.setAttr('globalCompositeOperation', globalCompositeOperation); + const op = node.attrs.globalCompositeOperation; + var def = !op || op === 'source-over'; + if (!def) { + this.setAttr('globalCompositeOperation', op); } } } @@ -2001,16 +1985,6 @@ shape._fillFunc(this); } _fillPattern(shape) { - var fillPatternX = shape.getFillPatternX(), fillPatternY = shape.getFillPatternY(), fillPatternRotation = Konva$2.getAngle(shape.getFillPatternRotation()), fillPatternOffsetX = shape.getFillPatternOffsetX(), fillPatternOffsetY = shape.getFillPatternOffsetY(); shape.getFillPatternScaleX(); shape.getFillPatternScaleY(); - if (fillPatternX || fillPatternY) { - this.translate(fillPatternX || 0, fillPatternY || 0); - } - if (fillPatternRotation) { - this.rotate(fillPatternRotation); - } - if (fillPatternOffsetX || fillPatternOffsetY) { - this.translate(-1 * fillPatternOffsetX, -1 * fillPatternOffsetY); - } this.setAttr('fillStyle', shape._getFillPattern()); shape._fillFunc(this); } @@ -2107,10 +2081,11 @@ } } _applyShadow(shape) { - var util = Util, color = util.get(shape.getShadowRGBA(), 'black'), blur = util.get(shape.getShadowBlur(), 5), offset = util.get(shape.getShadowOffset(), { + var _a, _b, _c; + var color = (_a = shape.getShadowRGBA()) !== null && _a !== void 0 ? _a : 'black', blur = (_b = shape.getShadowBlur()) !== null && _b !== void 0 ? _b : 5, offset = (_c = shape.getShadowOffset()) !== null && _c !== void 0 ? _c : { x: 0, y: 0, - }), scale = shape.getAbsoluteScale(), ratio = this.canvas.getPixelRatio(), scaleX = scale.x * ratio, scaleY = scale.y * ratio; + }, scale = shape.getAbsoluteScale(), ratio = this.canvas.getPixelRatio(), scaleX = scale.x * ratio, scaleY = scale.y * ratio; this.setAttr('shadowColor', color); this.setAttr('shadowBlur', blur * Math.min(Math.abs(scaleX), Math.abs(scaleY))); this.setAttr('shadowOffsetX', offset.x * scaleX); @@ -2370,7 +2345,7 @@ // dragBefore and dragAfter allows us to set correct order of events // setup all in dragbefore, and stop dragging only after pointerup triggered. _endDragBefore(evt) { - DD._dragElements.forEach((elem, key) => { + DD._dragElements.forEach((elem) => { const { node } = elem; // we need to find pointer relative to that node const stage = node.getStage(); @@ -2383,9 +2358,11 @@ return; } if (elem.dragStatus === 'dragging' || elem.dragStatus === 'stopped') { - // if a node is stopped manully we still need to reset events: + // if a node is stopped manually we still need to reset events: DD.justDragged = true; - Konva$2.listenClickTap = false; + Konva$2._mouseListenClick = false; + Konva$2._touchListenClick = false; + Konva$2._pointerListenClick = false; elem.dragStatus = 'stopped'; } const drawNode = elem.node.getLayer() || @@ -2419,53 +2396,8 @@ window.addEventListener('touchend', DD._endDragAfter, false); } - const ids = {}; - const names = {}; - const _addId = function (node, id) { - if (!id) { - return; - } - ids[id] = node; - }; - const _removeId = function (id, node) { - // node has no id - if (!id) { - return; - } - // another node is registered (possible for duplicate ids) - if (ids[id] !== node) { - return; - } - delete ids[id]; - }; - const _addName = function (node, name) { - if (name) { - if (!names[name]) { - names[name] = []; - } - names[name].push(node); - } - }; - const _removeName = function (name, _id) { - if (!name) { - return; - } - var nodes = names[name]; - if (!nodes) { - return; - } - for (var n = 0; n < nodes.length; n++) { - var no = nodes[n]; - if (no._id === _id) { - nodes.splice(n, 1); - } - } - if (nodes.length === 0) { - delete names[name]; - } - }; // CONSTANTS - var ABSOLUTE_OPACITY = 'absoluteOpacity', ALL_LISTENERS = 'allEventListeners', ABSOLUTE_TRANSFORM = 'absoluteTransform', ABSOLUTE_SCALE = 'absoluteScale', CANVAS = 'canvas', CHANGE = 'Change', CHILDREN = 'children', KONVA = 'konva', LISTENING = 'listening', MOUSEENTER$1 = 'mouseenter', MOUSELEAVE$1 = 'mouseleave', NAME = 'name', SET = 'set', SHAPE = 'Shape', SPACE$1 = ' ', STAGE$1 = 'stage', TRANSFORM = 'transform', UPPER_STAGE = 'Stage', VISIBLE = 'visible', TRANSFORM_CHANGE_STR$1 = [ + var ABSOLUTE_OPACITY = 'absoluteOpacity', ALL_LISTENERS = 'allEventListeners', ABSOLUTE_TRANSFORM = 'absoluteTransform', ABSOLUTE_SCALE = 'absoluteScale', CANVAS = 'canvas', CHANGE = 'Change', CHILDREN = 'children', KONVA = 'konva', LISTENING = 'listening', MOUSEENTER$1 = 'mouseenter', MOUSELEAVE$1 = 'mouseleave', SET = 'set', SHAPE = 'Shape', SPACE$1 = ' ', STAGE$1 = 'stage', TRANSFORM = 'transform', UPPER_STAGE = 'Stage', VISIBLE = 'visible', TRANSFORM_CHANGE_STR$1 = [ 'xChange.konva', 'yChange.konva', 'scaleXChange.konva', @@ -3070,14 +3002,6 @@ * node.destroy(); */ destroy() { - // remove from ids and names hashes - _removeId(this.id(), this); - // remove all names - var names = (this.name() || '').split(/\s/g); - for (var i = 0; i < names.length; i++) { - var subname = names[i]; - _removeName(subname, this._id); - } this.remove(); return this; } @@ -3338,6 +3262,33 @@ y: this.y(), }; } + /** + * get position of first pointer (like mouse or first touch) relative to local coordinates of current node + * @method + * @name Konva.Node#getRelativePointerPosition + * @returns {Konva.Node} + * @example + * + * // let's think we have a rectangle at position x = 10, y = 10 + * // now we clicked at x = 15, y = 15 of the stage + * // if you want to know position of the click, related to the rectangle you can use + * rect.getRelativePointerPosition(); + */ + getRelativePointerPosition() { + if (!this.getStage()) { + return null; + } + // get pointer (say mouse or touch) position + var pos = this.getStage().getPointerPosition(); + if (!pos) { + return null; + } + var transform = this.getAbsoluteTransform().copy(); + // to detect relative position we need to invert transform + transform.invert(); + // now we can find relative point + return transform.point(pos); + } /** * get absolute position of a node. That function can be used to calculate absolute position, but relative to any ancestor * @method @@ -4172,34 +4123,6 @@ newVal: newVal, }); } - setId(id) { - var oldId = this.id(); - _removeId(oldId, this); - _addId(this, id); - this._setAttr('id', id); - return this; - } - setName(name) { - var oldNames = (this.name() || '').split(/\s/g); - var newNames = (name || '').split(/\s/g); - var subname, i; - // remove all subnames - for (i = 0; i < oldNames.length; i++) { - subname = oldNames[i]; - if (newNames.indexOf(subname) === -1 && subname) { - _removeName(subname, this._id); - } - } - // add new names - for (i = 0; i < newNames.length; i++) { - subname = newNames[i]; - if (oldNames.indexOf(subname) === -1 && subname) { - _addName(this, subname); - } - } - this._setAttr(NAME, name); - return this; - } /** * add name to node * @method @@ -4215,7 +4138,7 @@ if (!this.hasName(name)) { var oldName = this.name(); var newName = oldName ? oldName + ' ' + name : name; - this.setName(newName); + this.name(newName); } return this; } @@ -4260,7 +4183,7 @@ var index = names.indexOf(name); if (index !== -1) { names.splice(index, 1); - this.setName(names.join(' ')); + this.name(names.join(' ')); } return this; } @@ -4291,7 +4214,7 @@ drawNode === null || drawNode === void 0 ? void 0 : drawNode.batchDraw(); } } - _setAttr(key, val, skipFire = false) { + _setAttr(key, val) { var oldVal = this.attrs[key]; if (oldVal === val && !Util.isObject(val)) { return; @@ -4547,6 +4470,34 @@ this.off('mousedown.konva'); this.off('touchstart.konva'); } + /** + * determine if node (at least partially) is currently in user-visible area + * @method + * @param {(Number | Object)} margin optional margin in pixels + * @param {Number} margin.x + * @param {Number} margin.y + * @returns {Boolean} + * @name Konva.Node#isClientRectOnScreen + * @example + * // get index + * // default calculations + * var isOnScreen = node.isClientRectOnScreen() + * // increase object size (or screen size) for cases when objects close to the screen still need to be marked as "visible" + * var isOnScreen = node.isClientRectOnScreen({ x: stage.width(), y: stage.height() }) + */ + isClientRectOnScreen(margin = { x: 0, y: 0 }) { + const stage = this.getStage(); + if (!stage) { + return false; + } + const screenRect = { + x: -margin.x, + y: -margin.y, + width: stage.width() + margin.x, + height: stage.height() + margin.y, + }; + return Util.haveIntersection(screenRect, this.getClientRect()); + } /** * create node with JSON string or an Object. De-serializtion does not generate custom * shape drawing functions, images, or event handlers (this would make the @@ -5731,39 +5682,92 @@ // CONSTANTS var STAGE = 'Stage', STRING = 'string', PX = 'px', MOUSEOUT = 'mouseout', MOUSELEAVE = 'mouseleave', MOUSEOVER = 'mouseover', MOUSEENTER = 'mouseenter', MOUSEMOVE = 'mousemove', MOUSEDOWN = 'mousedown', MOUSEUP = 'mouseup', // TODO: add them into "on" method docs and into site docs - POINTERMOVE = 'pointermove', POINTERDOWN = 'pointerdown', POINTERUP = 'pointerup', POINTERCANCEL = 'pointercancel', LOSTPOINTERCAPTURE = 'lostpointercapture', CONTEXTMENU = 'contextmenu', CLICK = 'click', DBL_CLICK = 'dblclick', TOUCHSTART = 'touchstart', TOUCHEND = 'touchend', TAP = 'tap', DBL_TAP = 'dbltap', TOUCHMOVE = 'touchmove', WHEEL = 'wheel', CONTENT_MOUSEOUT = 'contentMouseout', CONTENT_MOUSEOVER = 'contentMouseover', CONTENT_MOUSEMOVE = 'contentMousemove', CONTENT_MOUSEDOWN = 'contentMousedown', CONTENT_MOUSEUP = 'contentMouseup', CONTENT_CONTEXTMENU = 'contentContextmenu', CONTENT_CLICK = 'contentClick', CONTENT_DBL_CLICK = 'contentDblclick', CONTENT_TOUCHSTART = 'contentTouchstart', CONTENT_TOUCHEND = 'contentTouchend', CONTENT_DBL_TAP = 'contentDbltap', CONTENT_TAP = 'contentTap', CONTENT_TOUCHMOVE = 'contentTouchmove', CONTENT_WHEEL = 'contentWheel', RELATIVE = 'relative', KONVA_CONTENT = 'konvajs-content', UNDERSCORE = '_', CONTAINER = 'container', MAX_LAYERS_NUMBER = 5, EMPTY_STRING$1 = '', EVENTS = [ - MOUSEENTER, - MOUSEDOWN, - MOUSEMOVE, - MOUSEUP, - MOUSELEAVE, - TOUCHSTART, - TOUCHMOVE, - TOUCHEND, - MOUSEOVER, - WHEEL, - CONTEXTMENU, - POINTERDOWN, - POINTERMOVE, - POINTERUP, - POINTERCANCEL, - LOSTPOINTERCAPTURE, - ], - // cached variables - eventsLength = EVENTS.length; - function addEvent(ctx, eventName) { - ctx.content.addEventListener(eventName, function (evt) { - ctx[UNDERSCORE + eventName](evt); - }, false); - } - const NO_POINTERS_MESSAGE = `Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);`; - const stages = []; + 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 = [ + [MOUSEENTER, '_pointerenter'], + [MOUSEDOWN, '_pointerdown'], + [MOUSEMOVE, '_pointermove'], + [MOUSEUP, '_pointerup'], + [MOUSELEAVE, '_pointerleave'], + [TOUCHSTART, '_pointerdown'], + [TOUCHMOVE, '_pointermove'], + [TOUCHEND, '_pointerup'], + [TOUCHCANCEL, '_pointercancel'], + [MOUSEOVER, '_pointerover'], + [WHEEL, '_wheel'], + [CONTEXTMENU, '_contextmenu'], + [POINTERDOWN, '_pointerdown'], + [POINTERMOVE, '_pointermove'], + [POINTERUP, '_pointerup'], + [POINTERCANCEL, '_pointercancel'], + [LOSTPOINTERCAPTURE, '_lostpointercapture'], + ]; + const EVENTS_MAP = { + mouse: { + [POINTEROUT]: MOUSEOUT, + [POINTERLEAVE]: MOUSELEAVE, + [POINTEROVER]: MOUSEOVER, + [POINTERENTER]: MOUSEENTER, + [POINTERMOVE]: MOUSEMOVE, + [POINTERDOWN]: MOUSEDOWN, + [POINTERUP]: MOUSEUP, + [POINTERCANCEL]: 'mousecancel', + pointerclick: 'click', + pointerdblclick: 'dblclick', + }, + touch: { + [POINTEROUT]: 'touchout', + [POINTERLEAVE]: 'touchleave', + [POINTEROVER]: 'touchover', + [POINTERENTER]: 'touchenter', + [POINTERMOVE]: TOUCHMOVE, + [POINTERDOWN]: TOUCHSTART, + [POINTERUP]: TOUCHEND, + [POINTERCANCEL]: TOUCHCANCEL, + pointerclick: 'tap', + pointerdblclick: 'dbltap', + }, + pointer: { + [POINTEROUT]: POINTEROUT, + [POINTERLEAVE]: POINTERLEAVE, + [POINTEROVER]: POINTEROVER, + [POINTERENTER]: POINTERENTER, + [POINTERMOVE]: POINTERMOVE, + [POINTERDOWN]: POINTERDOWN, + [POINTERUP]: POINTERUP, + [POINTERCANCEL]: POINTERCANCEL, + pointerclick: 'pointerclick', + pointerdblclick: 'pointerdblclick', + }, + }; + const getEventType = (type) => { + if (type.indexOf('pointer') >= 0) { + return 'pointer'; + } + if (type.indexOf('touch') >= 0) { + return 'touch'; + } + return 'mouse'; + }; + const getEventsMap = (eventType) => { + const type = getEventType(eventType); + if (type === 'pointer') { + return Konva$2.pointerEventsEnabled && EVENTS_MAP.pointer; + } + if (type === 'touch') { + return EVENTS_MAP.touch; + } + if (type === 'mouse') { + return EVENTS_MAP.mouse; + } + }; function checkNoClip(attrs = {}) { if (attrs.clipFunc || attrs.clipWidth || attrs.clipHeight) { Util.warn('Stage does not support clipping. Please use clip for Layers or Groups.'); } return attrs; } + const NO_POINTERS_MESSAGE = `Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);`; + const stages = []; /** * Stage constructor. A stage is used to contain multiple layers * @constructor @@ -5854,7 +5858,7 @@ throw 'Can not find container in document with id ' + id; } } - this._setAttr(CONTAINER, container); + this._setAttr('container', container); if (this.content) { if (this.content.parentElement) { this.content.parentElement.removeChild(this.content); @@ -5899,9 +5903,9 @@ return this; } /** - * returns absolute pointer position which can be a touch position or mouse position + * returns ABSOLUTE pointer position which can be a touch position or mouse position * pointer position doesn't include any transforms (such as scale) of the stage - * it is just a plain position of pointer relative to top-left corner of the stage container + * it is just a plain position of pointer relative to top-left corner of the canvas * @method * @name Konva.Stage#getPointerPosition * @returns {Vector2d|null} @@ -5962,20 +5966,17 @@ * @param {Object} pos * @param {Number} pos.x * @param {Number} pos.y - * @param {String} [selector] * @returns {Konva.Node} * @example * var shape = stage.getIntersection({x: 50, y: 50}); - * // or if you interested in shape parent: - * var group = stage.getIntersection({x: 50, y: 50}, 'Group'); */ - getIntersection(pos, selector) { + getIntersection(pos) { if (!pos) { return null; } var layers = this.children, len = layers.length, end = len - 1, n; for (n = end; n >= 0; n--) { - const shape = layers[n].getIntersection(pos, selector); + const shape = layers[n].getIntersection(pos); if (shape) { return shape; } @@ -6048,37 +6049,63 @@ if (!Konva$2.isBrowser) { return; } - for (var n = 0; n < eventsLength; n++) { - addEvent(this, EVENTS[n]); + EVENTS.forEach(([event, methodName]) => { + this.content.addEventListener(event, (evt) => { + this[methodName](evt); + }); + }); + } + _pointerenter(evt) { + this.setPointersPositions(evt); + const events = getEventsMap(evt.type); + this._fire(events.pointerenter, { + evt: evt, + target: this, + currentTarget: this, + }); + } + _pointerover(evt) { + this.setPointersPositions(evt); + const events = getEventsMap(evt.type); + this._fire(events.pointerover, { + evt: evt, + target: this, + currentTarget: this, + }); + } + _getTargetShape(evenType) { + let shape = this[evenType + 'targetShape']; + if (shape && !shape.getStage()) { + shape = null; } + return shape; } - _mouseenter(evt) { + _pointerleave(evt) { + const events = getEventsMap(evt.type); + const eventType = getEventType(evt.type); + if (!events) { + return; + } this.setPointersPositions(evt); - this._fire(MOUSEENTER, { evt: evt, target: this, currentTarget: this }); - } - _mouseover(evt) { - this.setPointersPositions(evt); - this._fire(CONTENT_MOUSEOVER, { evt: evt }); - this._fire(MOUSEOVER, { evt: evt, target: this, currentTarget: this }); - } - _mouseleave(evt) { - var _a; - this.setPointersPositions(evt); - var targetShape = ((_a = this.targetShape) === null || _a === void 0 ? void 0 : _a.getStage()) ? this.targetShape : null; + var targetShape = this._getTargetShape(eventType); var eventsEnabled = !DD.isDragging || Konva$2.hitOnDragEnabled; if (targetShape && eventsEnabled) { - targetShape._fireAndBubble(MOUSEOUT, { evt: evt }); - targetShape._fireAndBubble(MOUSELEAVE, { evt: evt }); - this._fire(MOUSELEAVE, { evt: evt, target: this, currentTarget: this }); - this.targetShape = null; - } - else if (eventsEnabled) { - this._fire(MOUSELEAVE, { + targetShape._fireAndBubble(events.pointerout, { evt: evt }); + targetShape._fireAndBubble(events.pointerleave, { evt: evt }); + this._fire(events.pointerleave, { evt: evt, target: this, currentTarget: this, }); - this._fire(MOUSEOUT, { + this[eventType + 'targetShape'] = null; + } + else if (eventsEnabled) { + this._fire(events.pointerleave, { + evt: evt, + target: this, + currentTarget: this, + }); + this._fire(events.pointerout, { evt: evt, target: this, currentTarget: this, @@ -6086,155 +6113,194 @@ } this.pointerPos = undefined; this._pointerPositions = []; - this._fire(CONTENT_MOUSEOUT, { evt: evt }); } - _mousemove(evt) { - var _a; + _pointerdown(evt) { + const events = getEventsMap(evt.type); + const eventType = getEventType(evt.type); + if (!events) { + return; + } + this.setPointersPositions(evt); + var triggeredOnShape = false; + this._changedPointerPositions.forEach((pos) => { + var shape = this.getIntersection(pos); + DD.justDragged = false; + // probably we are staring a click + Konva$2['_' + eventType + 'ListenClick'] = true; + // no shape detected? do nothing + const hasShape = shape && shape.isListening(); + if (!hasShape) { + return; + } + if (Konva$2.capturePointerEventsEnabled) { + shape.setPointerCapture(pos.id); + } + // save where we started the click + this[eventType + 'ClickStartShape'] = shape; + shape._fireAndBubble(events.pointerdown, { + evt: evt, + pointerId: pos.id, + }); + triggeredOnShape = true; + // TODO: test in iframe + // only call preventDefault if the shape is listening for events + const isTouch = evt.type.indexOf('touch') >= 0; + if (shape.preventDefault() && evt.cancelable && isTouch) { + evt.preventDefault(); + } + }); + // trigger down on stage if not already + if (!triggeredOnShape) { + this._fire(events.pointerdown, { + evt: evt, + target: this, + currentTarget: this, + pointerId: this._pointerPositions[0].id, + }); + } + } + _pointermove(evt) { + const events = getEventsMap(evt.type); + const eventType = getEventType(evt.type); + if (!events) { + return; + } + if (DD.isDragging && DD.node.preventDefault() && evt.cancelable) { + evt.preventDefault(); + } this.setPointersPositions(evt); - var pointerId = Util._getFirstPointerId(evt); - var targetShape = ((_a = this.targetShape) === null || _a === void 0 ? void 0 : _a.getStage()) ? this.targetShape : null; var eventsEnabled = !DD.isDragging || Konva$2.hitOnDragEnabled; - if (eventsEnabled) { - const shape = this.getIntersection(this.getPointerPosition()); + if (!eventsEnabled) { + return; + } + var processedShapesIds = {}; + let triggeredOnShape = false; + var targetShape = this._getTargetShape(eventType); + this._changedPointerPositions.forEach((pos) => { + const shape = (getCapturedShape(pos.id) || + this.getIntersection(pos)); + const pointerId = pos.id; + const event = { evt: evt, pointerId }; + var differentTarget = targetShape !== shape; + if (differentTarget && targetShape) { + targetShape._fireAndBubble(events.pointerout, event, shape); + targetShape._fireAndBubble(events.pointerleave, event, shape); + } + if (shape) { + if (processedShapesIds[shape._id]) { + return; + } + processedShapesIds[shape._id] = true; + } if (shape && shape.isListening()) { - var differentTarget = targetShape !== shape; - if (eventsEnabled && differentTarget) { - if (targetShape) { - targetShape._fireAndBubble(MOUSEOUT, { evt: evt, pointerId }, shape); - targetShape._fireAndBubble(MOUSELEAVE, { evt: evt, pointerId }, shape); - } - shape._fireAndBubble(MOUSEOVER, { evt: evt, pointerId }, targetShape); - shape._fireAndBubble(MOUSEENTER, { evt: evt, pointerId }, targetShape); - shape._fireAndBubble(MOUSEMOVE, { evt: evt, pointerId }); - this.targetShape = shape; - } - else { - shape._fireAndBubble(MOUSEMOVE, { evt: evt, pointerId }); + triggeredOnShape = true; + if (differentTarget) { + shape._fireAndBubble(events.pointerover, event, targetShape); + shape._fireAndBubble(events.pointerenter, event, targetShape); + this[eventType + 'targetShape'] = shape; } + shape._fireAndBubble(events.pointermove, event); } else { - /* - * if no shape was detected, clear target shape and try - * to run mouseout from previous target shape - */ - if (targetShape && eventsEnabled) { - targetShape._fireAndBubble(MOUSEOUT, { evt: evt, pointerId }); - targetShape._fireAndBubble(MOUSELEAVE, { evt: evt, pointerId }); - this._fire(MOUSEOVER, { + if (targetShape) { + this._fire(events.pointerover, { evt: evt, target: this, currentTarget: this, pointerId, }); - this.targetShape = null; + this[eventType + 'targetShape'] = null; } - this._fire(MOUSEMOVE, { - evt: evt, - target: this, - currentTarget: this, - pointerId, - }); } - // content event - this._fire(CONTENT_MOUSEMOVE, { evt: evt }); - } - // always call preventDefault for desktop events because some browsers - // try to drag and drop the canvas element - if (evt.cancelable) { - evt.preventDefault(); - } - } - _mousedown(evt) { - this.setPointersPositions(evt); - var pointerId = Util._getFirstPointerId(evt); - var shape = this.getIntersection(this.getPointerPosition()); - DD.justDragged = false; - Konva$2.listenClickTap = true; - if (shape && shape.isListening()) { - this.clickStartShape = shape; - shape._fireAndBubble(MOUSEDOWN, { evt: evt, pointerId }); - } - else { - this._fire(MOUSEDOWN, { + }); + if (!triggeredOnShape) { + this._fire(events.pointermove, { evt: evt, target: this, currentTarget: this, - pointerId, + pointerId: this._changedPointerPositions[0].id, }); } - // content event - this._fire(CONTENT_MOUSEDOWN, { evt: evt }); - // Do not prevent default behavior, because it will prevent listening events outside of window iframe - // we used preventDefault for disabling native drag&drop - // but userSelect = none style will do the trick - // if (evt.cancelable) { - // evt.preventDefault(); - // } } - _mouseup(evt) { + _pointerup(evt) { + const events = getEventsMap(evt.type); + const eventType = getEventType(evt.type); + if (!events) { + return; + } this.setPointersPositions(evt); - var pointerId = Util._getFirstPointerId(evt); - var shape = this.getIntersection(this.getPointerPosition()), clickStartShape = this.clickStartShape, clickEndShape = this.clickEndShape, fireDblClick = false; - if (Konva$2.inDblClickWindow) { - fireDblClick = true; - clearTimeout(this.dblTimeout); - // Konva.inDblClickWindow = false; - } - else if (!DD.justDragged) { - // don't set inDblClickWindow after dragging - Konva$2.inDblClickWindow = true; - clearTimeout(this.dblTimeout); - } - this.dblTimeout = setTimeout(function () { - Konva$2.inDblClickWindow = false; - }, Konva$2.dblClickWindow); - if (shape && shape.isListening()) { - this.clickEndShape = shape; - shape._fireAndBubble(MOUSEUP, { evt: evt, pointerId }); - // detect if click or double click occurred - if (Konva$2.listenClickTap && - clickStartShape && - clickStartShape._id === shape._id) { - shape._fireAndBubble(CLICK, { evt: evt, pointerId }); - if (fireDblClick && clickEndShape && clickEndShape === shape) { - shape._fireAndBubble(DBL_CLICK, { evt: evt, pointerId }); + const clickStartShape = this[eventType + 'ClickStartShape']; + const clickEndShape = this[eventType + 'ClickEndShape']; + var processedShapesIds = {}; + let triggeredOnShape = false; + this._changedPointerPositions.forEach((pos) => { + const shape = (getCapturedShape(pos.id) || + this.getIntersection(pos)); + if (shape) { + shape.releaseCapture(pos.id); + if (processedShapesIds[shape._id]) { + return; + } + processedShapesIds[shape._id] = true; + } + const pointerId = pos.id; + const event = { evt: evt, pointerId }; + let fireDblClick = false; + if (Konva$2['_' + eventType + 'InDblClickWindow']) { + fireDblClick = true; + clearTimeout(this[eventType + 'DblTimeout']); + } + else if (!DD.justDragged) { + // don't set inDblClickWindow after dragging + Konva$2['_' + eventType + 'InDblClickWindow'] = true; + clearTimeout(this[eventType + 'DblTimeout']); + } + this[eventType + 'DblTimeout'] = setTimeout(function () { + Konva$2['_' + eventType + 'InDblClickWindow'] = false; + }, Konva$2.dblClickWindow); + if (shape && shape.isListening()) { + triggeredOnShape = true; + this[eventType + 'ClickEndShape'] = shape; + shape._fireAndBubble(events.pointerup, event); + // detect if click or double click occurred + if (Konva$2['_' + eventType + 'ListenClick'] && + clickStartShape && + clickStartShape === shape) { + shape._fireAndBubble(events.pointerclick, event); + if (fireDblClick && clickEndShape && clickEndShape === shape) { + shape._fireAndBubble(events.pointerdblclick, event); + } } } - } - else { - this.clickEndShape = null; - this._fire(MOUSEUP, { + else { + this[eventType + 'ClickEndShape'] = null; + if (Konva$2['_' + eventType + 'ListenClick']) { + this._fire(events.pointerclick, { + evt: evt, + target: this, + currentTarget: this, + pointerId, + }); + } + if (fireDblClick) { + this._fire(events.pointerdblclick, { + evt: evt, + target: this, + currentTarget: this, + pointerId, + }); + } + } + }); + if (!triggeredOnShape) { + this._fire(events.pointerup, { evt: evt, target: this, currentTarget: this, - pointerId, + pointerId: this._changedPointerPositions[0].id, }); - if (Konva$2.listenClickTap) { - this._fire(CLICK, { - evt: evt, - target: this, - currentTarget: this, - pointerId, - }); - } - if (fireDblClick) { - this._fire(DBL_CLICK, { - evt: evt, - target: this, - currentTarget: this, - pointerId, - }); - } } - // content events - this._fire(CONTENT_MOUSEUP, { evt: evt }); - if (Konva$2.listenClickTap) { - this._fire(CONTENT_CLICK, { evt: evt }); - if (fireDblClick) { - this._fire(CONTENT_DBL_CLICK, { evt: evt }); - } - } - Konva$2.listenClickTap = false; + Konva$2['_' + eventType + 'ListenClick'] = false; // always call preventDefault for desktop events because some browsers // try to drag and drop the canvas element if (evt.cancelable) { @@ -6254,165 +6320,6 @@ currentTarget: this, }); } - this._fire(CONTENT_CONTEXTMENU, { evt: evt }); - } - _touchstart(evt) { - this.setPointersPositions(evt); - var triggeredOnShape = false; - this._changedPointerPositions.forEach((pos) => { - var shape = this.getIntersection(pos); - Konva$2.listenClickTap = true; - DD.justDragged = false; - const hasShape = shape && shape.isListening(); - if (!hasShape) { - return; - } - if (Konva$2.captureTouchEventsEnabled) { - shape.setPointerCapture(pos.id); - } - this.tapStartShape = shape; - shape._fireAndBubble(TOUCHSTART, { evt: evt, pointerId: pos.id }, this); - triggeredOnShape = true; - // only call preventDefault if the shape is listening for events - if (shape.isListening() && shape.preventDefault() && evt.cancelable) { - evt.preventDefault(); - } - }); - if (!triggeredOnShape) { - this._fire(TOUCHSTART, { - evt: evt, - target: this, - currentTarget: this, - pointerId: this._changedPointerPositions[0].id, - }); - } - // content event - this._fire(CONTENT_TOUCHSTART, { evt: evt }); - } - _touchmove(evt) { - this.setPointersPositions(evt); - var eventsEnabled = !DD.isDragging || Konva$2.hitOnDragEnabled; - if (eventsEnabled) { - var triggeredOnShape = false; - var processedShapesIds = {}; - this._changedPointerPositions.forEach((pos) => { - const shape = getCapturedShape(pos.id) || this.getIntersection(pos); - const hasShape = shape && shape.isListening(); - if (!hasShape) { - return; - } - if (processedShapesIds[shape._id]) { - return; - } - processedShapesIds[shape._id] = true; - shape._fireAndBubble(TOUCHMOVE, { evt: evt, pointerId: pos.id }); - triggeredOnShape = true; - // only call preventDefault if the shape is listening for events - if (shape.isListening() && shape.preventDefault() && evt.cancelable) { - evt.preventDefault(); - } - }); - if (!triggeredOnShape) { - this._fire(TOUCHMOVE, { - evt: evt, - target: this, - currentTarget: this, - pointerId: this._changedPointerPositions[0].id, - }); - } - this._fire(CONTENT_TOUCHMOVE, { evt: evt }); - } - if (DD.isDragging && DD.node.preventDefault() && evt.cancelable) { - evt.preventDefault(); - } - } - _touchend(evt) { - this.setPointersPositions(evt); - var tapEndShape = this.tapEndShape, fireDblClick = false; - if (Konva$2.inDblClickWindow) { - fireDblClick = true; - clearTimeout(this.dblTimeout); - // Konva.inDblClickWindow = false; - } - else if (!DD.justDragged) { - Konva$2.inDblClickWindow = true; - clearTimeout(this.dblTimeout); - } - this.dblTimeout = setTimeout(function () { - Konva$2.inDblClickWindow = false; - }, Konva$2.dblClickWindow); - var triggeredOnShape = false; - var processedShapesIds = {}; - var tapTriggered = false; - var dblTapTriggered = false; - this._changedPointerPositions.forEach((pos) => { - var shape = getCapturedShape(pos.id) || - this.getIntersection(pos); - if (shape) { - shape.releaseCapture(pos.id); - } - const hasShape = shape && shape.isListening(); - if (!hasShape) { - return; - } - if (processedShapesIds[shape._id]) { - return; - } - processedShapesIds[shape._id] = true; - this.tapEndShape = shape; - shape._fireAndBubble(TOUCHEND, { evt: evt, pointerId: pos.id }); - triggeredOnShape = true; - // detect if tap or double tap occurred - if (Konva$2.listenClickTap && shape === this.tapStartShape) { - tapTriggered = true; - shape._fireAndBubble(TAP, { evt: evt, pointerId: pos.id }); - if (fireDblClick && tapEndShape && tapEndShape === shape) { - dblTapTriggered = true; - shape._fireAndBubble(DBL_TAP, { evt: evt, pointerId: pos.id }); - } - } - // only call preventDefault if the shape is listening for events - if (shape.isListening() && shape.preventDefault() && evt.cancelable) { - evt.preventDefault(); - } - }); - if (!triggeredOnShape) { - this._fire(TOUCHEND, { - evt: evt, - target: this, - currentTarget: this, - pointerId: this._changedPointerPositions[0].id, - }); - } - if (Konva$2.listenClickTap && !tapTriggered) { - this.tapEndShape = null; - this._fire(TAP, { - evt: evt, - target: this, - currentTarget: this, - pointerId: this._changedPointerPositions[0].id, - }); - } - if (fireDblClick && !dblTapTriggered) { - this._fire(DBL_TAP, { - evt: evt, - target: this, - currentTarget: this, - pointerId: this._changedPointerPositions[0].id, - }); - } - // content events - this._fire(CONTENT_TOUCHEND, { evt: evt }); - if (Konva$2.listenClickTap) { - this._fire(CONTENT_TAP, { evt: evt }); - if (fireDblClick) { - this._fire(CONTENT_DBL_TAP, { evt: evt }); - } - } - if (this.preventDefault() && evt.cancelable) { - evt.preventDefault(); - } - Konva$2.listenClickTap = false; } _wheel(evt) { this.setPointersPositions(evt); @@ -6427,46 +6334,8 @@ currentTarget: this, }); } - this._fire(CONTENT_WHEEL, { evt: evt }); - } - _pointerdown(evt) { - if (!Konva$2._pointerEventsEnabled) { - return; - } - this.setPointersPositions(evt); - const shape = getCapturedShape(evt.pointerId) || - this.getIntersection(this.getPointerPosition()); - if (shape) { - shape._fireAndBubble(POINTERDOWN, createEvent(evt)); - } - } - _pointermove(evt) { - if (!Konva$2._pointerEventsEnabled) { - return; - } - this.setPointersPositions(evt); - const shape = getCapturedShape(evt.pointerId) || - this.getIntersection(this.getPointerPosition()); - if (shape) { - shape._fireAndBubble(POINTERMOVE, createEvent(evt)); - } - } - _pointerup(evt) { - if (!Konva$2._pointerEventsEnabled) { - return; - } - this.setPointersPositions(evt); - const shape = getCapturedShape(evt.pointerId) || - this.getIntersection(this.getPointerPosition()); - if (shape) { - shape._fireAndBubble(POINTERUP, createEvent(evt)); - } - releaseCapture(evt.pointerId); } _pointercancel(evt) { - if (!Konva$2._pointerEventsEnabled) { - return; - } this.setPointersPositions(evt); const shape = getCapturedShape(evt.pointerId) || this.getIntersection(this.getPointerPosition()); @@ -6571,12 +6440,12 @@ throw 'Stage has no container. A container is required.'; } // clear content inside container - container.innerHTML = EMPTY_STRING$1; + container.innerHTML = ''; // content this.content = document.createElement('div'); - this.content.style.position = RELATIVE; + this.content.style.position = 'relative'; this.content.style.userSelect = 'none'; - this.content.className = KONVA_CONTENT; + this.content.className = 'konvajs-content'; this.content.setAttribute('role', 'presentation'); container.appendChild(this.content); this._resizeDOM(); @@ -6828,13 +6697,19 @@ var ctx = getDummyContext$1(); const pattern = ctx.createPattern(this.fillPatternImage(), this.fillPatternRepeat() || 'repeat'); if (pattern && pattern.setTransform) { + const tr = new Transform(); + tr.translate(this.fillPatternX(), this.fillPatternX()); + tr.rotate(Konva$2.getAngle(this.fillPatternRotation())); + tr.scale(this.fillPatternScaleX(), this.fillPatternScaleY()); + tr.translate(-1 * this.fillPatternOffsetX(), -1 * this.fillPatternOffsetY()); + const m = tr.getMatrix(); pattern.setTransform({ - a: this.fillPatternScaleX(), - b: 0, - c: 0, - d: this.fillPatternScaleY(), - e: 0, - f: 0, // Vertical translation (moving). + a: m[0], + b: m[1], + c: m[2], + d: m[3], + e: m[4], + f: m[5], // Vertical translation (moving). }); } return pattern; @@ -7232,7 +7107,7 @@ Shape.prototype.eventListeners = {}; Shape.prototype.on.call(Shape.prototype, 'shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva', _clearHasShadowCache); Shape.prototype.on.call(Shape.prototype, 'shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva', _clearGetShadowRGBACache); - Shape.prototype.on.call(Shape.prototype, 'fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva', _clearFillPatternCache); + Shape.prototype.on.call(Shape.prototype, 'fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetX.konva fillPatternOffsetY.konva fillPatternRotation.konva', _clearFillPatternCache); Shape.prototype.on.call(Shape.prototype, 'fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva', _clearLinearGradientCache); Shape.prototype.on.call(Shape.prototype, 'fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva', _clearRadialGradientCache); // add getters and setters @@ -8542,14 +8417,11 @@ * @param {Object} pos * @param {Number} pos.x * @param {Number} pos.y - * @param {String} [selector] * @returns {Konva.Node} * @example * var shape = layer.getIntersection({x: 50, y: 50}); - * // or if you interested in shape parent: - * var group = layer.getIntersection({x: 50, y: 50}, 'Group'); */ - getIntersection(pos, selector) { + getIntersection(pos) { if (!this.isListening() || !this.isVisible()) { return null; } @@ -8565,10 +8437,7 @@ y: pos.y + intersectionOffset.y * spiralSearchDistance, }); const shape = obj.shape; - if (shape && selector) { - return shape.findAncestor(selector, true); - } - else if (shape) { + if (shape) { return shape; } // we should continue search if we found antialiased pixel @@ -9740,8 +9609,6 @@ Util, Transform, Node, - ids, - names, Container, Stage, stages, @@ -9941,6 +9808,26 @@ * arc.clockwise(true); */ + function getControlPoints(x0, y0, x1, y1, x2, y2, t) { + var d01 = Math.sqrt(Math.pow(x1 - x0, 2) + Math.pow(y1 - y0, 2)), d12 = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2)), fa = (t * d01) / (d01 + d12), fb = (t * d12) / (d01 + d12), p1x = x1 - fa * (x2 - x0), p1y = y1 - fa * (y2 - y0), p2x = x1 + fb * (x2 - x0), p2y = y1 + fb * (y2 - y0); + return [p1x, p1y, p2x, p2y]; + } + function expandPoints(p, tension) { + var len = p.length, allPoints = [], n, cp; + for (n = 2; n < len - 2; n += 2) { + cp = getControlPoints(p[n - 2], p[n - 1], p[n], p[n + 1], p[n + 2], p[n + 3], tension); + if (isNaN(cp[0])) { + continue; + } + allPoints.push(cp[0]); + allPoints.push(cp[1]); + allPoints.push(p[n]); + allPoints.push(p[n + 1]); + allPoints.push(cp[2]); + allPoints.push(cp[3]); + } + return allPoints; + } /** * Line constructor.  Lines are defined by an array of points and * a tension @@ -10096,11 +9983,11 @@ return this._getTensionPointsClosed(); } else { - return Util._expandPoints(this.points(), this.tension()); + return expandPoints(this.points(), this.tension()); } } _getTensionPointsClosed() { - var p = this.points(), len = p.length, tension = this.tension(), firstControlPoints = Util._getControlPoints(p[len - 2], p[len - 1], p[0], p[1], p[2], p[3], tension), lastControlPoints = Util._getControlPoints(p[len - 4], p[len - 3], p[len - 2], p[len - 1], p[0], p[1], tension), middle = Util._expandPoints(p, tension), tp = [firstControlPoints[2], firstControlPoints[3]] + var p = this.points(), len = p.length, tension = this.tension(), firstControlPoints = getControlPoints(p[len - 2], p[len - 1], p[0], p[1], p[2], p[3], tension), lastControlPoints = getControlPoints(p[len - 4], p[len - 3], p[len - 2], p[len - 1], p[0], p[1], tension), middle = expandPoints(p, tension), tp = [firstControlPoints[2], firstControlPoints[3]] .concat(middle) .concat([ lastControlPoints[0], @@ -10233,6 +10120,830 @@ * line.points(line.points().concat([70, 80])); */ + /** + * Path constructor. + * @author Jason Follas + * @constructor + * @memberof Konva + * @augments Konva.Shape + * @param {Object} config + * @param {String} config.data SVG data string + * @param {String} [config.fill] fill color + * @param {Image} [config.fillPatternImage] fill pattern image + * @param {Number} [config.fillPatternX] + * @param {Number} [config.fillPatternY] + * @param {Object} [config.fillPatternOffset] object with x and y component + * @param {Number} [config.fillPatternOffsetX] + * @param {Number} [config.fillPatternOffsetY] + * @param {Object} [config.fillPatternScale] object with x and y component + * @param {Number} [config.fillPatternScaleX] + * @param {Number} [config.fillPatternScaleY] + * @param {Number} [config.fillPatternRotation] + * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" + * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component + * @param {Number} [config.fillLinearGradientStartPointX] + * @param {Number} [config.fillLinearGradientStartPointY] + * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component + * @param {Number} [config.fillLinearGradientEndPointX] + * @param {Number} [config.fillLinearGradientEndPointY] + * @param {Array} [config.fillLinearGradientColorStops] array of color stops + * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component + * @param {Number} [config.fillRadialGradientStartPointX] + * @param {Number} [config.fillRadialGradientStartPointY] + * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component + * @param {Number} [config.fillRadialGradientEndPointX] + * @param {Number} [config.fillRadialGradientEndPointY] + * @param {Number} [config.fillRadialGradientStartRadius] + * @param {Number} [config.fillRadialGradientEndRadius] + * @param {Array} [config.fillRadialGradientColorStops] array of color stops + * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true + * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration + * @param {String} [config.stroke] stroke color + * @param {Number} [config.strokeWidth] stroke width + * @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false. + * @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth + * @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true + * @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true + * @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true + * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true + * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true + * @param {String} [config.lineJoin] can be miter, round, or bevel. The default + * is miter + * @param {String} [config.lineCap] can be butt, round, or square. The default + * is butt + * @param {String} [config.shadowColor] + * @param {Number} [config.shadowBlur] + * @param {Object} [config.shadowOffset] object with x and y component + * @param {Number} [config.shadowOffsetX] + * @param {Number} [config.shadowOffsetY] + * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number + * between 0 and 1 + * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true + * @param {Array} [config.dash] + * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true + + * @param {Number} [config.x] + * @param {Number} [config.y] + * @param {Number} [config.width] + * @param {Number} [config.height] + * @param {Boolean} [config.visible] + * @param {Boolean} [config.listening] whether or not the node is listening for events + * @param {String} [config.id] unique id + * @param {String} [config.name] non-unique name + * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 + * @param {Object} [config.scale] set scale + * @param {Number} [config.scaleX] set scale x + * @param {Number} [config.scaleY] set scale y + * @param {Number} [config.rotation] rotation in degrees + * @param {Object} [config.offset] offset from center point and rotation point + * @param {Number} [config.offsetX] set offset x + * @param {Number} [config.offsetY] set offset y + * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop + * the entire stage by dragging any portion of the stage + * @param {Number} [config.dragDistance] + * @param {Function} [config.dragBoundFunc] + * @example + * var path = new Konva.Path({ + * x: 240, + * y: 40, + * data: 'M12.582,9.551C3.251,16.237,0.921,29.021,7.08,38.564l-2.36,1.689l4.893,2.262l4.893,2.262l-0.568-5.36l-0.567-5.359l-2.365,1.694c-4.657-7.375-2.83-17.185,4.352-22.33c7.451-5.338,17.817-3.625,23.156,3.824c5.337,7.449,3.625,17.813-3.821,23.152l2.857,3.988c9.617-6.893,11.827-20.277,4.935-29.896C35.591,4.87,22.204,2.658,12.582,9.551z', + * fill: 'green', + * scaleX: 2, + * scaleY: 2 + * }); + */ + class Path extends Shape { + constructor(config) { + super(config); + this.dataArray = []; + this.pathLength = 0; + this.dataArray = Path.parsePathData(this.data()); + this.pathLength = 0; + for (var i = 0; i < this.dataArray.length; ++i) { + this.pathLength += this.dataArray[i].pathLength; + } + this.on('dataChange.konva', function () { + this.dataArray = Path.parsePathData(this.data()); + this.pathLength = 0; + for (var i = 0; i < this.dataArray.length; ++i) { + this.pathLength += this.dataArray[i].pathLength; + } + }); + } + _sceneFunc(context) { + var ca = this.dataArray; + // context position + context.beginPath(); + var isClosed = false; + for (var n = 0; n < ca.length; n++) { + var c = ca[n].command; + var p = ca[n].points; + switch (c) { + case 'L': + context.lineTo(p[0], p[1]); + break; + case 'M': + context.moveTo(p[0], p[1]); + break; + case 'C': + context.bezierCurveTo(p[0], p[1], p[2], p[3], p[4], p[5]); + break; + case 'Q': + context.quadraticCurveTo(p[0], p[1], p[2], p[3]); + break; + case 'A': + var cx = p[0], cy = p[1], rx = p[2], ry = p[3], theta = p[4], dTheta = p[5], psi = p[6], fs = p[7]; + var r = rx > ry ? rx : ry; + var scaleX = rx > ry ? 1 : rx / ry; + var scaleY = rx > ry ? ry / rx : 1; + context.translate(cx, cy); + context.rotate(psi); + context.scale(scaleX, scaleY); + context.arc(0, 0, r, theta, theta + dTheta, 1 - fs); + context.scale(1 / scaleX, 1 / scaleY); + context.rotate(-psi); + context.translate(-cx, -cy); + break; + case 'z': + isClosed = true; + context.closePath(); + break; + } + } + if (!isClosed && !this.hasFill()) { + context.strokeShape(this); + } + else { + context.fillStrokeShape(this); + } + } + getSelfRect() { + var points = []; + this.dataArray.forEach(function (data) { + if (data.command === 'A') { + // Approximates by breaking curve into line segments + var start = data.points[4]; + // 4 = theta + var dTheta = data.points[5]; + // 5 = dTheta + var end = data.points[4] + dTheta; + var inc = Math.PI / 180.0; + // 1 degree resolution + if (Math.abs(start - end) < inc) { + inc = Math.abs(start - end); + } + if (dTheta < 0) { + // clockwise + for (let t = start - inc; t > end; t -= inc) { + const point = Path.getPointOnEllipticalArc(data.points[0], data.points[1], data.points[2], data.points[3], t, 0); + points.push(point.x, point.y); + } + } + else { + // counter-clockwise + for (let t = start + inc; t < end; t += inc) { + const point = Path.getPointOnEllipticalArc(data.points[0], data.points[1], data.points[2], data.points[3], t, 0); + points.push(point.x, point.y); + } + } + } + else if (data.command === 'C') { + // Approximates by breaking curve into 100 line segments + for (let t = 0.0; t <= 1; t += 0.01) { + const point = Path.getPointOnCubicBezier(t, data.start.x, data.start.y, data.points[0], data.points[1], data.points[2], data.points[3], data.points[4], data.points[5]); + points.push(point.x, point.y); + } + } + else { + // TODO: how can we calculate bezier curves better? + points = points.concat(data.points); + } + }); + var minX = points[0]; + var maxX = points[0]; + var minY = points[1]; + var maxY = points[1]; + var x, y; + for (var i = 0; i < points.length / 2; i++) { + x = points[i * 2]; + y = points[i * 2 + 1]; + // skip bad values + if (!isNaN(x)) { + minX = Math.min(minX, x); + maxX = Math.max(maxX, x); + } + if (!isNaN(y)) { + minY = Math.min(minY, y); + maxY = Math.max(maxY, y); + } + } + return { + x: Math.round(minX), + y: Math.round(minY), + width: Math.round(maxX - minX), + height: Math.round(maxY - minY), + }; + } + /** + * Return length of the path. + * @method + * @name Konva.Path#getLength + * @returns {Number} length + * @example + * var length = path.getLength(); + */ + getLength() { + return this.pathLength; + } + /** + * Get point on path at specific length of the path + * @method + * @name Konva.Path#getPointAtLength + * @param {Number} length length + * @returns {Object} point {x,y} point + * @example + * var point = path.getPointAtLength(10); + */ + getPointAtLength(length) { + var point, i = 0, ii = this.dataArray.length; + if (!ii) { + return null; + } + while (i < ii && length > this.dataArray[i].pathLength) { + length -= this.dataArray[i].pathLength; + ++i; + } + if (i === ii) { + point = this.dataArray[i - 1].points.slice(-2); + return { + x: point[0], + y: point[1], + }; + } + if (length < 0.01) { + point = this.dataArray[i].points.slice(0, 2); + return { + x: point[0], + y: point[1], + }; + } + var cp = this.dataArray[i]; + var p = cp.points; + switch (cp.command) { + case 'L': + return Path.getPointOnLine(length, cp.start.x, cp.start.y, p[0], p[1]); + case 'C': + return Path.getPointOnCubicBezier(length / cp.pathLength, cp.start.x, cp.start.y, p[0], p[1], p[2], p[3], p[4], p[5]); + case 'Q': + return Path.getPointOnQuadraticBezier(length / cp.pathLength, cp.start.x, cp.start.y, p[0], p[1], p[2], p[3]); + case 'A': + var cx = p[0], cy = p[1], rx = p[2], ry = p[3], theta = p[4], dTheta = p[5], psi = p[6]; + theta += (dTheta * length) / cp.pathLength; + return Path.getPointOnEllipticalArc(cx, cy, rx, ry, theta, psi); + } + return null; + } + static getLineLength(x1, y1, x2, y2) { + return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); + } + static getPointOnLine(dist, P1x, P1y, P2x, P2y, fromX, fromY) { + if (fromX === undefined) { + fromX = P1x; + } + if (fromY === undefined) { + fromY = P1y; + } + var m = (P2y - P1y) / (P2x - P1x + 0.00000001); + var run = Math.sqrt((dist * dist) / (1 + m * m)); + if (P2x < P1x) { + run *= -1; + } + var rise = m * run; + var pt; + if (P2x === P1x) { + // vertical line + pt = { + x: fromX, + y: fromY + rise, + }; + } + else if ((fromY - P1y) / (fromX - P1x + 0.00000001) === m) { + pt = { + x: fromX + run, + y: fromY + rise, + }; + } + else { + var ix, iy; + var len = this.getLineLength(P1x, P1y, P2x, P2y); + // if (len < 0.00000001) { + // return { + // x: P1x, + // y: P1y, + // }; + // } + var u = (fromX - P1x) * (P2x - P1x) + (fromY - P1y) * (P2y - P1y); + u = u / (len * len); + ix = P1x + u * (P2x - P1x); + iy = P1y + u * (P2y - P1y); + var pRise = this.getLineLength(fromX, fromY, ix, iy); + var pRun = Math.sqrt(dist * dist - pRise * pRise); + run = Math.sqrt((pRun * pRun) / (1 + m * m)); + if (P2x < P1x) { + run *= -1; + } + rise = m * run; + pt = { + x: ix + run, + y: iy + rise, + }; + } + return pt; + } + static getPointOnCubicBezier(pct, P1x, P1y, P2x, P2y, P3x, P3y, P4x, P4y) { + function CB1(t) { + return t * t * t; + } + function CB2(t) { + return 3 * t * t * (1 - t); + } + function CB3(t) { + return 3 * t * (1 - t) * (1 - t); + } + function CB4(t) { + return (1 - t) * (1 - t) * (1 - t); + } + var x = P4x * CB1(pct) + P3x * CB2(pct) + P2x * CB3(pct) + P1x * CB4(pct); + var y = P4y * CB1(pct) + P3y * CB2(pct) + P2y * CB3(pct) + P1y * CB4(pct); + return { + x: x, + y: y, + }; + } + static getPointOnQuadraticBezier(pct, P1x, P1y, P2x, P2y, P3x, P3y) { + function QB1(t) { + return t * t; + } + function QB2(t) { + return 2 * t * (1 - t); + } + function QB3(t) { + return (1 - t) * (1 - t); + } + var x = P3x * QB1(pct) + P2x * QB2(pct) + P1x * QB3(pct); + var y = P3y * QB1(pct) + P2y * QB2(pct) + P1y * QB3(pct); + return { + x: x, + y: y, + }; + } + static getPointOnEllipticalArc(cx, cy, rx, ry, theta, psi) { + var cosPsi = Math.cos(psi), sinPsi = Math.sin(psi); + var pt = { + x: rx * Math.cos(theta), + y: ry * Math.sin(theta), + }; + return { + x: cx + (pt.x * cosPsi - pt.y * sinPsi), + y: cy + (pt.x * sinPsi + pt.y * cosPsi), + }; + } + /* + * get parsed data array from the data + * string. V, v, H, h, and l data are converted to + * L data for the purpose of high performance Path + * rendering + */ + static parsePathData(data) { + // Path Data Segment must begin with a moveTo + //m (x y)+ Relative moveTo (subsequent points are treated as lineTo) + //M (x y)+ Absolute moveTo (subsequent points are treated as lineTo) + //l (x y)+ Relative lineTo + //L (x y)+ Absolute LineTo + //h (x)+ Relative horizontal lineTo + //H (x)+ Absolute horizontal lineTo + //v (y)+ Relative vertical lineTo + //V (y)+ Absolute vertical lineTo + //z (closepath) + //Z (closepath) + //c (x1 y1 x2 y2 x y)+ Relative Bezier curve + //C (x1 y1 x2 y2 x y)+ Absolute Bezier curve + //q (x1 y1 x y)+ Relative Quadratic Bezier + //Q (x1 y1 x y)+ Absolute Quadratic Bezier + //t (x y)+ Shorthand/Smooth Relative Quadratic Bezier + //T (x y)+ Shorthand/Smooth Absolute Quadratic Bezier + //s (x2 y2 x y)+ Shorthand/Smooth Relative Bezier curve + //S (x2 y2 x y)+ Shorthand/Smooth Absolute Bezier curve + //a (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Relative Elliptical Arc + //A (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Absolute Elliptical Arc + // return early if data is not defined + if (!data) { + return []; + } + // command string + var cs = data; + // command chars + var cc = [ + 'm', + 'M', + 'l', + 'L', + 'v', + 'V', + 'h', + 'H', + 'z', + 'Z', + 'c', + 'C', + 'q', + 'Q', + 't', + 'T', + 's', + 'S', + 'a', + 'A', + ]; + // convert white spaces to commas + cs = cs.replace(new RegExp(' ', 'g'), ','); + // create pipes so that we can split the data + for (var n = 0; n < cc.length; n++) { + cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]); + } + // create array + var arr = cs.split('|'); + var ca = []; + var coords = []; + // init context point + var cpx = 0; + var cpy = 0; + var re = /([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi; + var match; + for (n = 1; n < arr.length; n++) { + var str = arr[n]; + var c = str.charAt(0); + str = str.slice(1); + coords.length = 0; + while ((match = re.exec(str))) { + coords.push(match[0]); + } + // while ((match = re.exec(str))) { + // coords.push(match[0]); + // } + var p = []; + for (var j = 0, jlen = coords.length; j < jlen; j++) { + // extra case for merged flags + if (coords[j] === '00') { + p.push(0, 0); + continue; + } + var parsed = parseFloat(coords[j]); + if (!isNaN(parsed)) { + p.push(parsed); + } + else { + p.push(0); + } + } + while (p.length > 0) { + if (isNaN(p[0])) { + // case for a trailing comma before next command + break; + } + var cmd = null; + var points = []; + var startX = cpx, startY = cpy; + // Move var from within the switch to up here (jshint) + var prevCmd, ctlPtx, ctlPty; // Ss, Tt + var rx, ry, psi, fa, fs, x1, y1; // Aa + // convert l, H, h, V, and v to L + switch (c) { + // Note: Keep the lineTo's above the moveTo's in this switch + case 'l': + cpx += p.shift(); + cpy += p.shift(); + cmd = 'L'; + points.push(cpx, cpy); + break; + case 'L': + cpx = p.shift(); + cpy = p.shift(); + points.push(cpx, cpy); + break; + // Note: lineTo handlers need to be above this point + case 'm': + var dx = p.shift(); + var dy = p.shift(); + cpx += dx; + cpy += dy; + cmd = 'M'; + // After closing the path move the current position + // to the the first point of the path (if any). + if (ca.length > 2 && ca[ca.length - 1].command === 'z') { + for (var idx = ca.length - 2; idx >= 0; idx--) { + if (ca[idx].command === 'M') { + cpx = ca[idx].points[0] + dx; + cpy = ca[idx].points[1] + dy; + break; + } + } + } + points.push(cpx, cpy); + c = 'l'; + // subsequent points are treated as relative lineTo + break; + case 'M': + cpx = p.shift(); + cpy = p.shift(); + cmd = 'M'; + points.push(cpx, cpy); + c = 'L'; + // subsequent points are treated as absolute lineTo + break; + case 'h': + cpx += p.shift(); + cmd = 'L'; + points.push(cpx, cpy); + break; + case 'H': + cpx = p.shift(); + cmd = 'L'; + points.push(cpx, cpy); + break; + case 'v': + cpy += p.shift(); + cmd = 'L'; + points.push(cpx, cpy); + break; + case 'V': + cpy = p.shift(); + cmd = 'L'; + points.push(cpx, cpy); + break; + case 'C': + points.push(p.shift(), p.shift(), p.shift(), p.shift()); + cpx = p.shift(); + cpy = p.shift(); + points.push(cpx, cpy); + break; + case 'c': + points.push(cpx + p.shift(), cpy + p.shift(), cpx + p.shift(), cpy + p.shift()); + cpx += p.shift(); + cpy += p.shift(); + cmd = 'C'; + points.push(cpx, cpy); + break; + case 'S': + ctlPtx = cpx; + ctlPty = cpy; + prevCmd = ca[ca.length - 1]; + if (prevCmd.command === 'C') { + ctlPtx = cpx + (cpx - prevCmd.points[2]); + ctlPty = cpy + (cpy - prevCmd.points[3]); + } + points.push(ctlPtx, ctlPty, p.shift(), p.shift()); + cpx = p.shift(); + cpy = p.shift(); + cmd = 'C'; + points.push(cpx, cpy); + break; + case 's': + ctlPtx = cpx; + ctlPty = cpy; + prevCmd = ca[ca.length - 1]; + if (prevCmd.command === 'C') { + ctlPtx = cpx + (cpx - prevCmd.points[2]); + ctlPty = cpy + (cpy - prevCmd.points[3]); + } + points.push(ctlPtx, ctlPty, cpx + p.shift(), cpy + p.shift()); + cpx += p.shift(); + cpy += p.shift(); + cmd = 'C'; + points.push(cpx, cpy); + break; + case 'Q': + points.push(p.shift(), p.shift()); + cpx = p.shift(); + cpy = p.shift(); + points.push(cpx, cpy); + break; + case 'q': + points.push(cpx + p.shift(), cpy + p.shift()); + cpx += p.shift(); + cpy += p.shift(); + cmd = 'Q'; + points.push(cpx, cpy); + break; + case 'T': + ctlPtx = cpx; + ctlPty = cpy; + prevCmd = ca[ca.length - 1]; + if (prevCmd.command === 'Q') { + ctlPtx = cpx + (cpx - prevCmd.points[0]); + ctlPty = cpy + (cpy - prevCmd.points[1]); + } + cpx = p.shift(); + cpy = p.shift(); + cmd = 'Q'; + points.push(ctlPtx, ctlPty, cpx, cpy); + break; + case 't': + ctlPtx = cpx; + ctlPty = cpy; + prevCmd = ca[ca.length - 1]; + if (prevCmd.command === 'Q') { + ctlPtx = cpx + (cpx - prevCmd.points[0]); + ctlPty = cpy + (cpy - prevCmd.points[1]); + } + cpx += p.shift(); + cpy += p.shift(); + cmd = 'Q'; + points.push(ctlPtx, ctlPty, cpx, cpy); + break; + case 'A': + rx = p.shift(); + ry = p.shift(); + psi = p.shift(); + fa = p.shift(); + fs = p.shift(); + x1 = cpx; + y1 = cpy; + cpx = p.shift(); + cpy = p.shift(); + cmd = 'A'; + points = this.convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi); + break; + case 'a': + rx = p.shift(); + ry = p.shift(); + psi = p.shift(); + fa = p.shift(); + fs = p.shift(); + x1 = cpx; + y1 = cpy; + cpx += p.shift(); + cpy += p.shift(); + cmd = 'A'; + points = this.convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi); + break; + } + ca.push({ + command: cmd || c, + points: points, + start: { + x: startX, + y: startY, + }, + pathLength: this.calcLength(startX, startY, cmd || c, points), + }); + } + if (c === 'z' || c === 'Z') { + ca.push({ + command: 'z', + points: [], + start: undefined, + pathLength: 0, + }); + } + } + return ca; + } + static calcLength(x, y, cmd, points) { + var len, p1, p2, t; + var path = Path; + switch (cmd) { + case 'L': + return path.getLineLength(x, y, points[0], points[1]); + case 'C': + // Approximates by breaking curve into 100 line segments + len = 0.0; + p1 = path.getPointOnCubicBezier(0, x, y, points[0], points[1], points[2], points[3], points[4], points[5]); + for (t = 0.01; t <= 1; t += 0.01) { + p2 = path.getPointOnCubicBezier(t, x, y, points[0], points[1], points[2], points[3], points[4], points[5]); + len += path.getLineLength(p1.x, p1.y, p2.x, p2.y); + p1 = p2; + } + return len; + case 'Q': + // Approximates by breaking curve into 100 line segments + len = 0.0; + p1 = path.getPointOnQuadraticBezier(0, x, y, points[0], points[1], points[2], points[3]); + for (t = 0.01; t <= 1; t += 0.01) { + p2 = path.getPointOnQuadraticBezier(t, x, y, points[0], points[1], points[2], points[3]); + len += path.getLineLength(p1.x, p1.y, p2.x, p2.y); + p1 = p2; + } + return len; + case 'A': + // Approximates by breaking curve into line segments + len = 0.0; + var start = points[4]; + // 4 = theta + var dTheta = points[5]; + // 5 = dTheta + var end = points[4] + dTheta; + var inc = Math.PI / 180.0; + // 1 degree resolution + if (Math.abs(start - end) < inc) { + inc = Math.abs(start - end); + } + // Note: for purpose of calculating arc length, not going to worry about rotating X-axis by angle psi + p1 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], start, 0); + if (dTheta < 0) { + // clockwise + for (t = start - inc; t > end; t -= inc) { + p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0); + len += path.getLineLength(p1.x, p1.y, p2.x, p2.y); + p1 = p2; + } + } + else { + // counter-clockwise + for (t = start + inc; t < end; t += inc) { + p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0); + len += path.getLineLength(p1.x, p1.y, p2.x, p2.y); + p1 = p2; + } + } + p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], end, 0); + len += path.getLineLength(p1.x, p1.y, p2.x, p2.y); + return len; + } + return 0; + } + static convertEndpointToCenterParameterization(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg) { + // Derived from: http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes + var psi = psiDeg * (Math.PI / 180.0); + var xp = (Math.cos(psi) * (x1 - x2)) / 2.0 + (Math.sin(psi) * (y1 - y2)) / 2.0; + var yp = (-1 * Math.sin(psi) * (x1 - x2)) / 2.0 + + (Math.cos(psi) * (y1 - y2)) / 2.0; + var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry); + if (lambda > 1) { + rx *= Math.sqrt(lambda); + ry *= Math.sqrt(lambda); + } + var f = Math.sqrt((rx * rx * (ry * ry) - rx * rx * (yp * yp) - ry * ry * (xp * xp)) / + (rx * rx * (yp * yp) + ry * ry * (xp * xp))); + if (fa === fs) { + f *= -1; + } + if (isNaN(f)) { + f = 0; + } + var cxp = (f * rx * yp) / ry; + var cyp = (f * -ry * xp) / rx; + var cx = (x1 + x2) / 2.0 + Math.cos(psi) * cxp - Math.sin(psi) * cyp; + var cy = (y1 + y2) / 2.0 + Math.sin(psi) * cxp + Math.cos(psi) * cyp; + var vMag = function (v) { + return Math.sqrt(v[0] * v[0] + v[1] * v[1]); + }; + var vRatio = function (u, v) { + return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v)); + }; + var vAngle = function (u, v) { + return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v)); + }; + var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]); + var u = [(xp - cxp) / rx, (yp - cyp) / ry]; + var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry]; + var dTheta = vAngle(u, v); + if (vRatio(u, v) <= -1) { + dTheta = Math.PI; + } + if (vRatio(u, v) >= 1) { + dTheta = 0; + } + if (fs === 0 && dTheta > 0) { + dTheta = dTheta - 2 * Math.PI; + } + if (fs === 1 && dTheta < 0) { + dTheta = dTheta + 2 * Math.PI; + } + return [cx, cy, rx, ry, theta, dTheta, psi, fs]; + } + } + Path.prototype.className = 'Path'; + Path.prototype._attrsAffectingSize = ['data']; + _registerNode(Path); + /** + * get/set SVG path data string. This method + * also automatically parses the data string + * into a data array. Currently supported SVG data: + * M, m, L, l, H, h, V, v, Q, q, T, t, C, c, S, s, A, a, Z, z + * @name Konva.Path#data + * @method + * @param {String} data svg path string + * @returns {String} + * @example + * // get data + * var data = path.data(); + * + * // set data + * path.data('M200,100h100v50z'); + */ + Factory.addGetterSetter(Path, 'data'); + /** * Arrow constructor * @constructor @@ -10339,18 +11050,28 @@ if (fromTension) { tp = this.getTensionPoints(); } + var length = this.pointerLength(); var n = points.length; var dx, dy; if (fromTension) { - dx = points[n - 2] - (tp[tp.length - 2] + tp[tp.length - 4]) / 2; - dy = points[n - 1] - (tp[tp.length - 1] + tp[tp.length - 3]) / 2; + const lp = [ + tp[tp.length - 4], + tp[tp.length - 3], + tp[tp.length - 2], + tp[tp.length - 1], + points[n - 2], + points[n - 1], + ]; + const lastLength = Path.calcLength(tp[tp.length - 4], tp[tp.length - 3], 'C', lp); + const previous = Path.getPointOnQuadraticBezier(Math.min(1, 1 - length / lastLength), lp[0], lp[1], lp[2], lp[3], lp[4], lp[5]); + dx = points[n - 2] - previous.x; + dy = points[n - 1] - previous.y; } else { dx = points[n - 2] - points[n - 4]; dy = points[n - 1] - points[n - 3]; } var radians = (Math.atan2(dy, dx) + PI2) % PI2; - var length = this.pointerLength(); var width = this.pointerWidth(); if (this.pointerAtEnding()) { ctx.save(); @@ -11345,825 +12066,6 @@ */ Factory.addGetterSetter(Tag, 'cornerRadius', 0, getNumberOrArrayOfNumbersValidator(4)); - /** - * Path constructor. - * @author Jason Follas - * @constructor - * @memberof Konva - * @augments Konva.Shape - * @param {Object} config - * @param {String} config.data SVG data string - * @param {String} [config.fill] fill color - * @param {Image} [config.fillPatternImage] fill pattern image - * @param {Number} [config.fillPatternX] - * @param {Number} [config.fillPatternY] - * @param {Object} [config.fillPatternOffset] object with x and y component - * @param {Number} [config.fillPatternOffsetX] - * @param {Number} [config.fillPatternOffsetY] - * @param {Object} [config.fillPatternScale] object with x and y component - * @param {Number} [config.fillPatternScaleX] - * @param {Number} [config.fillPatternScaleY] - * @param {Number} [config.fillPatternRotation] - * @param {String} [config.fillPatternRepeat] can be "repeat", "repeat-x", "repeat-y", or "no-repeat". The default is "no-repeat" - * @param {Object} [config.fillLinearGradientStartPoint] object with x and y component - * @param {Number} [config.fillLinearGradientStartPointX] - * @param {Number} [config.fillLinearGradientStartPointY] - * @param {Object} [config.fillLinearGradientEndPoint] object with x and y component - * @param {Number} [config.fillLinearGradientEndPointX] - * @param {Number} [config.fillLinearGradientEndPointY] - * @param {Array} [config.fillLinearGradientColorStops] array of color stops - * @param {Object} [config.fillRadialGradientStartPoint] object with x and y component - * @param {Number} [config.fillRadialGradientStartPointX] - * @param {Number} [config.fillRadialGradientStartPointY] - * @param {Object} [config.fillRadialGradientEndPoint] object with x and y component - * @param {Number} [config.fillRadialGradientEndPointX] - * @param {Number} [config.fillRadialGradientEndPointY] - * @param {Number} [config.fillRadialGradientStartRadius] - * @param {Number} [config.fillRadialGradientEndRadius] - * @param {Array} [config.fillRadialGradientColorStops] array of color stops - * @param {Boolean} [config.fillEnabled] flag which enables or disables the fill. The default value is true - * @param {String} [config.fillPriority] can be color, linear-gradient, radial-graident, or pattern. The default value is color. The fillPriority property makes it really easy to toggle between different fill types. For example, if you want to toggle between a fill color style and a fill pattern style, simply set the fill property and the fillPattern properties, and then use setFillPriority('color') to render the shape with a color fill, or use setFillPriority('pattern') to render the shape with the pattern fill configuration - * @param {String} [config.stroke] stroke color - * @param {Number} [config.strokeWidth] stroke width - * @param {Boolean} [config.fillAfterStrokeEnabled]. Should we draw fill AFTER stroke? Default is false. - * @param {Number} [config.hitStrokeWidth] size of the stroke on hit canvas. The default is "auto" - equals to strokeWidth - * @param {Boolean} [config.strokeHitEnabled] flag which enables or disables stroke hit region. The default is true - * @param {Boolean} [config.perfectDrawEnabled] flag which enables or disables using buffer canvas. The default is true - * @param {Boolean} [config.shadowForStrokeEnabled] flag which enables or disables shadow for stroke. The default is true - * @param {Boolean} [config.strokeScaleEnabled] flag which enables or disables stroke scale. The default is true - * @param {Boolean} [config.strokeEnabled] flag which enables or disables the stroke. The default value is true - * @param {String} [config.lineJoin] can be miter, round, or bevel. The default - * is miter - * @param {String} [config.lineCap] can be butt, round, or square. The default - * is butt - * @param {String} [config.shadowColor] - * @param {Number} [config.shadowBlur] - * @param {Object} [config.shadowOffset] object with x and y component - * @param {Number} [config.shadowOffsetX] - * @param {Number} [config.shadowOffsetY] - * @param {Number} [config.shadowOpacity] shadow opacity. Can be any real number - * between 0 and 1 - * @param {Boolean} [config.shadowEnabled] flag which enables or disables the shadow. The default value is true - * @param {Array} [config.dash] - * @param {Boolean} [config.dashEnabled] flag which enables or disables the dashArray. The default value is true - - * @param {Number} [config.x] - * @param {Number} [config.y] - * @param {Number} [config.width] - * @param {Number} [config.height] - * @param {Boolean} [config.visible] - * @param {Boolean} [config.listening] whether or not the node is listening for events - * @param {String} [config.id] unique id - * @param {String} [config.name] non-unique name - * @param {Number} [config.opacity] determines node opacity. Can be any number between 0 and 1 - * @param {Object} [config.scale] set scale - * @param {Number} [config.scaleX] set scale x - * @param {Number} [config.scaleY] set scale y - * @param {Number} [config.rotation] rotation in degrees - * @param {Object} [config.offset] offset from center point and rotation point - * @param {Number} [config.offsetX] set offset x - * @param {Number} [config.offsetY] set offset y - * @param {Boolean} [config.draggable] makes the node draggable. When stages are draggable, you can drag and drop - * the entire stage by dragging any portion of the stage - * @param {Number} [config.dragDistance] - * @param {Function} [config.dragBoundFunc] - * @example - * var path = new Konva.Path({ - * x: 240, - * y: 40, - * data: 'M12.582,9.551C3.251,16.237,0.921,29.021,7.08,38.564l-2.36,1.689l4.893,2.262l4.893,2.262l-0.568-5.36l-0.567-5.359l-2.365,1.694c-4.657-7.375-2.83-17.185,4.352-22.33c7.451-5.338,17.817-3.625,23.156,3.824c5.337,7.449,3.625,17.813-3.821,23.152l2.857,3.988c9.617-6.893,11.827-20.277,4.935-29.896C35.591,4.87,22.204,2.658,12.582,9.551z', - * fill: 'green', - * scaleX: 2, - * scaleY: 2 - * }); - */ - class Path extends Shape { - constructor(config) { - super(config); - this.dataArray = []; - this.pathLength = 0; - this.dataArray = Path.parsePathData(this.data()); - this.pathLength = 0; - for (var i = 0; i < this.dataArray.length; ++i) { - this.pathLength += this.dataArray[i].pathLength; - } - this.on('dataChange.konva', function () { - this.dataArray = Path.parsePathData(this.data()); - this.pathLength = 0; - for (var i = 0; i < this.dataArray.length; ++i) { - this.pathLength += this.dataArray[i].pathLength; - } - }); - } - _sceneFunc(context) { - var ca = this.dataArray; - // context position - context.beginPath(); - var isClosed = false; - for (var n = 0; n < ca.length; n++) { - var c = ca[n].command; - var p = ca[n].points; - switch (c) { - case 'L': - context.lineTo(p[0], p[1]); - break; - case 'M': - context.moveTo(p[0], p[1]); - break; - case 'C': - context.bezierCurveTo(p[0], p[1], p[2], p[3], p[4], p[5]); - break; - case 'Q': - context.quadraticCurveTo(p[0], p[1], p[2], p[3]); - break; - case 'A': - var cx = p[0], cy = p[1], rx = p[2], ry = p[3], theta = p[4], dTheta = p[5], psi = p[6], fs = p[7]; - var r = rx > ry ? rx : ry; - var scaleX = rx > ry ? 1 : rx / ry; - var scaleY = rx > ry ? ry / rx : 1; - context.translate(cx, cy); - context.rotate(psi); - context.scale(scaleX, scaleY); - context.arc(0, 0, r, theta, theta + dTheta, 1 - fs); - context.scale(1 / scaleX, 1 / scaleY); - context.rotate(-psi); - context.translate(-cx, -cy); - break; - case 'z': - isClosed = true; - context.closePath(); - break; - } - } - if (!isClosed && !this.hasFill()) { - context.strokeShape(this); - } - else { - context.fillStrokeShape(this); - } - } - getSelfRect() { - var points = []; - this.dataArray.forEach(function (data) { - if (data.command === 'A') { - // Approximates by breaking curve into line segments - var start = data.points[4]; - // 4 = theta - var dTheta = data.points[5]; - // 5 = dTheta - var end = data.points[4] + dTheta; - var inc = Math.PI / 180.0; - // 1 degree resolution - if (Math.abs(start - end) < inc) { - inc = Math.abs(start - end); - } - if (dTheta < 0) { - // clockwise - for (let t = start - inc; t > end; t -= inc) { - const point = Path.getPointOnEllipticalArc(data.points[0], data.points[1], data.points[2], data.points[3], t, 0); - points.push(point.x, point.y); - } - } - else { - // counter-clockwise - for (let t = start + inc; t < end; t += inc) { - const point = Path.getPointOnEllipticalArc(data.points[0], data.points[1], data.points[2], data.points[3], t, 0); - points.push(point.x, point.y); - } - } - } - else if (data.command === 'C') { - // Approximates by breaking curve into 100 line segments - for (let t = 0.0; t <= 1; t += 0.01) { - const point = Path.getPointOnCubicBezier(t, data.start.x, data.start.y, data.points[0], data.points[1], data.points[2], data.points[3], data.points[4], data.points[5]); - points.push(point.x, point.y); - } - } - else { - // TODO: how can we calculate bezier curves better? - points = points.concat(data.points); - } - }); - var minX = points[0]; - var maxX = points[0]; - var minY = points[1]; - var maxY = points[1]; - var x, y; - for (var i = 0; i < points.length / 2; i++) { - x = points[i * 2]; - y = points[i * 2 + 1]; - // skip bad values - if (!isNaN(x)) { - minX = Math.min(minX, x); - maxX = Math.max(maxX, x); - } - if (!isNaN(y)) { - minY = Math.min(minY, y); - maxY = Math.max(maxY, y); - } - } - return { - x: Math.round(minX), - y: Math.round(minY), - width: Math.round(maxX - minX), - height: Math.round(maxY - minY), - }; - } - /** - * Return length of the path. - * @method - * @name Konva.Path#getLength - * @returns {Number} length - * @example - * var length = path.getLength(); - */ - getLength() { - return this.pathLength; - } - /** - * Get point on path at specific length of the path - * @method - * @name Konva.Path#getPointAtLength - * @param {Number} length length - * @returns {Object} point {x,y} point - * @example - * var point = path.getPointAtLength(10); - */ - getPointAtLength(length) { - var point, i = 0, ii = this.dataArray.length; - if (!ii) { - return null; - } - while (i < ii && length > this.dataArray[i].pathLength) { - length -= this.dataArray[i].pathLength; - ++i; - } - if (i === ii) { - point = this.dataArray[i - 1].points.slice(-2); - return { - x: point[0], - y: point[1], - }; - } - if (length < 0.01) { - point = this.dataArray[i].points.slice(0, 2); - return { - x: point[0], - y: point[1], - }; - } - var cp = this.dataArray[i]; - var p = cp.points; - switch (cp.command) { - case 'L': - return Path.getPointOnLine(length, cp.start.x, cp.start.y, p[0], p[1]); - case 'C': - return Path.getPointOnCubicBezier(length / cp.pathLength, cp.start.x, cp.start.y, p[0], p[1], p[2], p[3], p[4], p[5]); - case 'Q': - return Path.getPointOnQuadraticBezier(length / cp.pathLength, cp.start.x, cp.start.y, p[0], p[1], p[2], p[3]); - case 'A': - var cx = p[0], cy = p[1], rx = p[2], ry = p[3], theta = p[4], dTheta = p[5], psi = p[6]; - theta += (dTheta * length) / cp.pathLength; - return Path.getPointOnEllipticalArc(cx, cy, rx, ry, theta, psi); - } - return null; - } - static getLineLength(x1, y1, x2, y2) { - return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); - } - static getPointOnLine(dist, P1x, P1y, P2x, P2y, fromX, fromY) { - if (fromX === undefined) { - fromX = P1x; - } - if (fromY === undefined) { - fromY = P1y; - } - var m = (P2y - P1y) / (P2x - P1x + 0.00000001); - var run = Math.sqrt((dist * dist) / (1 + m * m)); - if (P2x < P1x) { - run *= -1; - } - var rise = m * run; - var pt; - if (P2x === P1x) { - // vertical line - pt = { - x: fromX, - y: fromY + rise, - }; - } - else if ((fromY - P1y) / (fromX - P1x + 0.00000001) === m) { - pt = { - x: fromX + run, - y: fromY + rise, - }; - } - else { - var ix, iy; - var len = this.getLineLength(P1x, P1y, P2x, P2y); - // if (len < 0.00000001) { - // return { - // x: P1x, - // y: P1y, - // }; - // } - var u = (fromX - P1x) * (P2x - P1x) + (fromY - P1y) * (P2y - P1y); - u = u / (len * len); - ix = P1x + u * (P2x - P1x); - iy = P1y + u * (P2y - P1y); - var pRise = this.getLineLength(fromX, fromY, ix, iy); - var pRun = Math.sqrt(dist * dist - pRise * pRise); - run = Math.sqrt((pRun * pRun) / (1 + m * m)); - if (P2x < P1x) { - run *= -1; - } - rise = m * run; - pt = { - x: ix + run, - y: iy + rise, - }; - } - return pt; - } - static getPointOnCubicBezier(pct, P1x, P1y, P2x, P2y, P3x, P3y, P4x, P4y) { - function CB1(t) { - return t * t * t; - } - function CB2(t) { - return 3 * t * t * (1 - t); - } - function CB3(t) { - return 3 * t * (1 - t) * (1 - t); - } - function CB4(t) { - return (1 - t) * (1 - t) * (1 - t); - } - var x = P4x * CB1(pct) + P3x * CB2(pct) + P2x * CB3(pct) + P1x * CB4(pct); - var y = P4y * CB1(pct) + P3y * CB2(pct) + P2y * CB3(pct) + P1y * CB4(pct); - return { - x: x, - y: y, - }; - } - static getPointOnQuadraticBezier(pct, P1x, P1y, P2x, P2y, P3x, P3y) { - function QB1(t) { - return t * t; - } - function QB2(t) { - return 2 * t * (1 - t); - } - function QB3(t) { - return (1 - t) * (1 - t); - } - var x = P3x * QB1(pct) + P2x * QB2(pct) + P1x * QB3(pct); - var y = P3y * QB1(pct) + P2y * QB2(pct) + P1y * QB3(pct); - return { - x: x, - y: y, - }; - } - static getPointOnEllipticalArc(cx, cy, rx, ry, theta, psi) { - var cosPsi = Math.cos(psi), sinPsi = Math.sin(psi); - var pt = { - x: rx * Math.cos(theta), - y: ry * Math.sin(theta), - }; - return { - x: cx + (pt.x * cosPsi - pt.y * sinPsi), - y: cy + (pt.x * sinPsi + pt.y * cosPsi), - }; - } - /* - * get parsed data array from the data - * string. V, v, H, h, and l data are converted to - * L data for the purpose of high performance Path - * rendering - */ - static parsePathData(data) { - // Path Data Segment must begin with a moveTo - //m (x y)+ Relative moveTo (subsequent points are treated as lineTo) - //M (x y)+ Absolute moveTo (subsequent points are treated as lineTo) - //l (x y)+ Relative lineTo - //L (x y)+ Absolute LineTo - //h (x)+ Relative horizontal lineTo - //H (x)+ Absolute horizontal lineTo - //v (y)+ Relative vertical lineTo - //V (y)+ Absolute vertical lineTo - //z (closepath) - //Z (closepath) - //c (x1 y1 x2 y2 x y)+ Relative Bezier curve - //C (x1 y1 x2 y2 x y)+ Absolute Bezier curve - //q (x1 y1 x y)+ Relative Quadratic Bezier - //Q (x1 y1 x y)+ Absolute Quadratic Bezier - //t (x y)+ Shorthand/Smooth Relative Quadratic Bezier - //T (x y)+ Shorthand/Smooth Absolute Quadratic Bezier - //s (x2 y2 x y)+ Shorthand/Smooth Relative Bezier curve - //S (x2 y2 x y)+ Shorthand/Smooth Absolute Bezier curve - //a (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Relative Elliptical Arc - //A (rx ry x-axis-rotation large-arc-flag sweep-flag x y)+ Absolute Elliptical Arc - // return early if data is not defined - if (!data) { - return []; - } - // command string - var cs = data; - // command chars - var cc = [ - 'm', - 'M', - 'l', - 'L', - 'v', - 'V', - 'h', - 'H', - 'z', - 'Z', - 'c', - 'C', - 'q', - 'Q', - 't', - 'T', - 's', - 'S', - 'a', - 'A', - ]; - // convert white spaces to commas - cs = cs.replace(new RegExp(' ', 'g'), ','); - // create pipes so that we can split the data - for (var n = 0; n < cc.length; n++) { - cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]); - } - // create array - var arr = cs.split('|'); - var ca = []; - var coords = []; - // init context point - var cpx = 0; - var cpy = 0; - var re = /([-+]?((\d+\.\d+)|((\d+)|(\.\d+)))(?:e[-+]?\d+)?)/gi; - var match; - for (n = 1; n < arr.length; n++) { - var str = arr[n]; - var c = str.charAt(0); - str = str.slice(1); - coords.length = 0; - while ((match = re.exec(str))) { - coords.push(match[0]); - } - // while ((match = re.exec(str))) { - // coords.push(match[0]); - // } - var p = []; - for (var j = 0, jlen = coords.length; j < jlen; j++) { - var parsed = parseFloat(coords[j]); - if (!isNaN(parsed)) { - p.push(parsed); - } - else { - p.push(0); - } - } - while (p.length > 0) { - if (isNaN(p[0])) { - // case for a trailing comma before next command - break; - } - var cmd = null; - var points = []; - var startX = cpx, startY = cpy; - // Move var from within the switch to up here (jshint) - var prevCmd, ctlPtx, ctlPty; // Ss, Tt - var rx, ry, psi, fa, fs, x1, y1; // Aa - // convert l, H, h, V, and v to L - switch (c) { - // Note: Keep the lineTo's above the moveTo's in this switch - case 'l': - cpx += p.shift(); - cpy += p.shift(); - cmd = 'L'; - points.push(cpx, cpy); - break; - case 'L': - cpx = p.shift(); - cpy = p.shift(); - points.push(cpx, cpy); - break; - // Note: lineTo handlers need to be above this point - case 'm': - var dx = p.shift(); - var dy = p.shift(); - cpx += dx; - cpy += dy; - cmd = 'M'; - // After closing the path move the current position - // to the the first point of the path (if any). - if (ca.length > 2 && ca[ca.length - 1].command === 'z') { - for (var idx = ca.length - 2; idx >= 0; idx--) { - if (ca[idx].command === 'M') { - cpx = ca[idx].points[0] + dx; - cpy = ca[idx].points[1] + dy; - break; - } - } - } - points.push(cpx, cpy); - c = 'l'; - // subsequent points are treated as relative lineTo - break; - case 'M': - cpx = p.shift(); - cpy = p.shift(); - cmd = 'M'; - points.push(cpx, cpy); - c = 'L'; - // subsequent points are treated as absolute lineTo - break; - case 'h': - cpx += p.shift(); - cmd = 'L'; - points.push(cpx, cpy); - break; - case 'H': - cpx = p.shift(); - cmd = 'L'; - points.push(cpx, cpy); - break; - case 'v': - cpy += p.shift(); - cmd = 'L'; - points.push(cpx, cpy); - break; - case 'V': - cpy = p.shift(); - cmd = 'L'; - points.push(cpx, cpy); - break; - case 'C': - points.push(p.shift(), p.shift(), p.shift(), p.shift()); - cpx = p.shift(); - cpy = p.shift(); - points.push(cpx, cpy); - break; - case 'c': - points.push(cpx + p.shift(), cpy + p.shift(), cpx + p.shift(), cpy + p.shift()); - cpx += p.shift(); - cpy += p.shift(); - cmd = 'C'; - points.push(cpx, cpy); - break; - case 'S': - ctlPtx = cpx; - ctlPty = cpy; - prevCmd = ca[ca.length - 1]; - if (prevCmd.command === 'C') { - ctlPtx = cpx + (cpx - prevCmd.points[2]); - ctlPty = cpy + (cpy - prevCmd.points[3]); - } - points.push(ctlPtx, ctlPty, p.shift(), p.shift()); - cpx = p.shift(); - cpy = p.shift(); - cmd = 'C'; - points.push(cpx, cpy); - break; - case 's': - ctlPtx = cpx; - ctlPty = cpy; - prevCmd = ca[ca.length - 1]; - if (prevCmd.command === 'C') { - ctlPtx = cpx + (cpx - prevCmd.points[2]); - ctlPty = cpy + (cpy - prevCmd.points[3]); - } - points.push(ctlPtx, ctlPty, cpx + p.shift(), cpy + p.shift()); - cpx += p.shift(); - cpy += p.shift(); - cmd = 'C'; - points.push(cpx, cpy); - break; - case 'Q': - points.push(p.shift(), p.shift()); - cpx = p.shift(); - cpy = p.shift(); - points.push(cpx, cpy); - break; - case 'q': - points.push(cpx + p.shift(), cpy + p.shift()); - cpx += p.shift(); - cpy += p.shift(); - cmd = 'Q'; - points.push(cpx, cpy); - break; - case 'T': - ctlPtx = cpx; - ctlPty = cpy; - prevCmd = ca[ca.length - 1]; - if (prevCmd.command === 'Q') { - ctlPtx = cpx + (cpx - prevCmd.points[0]); - ctlPty = cpy + (cpy - prevCmd.points[1]); - } - cpx = p.shift(); - cpy = p.shift(); - cmd = 'Q'; - points.push(ctlPtx, ctlPty, cpx, cpy); - break; - case 't': - ctlPtx = cpx; - ctlPty = cpy; - prevCmd = ca[ca.length - 1]; - if (prevCmd.command === 'Q') { - ctlPtx = cpx + (cpx - prevCmd.points[0]); - ctlPty = cpy + (cpy - prevCmd.points[1]); - } - cpx += p.shift(); - cpy += p.shift(); - cmd = 'Q'; - points.push(ctlPtx, ctlPty, cpx, cpy); - break; - case 'A': - rx = p.shift(); - ry = p.shift(); - psi = p.shift(); - fa = p.shift(); - fs = p.shift(); - x1 = cpx; - y1 = cpy; - cpx = p.shift(); - cpy = p.shift(); - cmd = 'A'; - points = this.convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi); - break; - case 'a': - rx = p.shift(); - ry = p.shift(); - psi = p.shift(); - fa = p.shift(); - fs = p.shift(); - x1 = cpx; - y1 = cpy; - cpx += p.shift(); - cpy += p.shift(); - cmd = 'A'; - points = this.convertEndpointToCenterParameterization(x1, y1, cpx, cpy, fa, fs, rx, ry, psi); - break; - } - ca.push({ - command: cmd || c, - points: points, - start: { - x: startX, - y: startY, - }, - pathLength: this.calcLength(startX, startY, cmd || c, points), - }); - } - if (c === 'z' || c === 'Z') { - ca.push({ - command: 'z', - points: [], - start: undefined, - pathLength: 0, - }); - } - } - return ca; - } - static calcLength(x, y, cmd, points) { - var len, p1, p2, t; - var path = Path; - switch (cmd) { - case 'L': - return path.getLineLength(x, y, points[0], points[1]); - case 'C': - // Approximates by breaking curve into 100 line segments - len = 0.0; - p1 = path.getPointOnCubicBezier(0, x, y, points[0], points[1], points[2], points[3], points[4], points[5]); - for (t = 0.01; t <= 1; t += 0.01) { - p2 = path.getPointOnCubicBezier(t, x, y, points[0], points[1], points[2], points[3], points[4], points[5]); - len += path.getLineLength(p1.x, p1.y, p2.x, p2.y); - p1 = p2; - } - return len; - case 'Q': - // Approximates by breaking curve into 100 line segments - len = 0.0; - p1 = path.getPointOnQuadraticBezier(0, x, y, points[0], points[1], points[2], points[3]); - for (t = 0.01; t <= 1; t += 0.01) { - p2 = path.getPointOnQuadraticBezier(t, x, y, points[0], points[1], points[2], points[3]); - len += path.getLineLength(p1.x, p1.y, p2.x, p2.y); - p1 = p2; - } - return len; - case 'A': - // Approximates by breaking curve into line segments - len = 0.0; - var start = points[4]; - // 4 = theta - var dTheta = points[5]; - // 5 = dTheta - var end = points[4] + dTheta; - var inc = Math.PI / 180.0; - // 1 degree resolution - if (Math.abs(start - end) < inc) { - inc = Math.abs(start - end); - } - // Note: for purpose of calculating arc length, not going to worry about rotating X-axis by angle psi - p1 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], start, 0); - if (dTheta < 0) { - // clockwise - for (t = start - inc; t > end; t -= inc) { - p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0); - len += path.getLineLength(p1.x, p1.y, p2.x, p2.y); - p1 = p2; - } - } - else { - // counter-clockwise - for (t = start + inc; t < end; t += inc) { - p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], t, 0); - len += path.getLineLength(p1.x, p1.y, p2.x, p2.y); - p1 = p2; - } - } - p2 = path.getPointOnEllipticalArc(points[0], points[1], points[2], points[3], end, 0); - len += path.getLineLength(p1.x, p1.y, p2.x, p2.y); - return len; - } - return 0; - } - static convertEndpointToCenterParameterization(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg) { - // Derived from: http://www.w3.org/TR/SVG/implnote.html#ArcImplementationNotes - var psi = psiDeg * (Math.PI / 180.0); - var xp = (Math.cos(psi) * (x1 - x2)) / 2.0 + (Math.sin(psi) * (y1 - y2)) / 2.0; - var yp = (-1 * Math.sin(psi) * (x1 - x2)) / 2.0 + - (Math.cos(psi) * (y1 - y2)) / 2.0; - var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry); - if (lambda > 1) { - rx *= Math.sqrt(lambda); - ry *= Math.sqrt(lambda); - } - var f = Math.sqrt((rx * rx * (ry * ry) - rx * rx * (yp * yp) - ry * ry * (xp * xp)) / - (rx * rx * (yp * yp) + ry * ry * (xp * xp))); - if (fa === fs) { - f *= -1; - } - if (isNaN(f)) { - f = 0; - } - var cxp = (f * rx * yp) / ry; - var cyp = (f * -ry * xp) / rx; - var cx = (x1 + x2) / 2.0 + Math.cos(psi) * cxp - Math.sin(psi) * cyp; - var cy = (y1 + y2) / 2.0 + Math.sin(psi) * cxp + Math.cos(psi) * cyp; - var vMag = function (v) { - return Math.sqrt(v[0] * v[0] + v[1] * v[1]); - }; - var vRatio = function (u, v) { - return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v)); - }; - var vAngle = function (u, v) { - return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v)); - }; - var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]); - var u = [(xp - cxp) / rx, (yp - cyp) / ry]; - var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry]; - var dTheta = vAngle(u, v); - if (vRatio(u, v) <= -1) { - dTheta = Math.PI; - } - if (vRatio(u, v) >= 1) { - dTheta = 0; - } - if (fs === 0 && dTheta > 0) { - dTheta = dTheta - 2 * Math.PI; - } - if (fs === 1 && dTheta < 0) { - dTheta = dTheta + 2 * Math.PI; - } - return [cx, cy, rx, ry, theta, dTheta, psi, fs]; - } - } - Path.prototype.className = 'Path'; - Path.prototype._attrsAffectingSize = ['data']; - _registerNode(Path); - /** - * get/set SVG path data string. This method - * also automatically parses the data string - * into a data array. Currently supported SVG data: - * M, m, L, l, H, h, V, v, Q, q, T, t, C, c, S, s, A, a, Z, z - * @name Konva.Path#data - * @method - * @param {String} data svg path string - * @returns {String} - * @example - * // get data - * var data = path.data(); - * - * // set data - * path.data('M200,100h100v50z'); - */ - Factory.addGetterSetter(Path, 'data'); - /** * Rect constructor * @constructor @@ -13916,14 +13818,13 @@ * @memberof Konva * @augments Konva.Shape * @param {Object} config - * @param {String} [config.fontFamily] default is Calibri + * @param {String} [config.fontFamily] default is Arial * @param {Number} [config.fontSize] default is 12 * @param {String} [config.fontStyle] can be normal, bold, or italic. Default is normal * @param {String} [config.fontVariant] can be normal or small-caps. Default is normal * @param {String} [config.textBaseline] Can be 'top', 'bottom', 'middle', 'alphabetic', 'hanging'. Default is middle * @param {String} config.text * @param {String} config.data SVG data string - * @param {Function} config.getKerning a getter for kerning values for the specified characters * @param {Function} config.kerningFunc a getter for kerning values for the specified characters * @param {String} [config.fill] fill color * @param {Image} [config.fillPatternImage] fill pattern image @@ -14039,10 +13940,6 @@ }); // update text data for certain attr changes this.on('textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva', this._setTextData); - if (config && config['getKerning']) { - Util.warn('getKerning TextPath API is deprecated. Please use "kerningFunc" instead.'); - this.kerningFunc(config['getKerning']); - } this._setTextData(); } _sceneFunc(context) { @@ -14594,8 +14491,8 @@ if (anchorName === 'rotater') { return 'crosshair'; } - rad += Util._degToRad(ANGLES[anchorName] || 0); - var angle = ((Util._radToDeg(rad) % 360) + 360) % 360; + rad += Util.degToRad(ANGLES[anchorName] || 0); + var angle = ((Util.radToDeg(rad) % 360) + 360) % 360; if (Util._inRange(angle, 315 + 22.5, 360) || Util._inRange(angle, 0, 22.5)) { // TOP return 'ns-resize'; @@ -14706,6 +14603,7 @@ * @param {Boolean} [config.keepRatio] Should we keep ratio when we are moving edges? Default is true * @param {Boolean} [config.centeredScaling] Should we resize relative to node's center? Default is false * @param {Array} [config.enabledAnchors] Array of names of enabled handles + * @param {Boolean} [config.flipEnabled] Can we flip/mirror shape on transform?. True by default * @param {Function} [config.boundBoxFunc] Bounding box function * @param {Function} [config.ignoreStroke] Should we ignore stroke size? Default is false * @@ -15288,6 +15186,7 @@ this.update(); return; } + const allowNegativeScale = this.flipEnabled(); var t = new Transform(); t.rotate(Konva$2.getAngle(this.rotation())); if (this._movingAnchorName && @@ -15303,6 +15202,10 @@ this._movingAnchorName = this._movingAnchorName.replace('left', 'right'); this._anchorDragOffset.x -= offset.x; this._anchorDragOffset.y -= offset.y; + if (!allowNegativeScale) { + this.update(); + return; + } } else if (this._movingAnchorName && newAttrs.width < 0 && @@ -15315,6 +15218,10 @@ this._anchorDragOffset.x -= offset.x; this._anchorDragOffset.y -= offset.y; newAttrs.width += this.padding() * 2; + if (!allowNegativeScale) { + this.update(); + return; + } } if (this._movingAnchorName && newAttrs.height < 0 && @@ -15329,6 +15236,10 @@ this._anchorDragOffset.x -= offset.x; this._anchorDragOffset.y -= offset.y; newAttrs.height += this.padding() * 2; + if (!allowNegativeScale) { + this.update(); + return; + } } else if (this._movingAnchorName && newAttrs.height < 0 && @@ -15341,6 +15252,10 @@ this._anchorDragOffset.x -= offset.x; this._anchorDragOffset.y -= offset.y; newAttrs.height += this.padding() * 2; + if (!allowNegativeScale) { + this.update(); + return; + } } if (this.boundBoxFunc()) { const bounded = this.boundBoxFunc()(oldAttrs, newAttrs); @@ -15575,6 +15490,20 @@ * transformer.enabledAnchors(['top-left', 'top-center', 'top-right', 'middle-right', 'middle-left', 'bottom-left', 'bottom-center', 'bottom-right']); */ Factory.addGetterSetter(Transformer, 'enabledAnchors', ANCHORS_NAMES, validateAnchors); + /** + * get/set flip enabled + * @name Konva.Transformer#flipEnabled + * @method + * @param {Boolean} flag + * @returns {Boolean} + * @example + * // get flip enabled property + * var flipEnabled = transformer.flipEnabled(); + * + * // set handlers + * transformer.flipEnabled(false); + */ + Factory.addGetterSetter(Transformer, 'flipEnabled', true, getBooleanValidator()); /** * get/set resize ability. If false it will automatically hide resizing handlers * @name Konva.Transformer#resizeEnabled diff --git a/konva.min.js b/konva.min.js index e7660c94..ced76c64 100644 --- a/konva.min.js +++ b/konva.min.js @@ -3,10 +3,10 @@ * Konva JavaScript Framework v7.2.5 * http://konvajs.org/ * Licensed under the MIT - * Date: Wed May 05 2021 + * Date: Sun May 09 2021 * * Original work Copyright (C) 2011 - 2013 by Eric Rowell (KineticJS) * Modified work Copyright (C) 2014 - present by Anton Lavrenov (Konva) * * @license - */var t=Math.PI/180;const e="undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope?self:{},i={_global:e,version:"7.2.5",isBrowser:"undefined"!=typeof window&&("[object Window]"==={}.toString.call(window)||"[object global]"==={}.toString.call(window)),isUnminified:/param/.test(function(t){}.toString()),dblClickWindow:400,getAngle:e=>i.angleDeg?e*t:e,enableTrace:!1,_pointerEventsEnabled:!1,autoDrawEnabled:!0,hitOnDragEnabled:!1,captureTouchEventsEnabled:!1,listenClickTap:!1,inDblClickWindow:!1,pixelRatio:"undefined"!=typeof window&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging:()=>i.DD.isDragging,isDragReady:()=>!!i.DD.node,document:e.document,_injectGlobal(t){e.Konva=t}},r=t=>{i[t.prototype.getClassName()]=t};i._injectGlobal(i);class a{constructor(t=[1,0,0,1,0,0]){this.dirty=!1,this.m=t&&t.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new a(this.m)}copyInto(t){t.m[0]=this.m[0],t.m[1]=this.m[1],t.m[2]=this.m[2],t.m[3]=this.m[3],t.m[4]=this.m[4],t.m[5]=this.m[5]}point(t){var e=this.m;return{x:e[0]*t.x+e[2]*t.y+e[4],y:e[1]*t.x+e[3]*t.y+e[5]}}translate(t,e){return this.m[4]+=this.m[0]*t+this.m[2]*e,this.m[5]+=this.m[1]*t+this.m[3]*e,this}scale(t,e){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=e,this.m[3]*=e,this}rotate(t){var e=Math.cos(t),i=Math.sin(t),r=this.m[0]*e+this.m[2]*i,a=this.m[1]*e+this.m[3]*i,n=this.m[0]*-i+this.m[2]*e,s=this.m[1]*-i+this.m[3]*e;return this.m[0]=r,this.m[1]=a,this.m[2]=n,this.m[3]=s,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(t,e){var i=this.m[0]+this.m[2]*e,r=this.m[1]+this.m[3]*e,a=this.m[2]+this.m[0]*t,n=this.m[3]+this.m[1]*t;return this.m[0]=i,this.m[1]=r,this.m[2]=a,this.m[3]=n,this}multiply(t){var e=this.m[0]*t.m[0]+this.m[2]*t.m[1],i=this.m[1]*t.m[0]+this.m[3]*t.m[1],r=this.m[0]*t.m[2]+this.m[2]*t.m[3],a=this.m[1]*t.m[2]+this.m[3]*t.m[3],n=this.m[0]*t.m[4]+this.m[2]*t.m[5]+this.m[4],s=this.m[1]*t.m[4]+this.m[3]*t.m[5]+this.m[5];return this.m[0]=e,this.m[1]=i,this.m[2]=r,this.m[3]=a,this.m[4]=n,this.m[5]=s,this}invert(){var t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),e=this.m[3]*t,i=-this.m[1]*t,r=-this.m[2]*t,a=this.m[0]*t,n=t*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),s=t*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=e,this.m[1]=i,this.m[2]=r,this.m[3]=a,this.m[4]=n,this.m[5]=s,this}getMatrix(){return this.m}setAbsolutePosition(t,e){var i=this.m[0],r=this.m[1],a=this.m[2],n=this.m[3],s=this.m[4],o=(i*(e-this.m[5])-r*(t-s))/(i*n-r*a),h=(t-s-a*o)/i;return this.translate(h,o)}decompose(){var t=this.m[0],e=this.m[1],i=this.m[2],r=this.m[3],a=t*r-e*i;let n={x:this.m[4],y:this.m[5],rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(0!=t||0!=e){var s=Math.sqrt(t*t+e*e);n.rotation=e>0?Math.acos(t/s):-Math.acos(t/s),n.scaleX=s,n.scaleY=a/s,n.skewX=(t*i+e*r)/a,n.skewY=0}else if(0!=i||0!=r){var o=Math.sqrt(i*i+r*r);n.rotation=Math.PI/2-(r>0?Math.acos(-i/o):-Math.acos(i/o)),n.scaleX=a/o,n.scaleY=o,n.skewX=0,n.skewY=(t*i+e*r)/a}return n.rotation=d._getRotation(n.rotation),n}}var n=Math.PI/180,s=180/Math.PI,o={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},h=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/,l=[];const d={_isElement:t=>!(!t||1!=t.nodeType),_isFunction:t=>!!(t&&t.constructor&&t.call&&t.apply),_isPlainObject:t=>!!t&&t.constructor===Object,_isArray:t=>"[object Array]"===Object.prototype.toString.call(t),_isNumber:t=>"[object Number]"===Object.prototype.toString.call(t)&&!isNaN(t)&&isFinite(t),_isString:t=>"[object String]"===Object.prototype.toString.call(t),_isBoolean:t=>"[object Boolean]"===Object.prototype.toString.call(t),isObject:t=>t instanceof Object,isValidSelector(t){if("string"!=typeof t)return!1;var e=t[0];return"#"===e||"."===e||e===e.toUpperCase()},_sign:t=>0===t||t>0?1:-1,requestAnimFrame(t){l.push(t);const e="undefined"!=typeof requestAnimationFrame&&requestAnimationFrame||function(t){setTimeout(t,60)};1===l.length&&e((function(){const t=l;l=[],t.forEach((function(t){t()}))}))},createCanvasElement(){var t=document.createElement("canvas");try{t.style=t.style||{}}catch(t){}return t},createImageElement:()=>document.createElement("img"),_isInDocument(t){for(;t=t.parentNode;)if(t==document)return!0;return!1},_simplifyArray(t){var e,i,r=[],a=t.length,n=d;for(e=0;e((1<<24)+(t<<16)+(e<<8)+i).toString(16).slice(1),_hexToRgb(t){t=t.replace("#","");var e=parseInt(t,16);return{r:e>>16&255,g:e>>8&255,b:255&e}},getRandomColor(){for(var t=(16777215*Math.random()<<0).toString(16);t.length<6;)t="0"+t;return"#"+t},get:(t,e)=>void 0===t?e:t,getRGB(t){var e;return t in o?{r:(e=o[t])[0],g:e[1],b:e[2]}:"#"===t[0]?this._hexToRgb(t.substring(1)):"rgb("===t.substr(0,4)?(e=h.exec(t.replace(/ /g,"")),{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}):{r:0,g:0,b:0}},colorToRGBA:t=>(t=t||"black",d._namedColorToRBA(t)||d._hex3ColorToRGBA(t)||d._hex6ColorToRGBA(t)||d._rgbColorToRGBA(t)||d._rgbaColorToRGBA(t)||d._hslColorToRGBA(t)),_namedColorToRBA(t){var e=o[t.toLowerCase()];return e?{r:e[0],g:e[1],b:e[2],a:1}:null},_rgbColorToRGBA(t){if(0===t.indexOf("rgb(")){var e=(t=t.match(/rgb\(([^)]+)\)/)[1]).split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:1}}},_rgbaColorToRGBA(t){if(0===t.indexOf("rgba(")){var e=(t=t.match(/rgba\(([^)]+)\)/)[1]).split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:e[3]}}},_hex6ColorToRGBA(t){if("#"===t[0]&&7===t.length)return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16),a:1}},_hex3ColorToRGBA(t){if("#"===t[0]&&4===t.length)return{r:parseInt(t[1]+t[1],16),g:parseInt(t[2]+t[2],16),b:parseInt(t[3]+t[3],16),a:1}},_hslColorToRGBA(t){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(t)){const[e,...i]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(t),r=Number(i[0])/360,a=Number(i[1])/100,n=Number(i[2])/100;let s,o,h;if(0===a)return h=255*n,{r:Math.round(h),g:Math.round(h),b:Math.round(h),a:1};s=n<.5?n*(1+a):n+a-n*a;const l=2*n-s,d=[0,0,0];for(let t=0;t<3;t++)o=r+1/3*-(t-1),o<0&&o++,o>1&&o--,h=6*o<1?l+6*(s-l)*o:2*o<1?s:3*o<2?l+(s-l)*(2/3-o)*6:l,d[t]=255*h;return{r:Math.round(d[0]),g:Math.round(d[1]),b:Math.round(d[2]),a:1}}},haveIntersection:(t,e)=>!(e.x>t.x+t.width||e.x+e.widtht.y+t.height||e.y+e.heightt.slice(0),_degToRad:t=>t*n,_radToDeg:t=>t*s,_getRotation:t=>i.angleDeg?d._radToDeg(t):t,_capitalize:t=>t.charAt(0).toUpperCase()+t.slice(1),throw(t){throw new Error("Konva error: "+t)},error(t){console.error("Konva error: "+t)},warn(t){i.showWarnings&&console.warn("Konva warning: "+t)},extend(t,e){function i(){this.constructor=t}i.prototype=e.prototype;var r=t.prototype;for(var a in t.prototype=new i,r)r.hasOwnProperty(a)&&(t.prototype[a]=r[a]);t.__super__=e.prototype,t.super=e},_getControlPoints(t,e,i,r,a,n,s){var o=Math.sqrt(Math.pow(i-t,2)+Math.pow(r-e,2)),h=Math.sqrt(Math.pow(a-i,2)+Math.pow(n-r,2)),l=s*o/(o+h),d=s*h/(o+h);return[i-l*(a-t),r-l*(n-e),i+d*(a-t),r+d*(n-e)]},_expandPoints(t,e){var i,r,a=t.length,n=[];for(i=2;ie<=t&&t1?(s=i,o=r,h=(i-a)*(i-a)+(r-n)*(r-n)):h=((s=t+d*(i-t))-a)*(s-a)+((o=e+d*(r-e))-n)*(o-n)}return[s,o,h]},_getProjectionToLine(t,e,i){var r=d.cloneObject(t),a=Number.MAX_VALUE;return e.forEach((function(n,s){if(i||s!==e.length-1){var o=e[(s+1)%e.length],h=d._getProjectionToSegment(n.x,n.y,o.x,o.y,t.x,t.y),l=h[0],c=h[1],g=h[2];ge.length){var s=e;e=t,t=s}for(r=0;rt.touches?t.changedTouches[0].identifier:999};function c(t){return d._isString(t)?'"'+t+'"':"[object Number]"===Object.prototype.toString.call(t)||d._isBoolean(t)?t:Object.prototype.toString.call(t)}function g(t){return t>255?255:t<0?0:Math.round(t)}function u(){if(i.isUnminified)return function(t,e){return d._isNumber(t)||d.warn(c(t)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),t}}function f(t){if(i.isUnminified)return function(e,i){let r=d._isNumber(e),a=d._isArray(e)&&e.length==t;return r||a||d.warn(c(e)+' is a not valid value for "'+i+'" attribute. The value should be a number or Array('+t+")"),e}}function p(){if(i.isUnminified)return function(t,e){return d._isNumber(t)||"auto"===t||d.warn(c(t)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),t}}function v(){if(i.isUnminified)return function(t,e){return d._isString(t)||d.warn(c(t)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),t}}function m(){if(i.isUnminified)return function(t,e){const i=d._isString(t),r="[object CanvasGradient]"===Object.prototype.toString.call(t)||t&&t.addColorStop;return i||r||d.warn(c(t)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),t}}function _(){if(i.isUnminified)return function(t,e){return!0===t||!1===t||d.warn(c(t)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),t}}const y={addGetterSetter(t,e,i,r,a){y.addGetter(t,e,i),y.addSetter(t,e,r,a),y.addOverloadedGetterSetter(t,e)},addGetter(t,e,i){var r="get"+d._capitalize(e);t.prototype[r]=t.prototype[r]||function(){var t=this.attrs[e];return void 0===t?i:t}},addSetter(t,e,i,r){var a="set"+d._capitalize(e);t.prototype[a]||y.overWriteSetter(t,e,i,r)},overWriteSetter(t,e,i,r){var a="set"+d._capitalize(e);t.prototype[a]=function(t){return i&&null!=t&&(t=i.call(this,t,e)),this._setAttr(e,t),r&&r.call(this),this}},addComponentsGetterSetter(t,e,r,a,n){var s,o,h=r.length,l=d._capitalize,g="get"+l(e),u="set"+l(e);t.prototype[g]=function(){var t={};for(s=0;s"number"==typeof t?Math.floor(t):t)),h+="("+n.join(",")+")")):(h+=r.property,t||(h+="="+r.val)),h+=";";return h}clearTrace(){this.traceArr=[]}_trace(t){var e=this.traceArr;e.push(t),e.length>=100&&e.shift()}reset(){var t=this.getCanvas().getPixelRatio();this.setTransform(1*t,0,0,1*t,0,0)}getCanvas(){return this.canvas}clear(t){var e=this.getCanvas();t?this.clearRect(t.x||0,t.y||0,t.width||0,t.height||0):this.clearRect(0,0,e.getWidth()/e.pixelRatio,e.getHeight()/e.pixelRatio)}_applyLineCap(t){var e=t.getLineCap();e&&this.setAttr("lineCap",e)}_applyOpacity(t){var e=t.getAbsoluteOpacity();1!==e&&this.setAttr("globalAlpha",e)}_applyLineJoin(t){var e=t.attrs.lineJoin;e&&this.setAttr("lineJoin",e)}setAttr(t,e){this._context[t]=e}arc(t,e,i,r,a,n){this._context.arc(t,e,i,r,a,n)}arcTo(t,e,i,r,a){this._context.arcTo(t,e,i,r,a)}beginPath(){this._context.beginPath()}bezierCurveTo(t,e,i,r,a,n){this._context.bezierCurveTo(t,e,i,r,a,n)}clearRect(t,e,i,r){this._context.clearRect(t,e,i,r)}clip(){this._context.clip()}closePath(){this._context.closePath()}createImageData(t,e){var i=arguments;return 2===i.length?this._context.createImageData(t,e):1===i.length?this._context.createImageData(t):void 0}createLinearGradient(t,e,i,r){return this._context.createLinearGradient(t,e,i,r)}createPattern(t,e){return this._context.createPattern(t,e)}createRadialGradient(t,e,i,r,a,n){return this._context.createRadialGradient(t,e,i,r,a,n)}drawImage(t,e,i,r,a,n,s,o,h){var l=arguments,d=this._context;3===l.length?d.drawImage(t,e,i):5===l.length?d.drawImage(t,e,i,r,a):9===l.length&&d.drawImage(t,e,i,r,a,n,s,o,h)}ellipse(t,e,i,r,a,n,s,o){this._context.ellipse(t,e,i,r,a,n,s,o)}isPointInPath(t,e){return this._context.isPointInPath(t,e)}fill(){this._context.fill()}fillRect(t,e,i,r){this._context.fillRect(t,e,i,r)}strokeRect(t,e,i,r){this._context.strokeRect(t,e,i,r)}fillText(t,e,i){this._context.fillText(t,e,i)}measureText(t){return this._context.measureText(t)}getImageData(t,e,i,r){return this._context.getImageData(t,e,i,r)}lineTo(t,e){this._context.lineTo(t,e)}moveTo(t,e){this._context.moveTo(t,e)}rect(t,e,i,r){this._context.rect(t,e,i,r)}putImageData(t,e,i){this._context.putImageData(t,e,i)}quadraticCurveTo(t,e,i,r){this._context.quadraticCurveTo(t,e,i,r)}restore(){this._context.restore()}rotate(t){this._context.rotate(t)}save(){this._context.save()}scale(t,e){this._context.scale(t,e)}setLineDash(t){this._context.setLineDash?this._context.setLineDash(t):"mozDash"in this._context?this._context.mozDash=t:"webkitLineDash"in this._context&&(this._context.webkitLineDash=t)}getLineDash(){return this._context.getLineDash()}setTransform(t,e,i,r,a,n){this._context.setTransform(t,e,i,r,a,n)}stroke(){this._context.stroke()}strokeText(t,e,i,r){this._context.strokeText(t,e,i,r)}transform(t,e,i,r,a,n){this._context.transform(t,e,i,r,a,n)}translate(t,e){this._context.translate(t,e)}_enableTrace(){var t,e,i=this,r=x.length,a=this.setAttr,n=function(t){var r,a=i[t];i[t]=function(){return e=d._simplifyArray(Array.prototype.slice.call(arguments,0)),r=a.apply(i,arguments),i._trace({method:t,args:e}),r}};for(t=0;t{"dragging"===e.dragStatus&&(t=!0)}),t},justDragged:!1,get node(){var t;return A._dragElements.forEach(e=>{t=e.node}),t},_dragElements:new Map,_drag(t){const e=[];A._dragElements.forEach((i,r)=>{const{node:a}=i,n=a.getStage();n.setPointersPositions(t),void 0===i.pointerId&&(i.pointerId=d._getFirstPointerId(t));const s=n._changedPointerPositions.find(t=>t.id===i.pointerId);if(s){if("dragging"!==i.dragStatus){var o=a.dragDistance();if(Math.max(Math.abs(s.x-i.startPointerPos.x),Math.abs(s.y-i.startPointerPos.y)){e.fire("dragmove",{type:"dragmove",target:e,evt:t},!0)})},_endDragBefore(t){A._dragElements.forEach((e,r)=>{const{node:a}=e,n=a.getStage();t&&n.setPointersPositions(t);if(!n._changedPointerPositions.find(t=>t.id===e.pointerId))return;"dragging"!==e.dragStatus&&"stopped"!==e.dragStatus||(A.justDragged=!0,i.listenClickTap=!1,e.dragStatus="stopped");const s=e.node.getLayer()||e.node instanceof i.Stage&&e.node;s&&s.batchDraw()})},_endDragAfter(t){A._dragElements.forEach((e,i)=>{"stopped"===e.dragStatus&&e.node.fire("dragend",{type:"dragend",target:e.node,evt:t},!0),"dragging"!==e.dragStatus&&A._dragElements.delete(i)})}};i.isBrowser&&(window.addEventListener("mouseup",A._endDragBefore,!0),window.addEventListener("touchend",A._endDragBefore,!0),window.addEventListener("mousemove",A._drag),window.addEventListener("touchmove",A._drag),window.addEventListener("mouseup",A._endDragAfter,!1),window.addEventListener("touchend",A._endDragAfter,!1));const M={},G={},E=function(t,e){t&&M[t]===e&&delete M[t]},R=function(t,e){e&&(G[e]||(G[e]=[]),G[e].push(t))},L=function(t,e){if(t){var i=G[t];if(i){for(var r=0;rt+"Change.konva").join(" ");this.on(i,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,i)}_getCanvasCache(){return this._cache.get("canvas")}_clearSelfAndDescendantCache(t){this._clearCache(t),"absoluteTransform"===t&&this.fire("absoluteTransformChange")}clearCache(){return this._cache.delete("canvas"),this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(t){var e=t||{},i={};void 0!==e.x&&void 0!==e.y&&void 0!==e.width&&void 0!==e.height||(i=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()}));var r=Math.ceil(e.width||i.width),a=Math.ceil(e.height||i.height),n=e.pixelRatio,s=void 0===e.x?i.x:e.x,o=void 0===e.y?i.y:e.y,h=e.offset||0,l=e.drawBorder||!1,c=e.hitCanvasPixelRatio||1;if(r&&a){s-=h,o-=h;var g=new k({pixelRatio:n,width:r+=2*h,height:a+=2*h}),u=new k({pixelRatio:n,width:0,height:0}),f=new T({pixelRatio:c,width:r,height:a}),p=g.getContext(),v=f.getContext();return f.isCache=!0,g.isCache=!0,this._cache.delete("canvas"),this._filterUpToDate=!1,!1===e.imageSmoothingEnabled&&(g.getContext()._context.imageSmoothingEnabled=!1,u.getContext()._context.imageSmoothingEnabled=!1),p.save(),v.save(),p.translate(-s,-o),v.translate(-s,-o),this._isUnderCache=!0,this._clearSelfAndDescendantCache("absoluteOpacity"),this._clearSelfAndDescendantCache("absoluteScale"),this.drawScene(g,this),this.drawHit(f,this),this._isUnderCache=!1,p.restore(),v.restore(),l&&(p.save(),p.beginPath(),p.rect(0,0,r,a),p.closePath(),p.setAttr("strokeStyle","red"),p.setAttr("lineWidth",5),p.stroke(),p.restore()),this._cache.set("canvas",{scene:g,filter:u,hit:f,x:s,y:o}),this._requestDraw(),this}d.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.")}isCached(){return this._cache.has("canvas")}getClientRect(t){throw new Error('abstract "getClientRect" method call')}_transformedRect(t,e){var i,r,a,n,s=[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x+t.width,y:t.y+t.height},{x:t.x,y:t.y+t.height}],o=this.getAbsoluteTransform(e);return s.forEach((function(t){var e=o.point(t);void 0===i&&(i=a=e.x,r=n=e.y),i=Math.min(i,e.x),r=Math.min(r,e.y),a=Math.max(a,e.x),n=Math.max(n,e.y)})),{x:i,y:r,width:a-i,height:n-r}}_drawCachedSceneCanvas(t){t.save(),t._applyOpacity(this),t._applyGlobalCompositeOperation(this);const e=this._getCanvasCache();t.translate(e.x,e.y);var i=this._getCachedSceneCanvas(),r=i.pixelRatio;t.drawImage(i._canvas,0,0,i.width/r,i.height/r),t.restore()}_drawCachedHitCanvas(t){var e=this._getCanvasCache(),i=e.hit;t.save(),t.translate(e.x,e.y),t.drawImage(i._canvas,0,0,i.width/i.pixelRatio,i.height/i.pixelRatio),t.restore()}_getCachedSceneCanvas(){var t,e,i,r,a=this.filters(),n=this._getCanvasCache(),s=n.scene,o=n.filter,h=o.getContext();if(a){if(!this._filterUpToDate){var l=s.pixelRatio;o.setSize(s.width/s.pixelRatio,s.height/s.pixelRatio);try{for(t=a.length,h.clear(),h.drawImage(s._canvas,0,0,s.getWidth()/l,s.getHeight()/l),e=h.getImageData(0,0,o.getWidth(),o.getHeight()),i=0;i{var e,i;if(!t)return this;for(e in t)"children"!==e&&(i="set"+d._capitalize(e),d._isFunction(this[i])?this[i](t[e]):this._setAttr(e,t[e]))}),this}isListening(){return this._getCache("listening",this._isListening)}_isListening(t){if(!this.listening())return!1;const e=this.getParent();return!e||e===t||this===t||e._isListening(t)}isVisible(){return this._getCache("visible",this._isVisible)}_isVisible(t){if(!this.visible())return!1;const e=this.getParent();return!e||e===t||this===t||e._isVisible(t)}shouldDrawHit(t,e=!1){if(t)return this._isVisible(t)&&this._isListening(t);var r=this.getLayer(),a=!1;A._dragElements.forEach(t=>{"dragging"===t.dragStatus&&("Stage"===t.node.nodeType||t.node.getLayer()===r)&&(a=!0)});var n=!e&&!i.hitOnDragEnabled&&a;return this.isListening()&&this.isVisible()&&!n}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){var t,e,i,r,a=this.getDepth(),n=this,s=0;return"Stage"!==n.nodeType&&function o(h){for(t=[],e=h.length,i=0;i0&&t[0].getDepth()<=a&&o(t)}(n.getStage().getChildren()),s}getDepth(){for(var t=0,e=this.parent;e;)t++,e=e.parent;return t}_batchTransformChanges(t){this._batchingTransformChange=!0,t(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")),this._needClearTransformCache=!1}setPosition(t){return this._batchTransformChanges(()=>{this.x(t.x),this.y(t.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getAbsolutePosition(t){let e=!1,i=this.parent;for(;i;){if(i.isCached()){e=!0;break}i=i.parent}e&&!t&&(t=!0);var r=this.getAbsoluteTransform(t).getMatrix(),n=new a,s=this.offset();return n.m=r.slice(),n.translate(s.x,s.y),n.getTranslation()}setAbsolutePosition(t){var e=this._clearTransform();this.attrs.x=e.x,this.attrs.y=e.y,delete e.x,delete e.y,this._clearCache("transform");var i=this._getAbsoluteTransform().copy();return i.invert(),i.translate(t.x,t.y),t={x:this.attrs.x+i.getTranslation().x,y:this.attrs.y+i.getTranslation().y},this._setTransform(e),this.setPosition({x:t.x,y:t.y}),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform"),this}_setTransform(t){var e;for(e in t)this.attrs[e]=t[e]}_clearTransform(){var t={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,t}move(t){var e=t.x,i=t.y,r=this.x(),a=this.y();return void 0!==e&&(r+=e),void 0!==i&&(a+=i),this.setPosition({x:r,y:a}),this}_eachAncestorReverse(t,e){var i,r,a=[],n=this.getParent();if(!e||e._id!==this._id){for(a.unshift(this);n&&(!e||n._id!==e._id);)a.unshift(n),n=n.parent;for(i=a.length,r=0;r0&&(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0)}moveToBottom(){if(!this.parent)return d.warn("Node has no parent. moveToBottom function is ignored."),!1;var t=this.index;return t>0&&(this.parent.children.splice(t,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0)}setZIndex(t){if(!this.parent)return d.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&d.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");var e=this.index;return this.parent.children.splice(e,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache("absoluteOpacity",this._getAbsoluteOpacity)}_getAbsoluteOpacity(){var t=this.opacity(),e=this.getParent();return e&&!e._isUnderCache&&(t*=e.getAbsoluteOpacity()),t}moveTo(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this}toObject(){var t,e,i,r,a={},n=this.getAttrs();for(t in a.attrs={},n)e=n[t],d.isObject(e)&&!d._isPlainObject(e)&&!d._isArray(e)||(i="function"==typeof this[t]&&this[t],delete n[t],r=i?i.call(this):null,n[t]=e,r!==e&&(a.attrs[t]=e));return a.className=this.getClassName(),d._prepareToStringify(a)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(t,e,i){var r=[];e&&this._isMatch(t)&&r.push(this);for(var a=this.parent;a;){if(a===i)return r;a._isMatch(t)&&r.push(a),a=a.parent}return r}isAncestorOf(t){return!1}findAncestor(t,e,i){return this.findAncestors(t,e,i)[0]}_isMatch(t){if(!t)return!1;if("function"==typeof t)return t(this);var e,i,r=t.replace(/ /g,"").split(","),a=r.length;for(e=0;e=0)&&!this.isDragging()){var e=!1;A._dragElements.forEach(t=>{this.isAncestorOf(t.node)&&(e=!0)}),e||this._createDragElement(t)}}))}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const t=A._dragElements.get(this._id),e=t&&"dragging"===t.dragStatus,i=t&&"ready"===t.dragStatus;e?this.stopDrag():i&&A._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}static create(t,e){return d._isString(t)&&(t=JSON.parse(t)),this._createNode(t,e)}static _createNode(t,e){var r,a,n,s=O.prototype.getClassName.call(t),o=t.children;e&&(t.attrs.container=e),i[s]||(d.warn('Can not find a node with class name "'+s+'". Fallback to "Shape".'),s="Shape");if(r=new(0,i[s])(t.attrs),o)for(a=o.length,n=0;n0}removeChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.remove()}),this.children=[],this}destroyChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.destroy()}),this.children=[],this}add(...t){if(arguments.length>1){for(var e=0;e0?e[0]:void 0}_generalFind(t,e){var i=[];return this._descendants(r=>{const a=r._isMatch(t);return a&&i.push(r),!(!a||!e)}),i}_descendants(t){let e=!1;const i=this.getChildren();for(const r of i){if(e=t(r),e)return!0;if(r.hasChildren()&&(e=r._descendants(t),e))return!0}return!1}toObject(){var t=O.prototype.toObject.call(this);return t.children=[],this.getChildren().forEach(e=>{t.children.push(e.toObject())}),t}isAncestorOf(t){for(var e=t.getParent();e;){if(e._id===this._id)return!0;e=e.getParent()}return!1}clone(t){var e=O.prototype.clone.call(this,t);return this.getChildren().forEach((function(t){e.add(t.clone())})),e}getAllIntersections(t){var e=[];return this.find("Shape").forEach((function(i){i.isVisible()&&i.intersects(t)&&e.push(i)})),e}_clearSelfAndDescendantCache(t){var e;super._clearSelfAndDescendantCache(t),this.isCached()||null===(e=this.children)||void 0===e||e.forEach((function(e){e._clearSelfAndDescendantCache(t)}))}_setChildrenIndices(){var t;null===(t=this.children)||void 0===t||t.forEach((function(t,e){t.index=e})),this._requestDraw()}drawScene(t,e){var i=this.getLayer(),r=t||i&&i.getCanvas(),a=r&&r.getContext(),n=this._getCanvasCache(),s=n&&n.scene,o=r&&r.isCache;if(!this.isVisible()&&!o)return this;if(s){a.save();var h=this.getAbsoluteTransform(e).getMatrix();a.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedSceneCanvas(a),a.restore()}else this._drawChildren("drawScene",r,e);return this}drawHit(t,e){if(!this.shouldDrawHit(e))return this;var i=this.getLayer(),r=t||i&&i.hitCanvas,a=r&&r.getContext(),n=this._getCanvasCache();if(n&&n.hit){a.save();var s=this.getAbsoluteTransform(e).getMatrix();a.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this._drawCachedHitCanvas(a),a.restore()}else this._drawChildren("drawHit",r,e);return this}_drawChildren(t,e,i){var r,a=e&&e.getContext(),n=this.clipWidth(),s=this.clipHeight(),o=this.clipFunc(),h=n&&s||o;const l=i===this;if(h){a.save();var d=this.getAbsoluteTransform(i),c=d.getMatrix();if(a.transform(c[0],c[1],c[2],c[3],c[4],c[5]),a.beginPath(),o)o.call(this,a,this);else{var g=this.clipX(),u=this.clipY();a.rect(g,u,n,s)}a.clip(),c=d.copy().invert().getMatrix(),a.transform(c[0],c[1],c[2],c[3],c[4],c[5])}var f=!l&&"source-over"!==this.globalCompositeOperation()&&"drawScene"===t;f&&(a.save(),a._applyGlobalCompositeOperation(this)),null===(r=this.children)||void 0===r||r.forEach((function(r){r[t](e,i)})),f&&a.restore(),h&&a.restore()}getClientRect(t){var e,i,r,a,n,s=(t=t||{}).skipTransform,o=t.relativeTo,h={x:1/0,y:1/0,width:0,height:0},l=this;null===(e=this.children)||void 0===e||e.forEach((function(e){if(e.visible()){var s=e.getClientRect({relativeTo:l,skipShadow:t.skipShadow,skipStroke:t.skipStroke});0===s.width&&0===s.height||(void 0===i?(i=s.x,r=s.y,a=s.x+s.width,n=s.y+s.height):(i=Math.min(i,s.x),r=Math.min(r,s.y),a=Math.max(a,s.x+s.width),n=Math.max(n,s.y+s.height)))}}));for(var d=this.find("Shape"),c=!1,g=0;g{Q(this.attrs)}),this._checkVisibility()}_validateAdd(t){const e="Layer"===t.getType(),i="FastLayer"===t.getType();e||i||d.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const t=this.visible()?"":"none";this.content.style.display=t}setContainer(t){if("string"==typeof t){if("."===t.charAt(0)){var e=t.slice(1);t=document.getElementsByClassName(e)[0]}else{var i;i="#"!==t.charAt(0)?t:t.slice(1),t=document.getElementById(i)}if(!t)throw"Can not find container in document with id "+i}return this._setAttr("container",t),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),t.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){var t,e=this.children,i=e.length;for(t=0;t-1&&V.splice(e,1),this}getPointerPosition(){const t=this._pointerPositions[0]||this._changedPointerPositions[0];return t?{x:t.x,y:t.y}:(d.warn("Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);"),null)}_getPointerById(t){return this._pointerPositions.find(e=>e.id===t)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(t){(t=t||{}).x=t.x||0,t.y=t.y||0,t.width=t.width||this.width(),t.height=t.height||this.height();var e=new k({width:t.width,height:t.height,pixelRatio:t.pixelRatio||1}),i=e.getContext()._context,r=this.children;return(t.x||t.y)&&i.translate(-1*t.x,-1*t.y),r.forEach((function(e){if(e.isVisible()){var r=e._toKonvaCanvas(t);i.drawImage(r._canvas,t.x,t.y,r.getWidth()/r.getPixelRatio(),r.getHeight()/r.getPixelRatio())}})),e}getIntersection(t,e){if(!t)return null;var i,r=this.children;for(i=r.length-1;i>=0;i--){const a=r[i].getIntersection(t,e);if(a)return a}return null}_resizeDOM(){var t=this.width(),e=this.height();this.content&&(this.content.style.width=t+"px",this.content.style.height=e+"px"),this.bufferCanvas.setSize(t,e),this.bufferHitCanvas.setSize(t,e),this.children.forEach(i=>{i.setSize({width:t,height:e}),i.draw()})}add(t,...e){if(arguments.length>1){for(var r=0;r5&&d.warn("The stage has "+a+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),t.setSize({width:this.width(),height:this.height()}),t.draw(),i.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return Y(t,this)}setPointerCapture(t){X(t,this)}releaseCapture(t){j(t)}getLayers(){return this.children}_bindContentEvents(){if(i.isBrowser)for(var t=0;t{var a=this.getIntersection(r);i.listenClickTap=!0,A.justDragged=!1;a&&a.isListening()&&(i.captureTouchEventsEnabled&&a.setPointerCapture(r.id),this.tapStartShape=a,a._fireAndBubble("touchstart",{evt:t,pointerId:r.id},this),e=!0,a.isListening()&&a.preventDefault()&&t.cancelable&&t.preventDefault())}),e||this._fire("touchstart",{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),this._fire("contentTouchstart",{evt:t})}_touchmove(t){if(this.setPointersPositions(t),!A.isDragging||i.hitOnDragEnabled){var e=!1,r={};this._changedPointerPositions.forEach(i=>{const a=W(i.id)||this.getIntersection(i);a&&a.isListening()&&(r[a._id]||(r[a._id]=!0,a._fireAndBubble("touchmove",{evt:t,pointerId:i.id}),e=!0,a.isListening()&&a.preventDefault()&&t.cancelable&&t.preventDefault()))}),e||this._fire("touchmove",{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),this._fire("contentTouchmove",{evt:t})}A.isDragging&&A.node.preventDefault()&&t.cancelable&&t.preventDefault()}_touchend(t){this.setPointersPositions(t);var e=this.tapEndShape,r=!1;i.inDblClickWindow?(r=!0,clearTimeout(this.dblTimeout)):A.justDragged||(i.inDblClickWindow=!0,clearTimeout(this.dblTimeout)),this.dblTimeout=setTimeout((function(){i.inDblClickWindow=!1}),i.dblClickWindow);var a=!1,n={},s=!1,o=!1;this._changedPointerPositions.forEach(h=>{var l=W(h.id)||this.getIntersection(h);l&&l.releaseCapture(h.id);l&&l.isListening()&&(n[l._id]||(n[l._id]=!0,this.tapEndShape=l,l._fireAndBubble("touchend",{evt:t,pointerId:h.id}),a=!0,i.listenClickTap&&l===this.tapStartShape&&(s=!0,l._fireAndBubble("tap",{evt:t,pointerId:h.id}),r&&e&&e===l&&(o=!0,l._fireAndBubble("dbltap",{evt:t,pointerId:h.id}))),l.isListening()&&l.preventDefault()&&t.cancelable&&t.preventDefault()))}),a||this._fire("touchend",{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),i.listenClickTap&&!s&&(this.tapEndShape=null,this._fire("tap",{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})),r&&!o&&this._fire("dbltap",{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),this._fire("contentTouchend",{evt:t}),i.listenClickTap&&(this._fire("contentTap",{evt:t}),r&&this._fire("contentDbltap",{evt:t})),this.preventDefault()&&t.cancelable&&t.preventDefault(),i.listenClickTap=!1}_wheel(t){this.setPointersPositions(t);var e=this.getIntersection(this.getPointerPosition());e&&e.isListening()?e._fireAndBubble("wheel",{evt:t}):this._fire("wheel",{evt:t,target:this,currentTarget:this}),this._fire("contentWheel",{evt:t})}_pointerdown(t){if(!i._pointerEventsEnabled)return;this.setPointersPositions(t);const e=W(t.pointerId)||this.getIntersection(this.getPointerPosition());e&&e._fireAndBubble("pointerdown",H(t))}_pointermove(t){if(!i._pointerEventsEnabled)return;this.setPointersPositions(t);const e=W(t.pointerId)||this.getIntersection(this.getPointerPosition());e&&e._fireAndBubble("pointermove",H(t))}_pointerup(t){if(!i._pointerEventsEnabled)return;this.setPointersPositions(t);const e=W(t.pointerId)||this.getIntersection(this.getPointerPosition());e&&e._fireAndBubble("pointerup",H(t)),j(t.pointerId)}_pointercancel(t){if(!i._pointerEventsEnabled)return;this.setPointersPositions(t);const e=W(t.pointerId)||this.getIntersection(this.getPointerPosition());e&&e._fireAndBubble("pointerup",H(t)),j(t.pointerId)}_lostpointercapture(t){j(t.pointerId)}setPointersPositions(t){var e=this._getContentPosition(),i=null,r=null;void 0!==(t=t||window.event).touches?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(t.touches,t=>{this._pointerPositions.push({id:t.identifier,x:(t.clientX-e.left)/e.scaleX,y:(t.clientY-e.top)/e.scaleY})}),Array.prototype.forEach.call(t.changedTouches||t.touches,t=>{this._changedPointerPositions.push({id:t.identifier,x:(t.clientX-e.left)/e.scaleX,y:(t.clientY-e.top)/e.scaleY})})):(i=(t.clientX-e.left)/e.scaleX,r=(t.clientY-e.top)/e.scaleY,this.pointerPos={x:i,y:r},this._pointerPositions=[{x:i,y:r,id:d._getFirstPointerId(t)}],this._changedPointerPositions=[{x:i,y:r,id:d._getFirstPointerId(t)}])}_setPointerPosition(t){d.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(t)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};var t=this.content.getBoundingClientRect();return{top:t.top,left:t.left,scaleX:t.width/this.content.clientWidth||1,scaleY:t.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new k({width:this.width(),height:this.height()}),this.bufferHitCanvas=new T({pixelRatio:1,width:this.width(),height:this.height()}),i.isBrowser){var t=this.container();if(!t)throw"Stage has no container. A container is required.";t.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),t.appendChild(this.content),this._resizeDOM()}}cache(){return d.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach((function(t){t.batchDraw()})),this}}J.prototype.nodeType="Stage",r(J),y.addGetterSetter(J,"container");let Z;function $(){return Z||(Z=d.createCanvasElement().getContext("2d"),Z)}const tt={};class et extends O{constructor(t){let e;for(super(t);e=d.getRandomColor(),!e||e in tt;);this.colorKey=e,tt[e]=this}getContext(){return this.getLayer().getContext()}getCanvas(){return this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache("hasShadow",this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&0!==this.shadowOpacity()&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache("patternImage",this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const t=$().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");return t&&t.setTransform&&t.setTransform({a:this.fillPatternScaleX(),b:0,c:0,d:this.fillPatternScaleY(),e:0,f:0}),t}}_getLinearGradient(){return this._getCache("linearGradient",this.__getLinearGradient)}__getLinearGradient(){var t=this.fillLinearGradientColorStops();if(t){for(var e=$(),i=this.fillLinearGradientStartPoint(),r=this.fillLinearGradientEndPoint(),a=e.createLinearGradient(i.x,i.y,r.x,r.y),n=0;nthis.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!(!this.stroke()&&!this.strokeLinearGradientColorStops()))}hasHitStroke(){const t=this.hitStrokeWidth();return"auto"===t?this.hasStroke():this.strokeEnabled()&&!!t}intersects(t){var e=this.getStage().bufferHitCanvas;return e.getContext().clear(),this.drawHit(e,null,!0),e.context.getImageData(Math.round(t.x),Math.round(t.y),1,1).data[3]>0}destroy(){return O.prototype.destroy.call(this),delete tt[this.colorKey],delete this.colorKey,this}_useBufferCanvas(t){var e;if(!this.getStage())return!1;if(!(null===(e=this.attrs.perfectDrawEnabled)||void 0===e||e))return!1;const i=t||this.hasFill(),r=this.hasStroke(),a=1!==this.getAbsoluteOpacity();if(i&&r&&a)return!0;const n=this.hasShadow(),s=this.shadowForStrokeEnabled();return!!(i&&r&&n&&s)}setStrokeHitEnabled(t){d.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),t?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return 0!==this.hitStrokeWidth()}getSelfRect(){var t=this.size();return{x:this._centroid?-t.width/2:0,y:this._centroid?-t.height/2:0,width:t.width,height:t.height}}getClientRect(t={}){const e=t.skipTransform,i=t.relativeTo,r=this.getSelfRect(),a=!t.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,n=r.width+a,s=r.height+a,o=!t.skipShadow&&this.hasShadow(),h=o?this.shadowOffsetX():0,l=o?this.shadowOffsetY():0,d=n+Math.abs(h),c=s+Math.abs(l),g=o&&this.shadowBlur()||0,u=d+2*g,f=c+2*g;let p=0;Math.round(a/2)!==a/2&&(p=1);const v={width:u+p,height:f+p,x:-Math.round(a/2+g)+Math.min(h,0)+r.x,y:-Math.round(a/2+g)+Math.min(l,0)+r.y};return e?v:this._transformedRect(v,i)}drawScene(t,e){var i,r,a=this.getLayer(),n=t||a.getCanvas(),s=n.getContext(),o=this._getCanvasCache(),h=this.getSceneFunc(),l=this.hasShadow(),d=n.isCache,c=n.isCache,g=e===this;if(!this.isVisible()&&!d)return this;if(o){s.save();var u=this.getAbsoluteTransform(e).getMatrix();return s.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(s),s.restore(),this}if(!h)return this;if(s.save(),this._useBufferCanvas()&&!c){(r=(i=this.getStage().bufferCanvas).getContext()).clear(),r.save(),r._applyLineJoin(this);var f=this.getAbsoluteTransform(e).getMatrix();r.transform(f[0],f[1],f[2],f[3],f[4],f[5]),h.call(this,r,this),r.restore();var p=i.pixelRatio;l&&s._applyShadow(this),s._applyOpacity(this),s._applyGlobalCompositeOperation(this),s.drawImage(i._canvas,0,0,i.width/p,i.height/p)}else{if(s._applyLineJoin(this),!g){f=this.getAbsoluteTransform(e).getMatrix();s.transform(f[0],f[1],f[2],f[3],f[4],f[5]),s._applyOpacity(this),s._applyGlobalCompositeOperation(this)}l&&s._applyShadow(this),h.call(this,s,this)}return s.restore(),this}drawHit(t,e,i=!1){if(!this.shouldDrawHit(e,i))return this;var r=this.getLayer(),a=t||r.hitCanvas,n=a&&a.getContext(),s=this.hitFunc()||this.sceneFunc(),o=this._getCanvasCache(),h=o&&o.hit;if(this.colorKey||d.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),h){n.save();var l=this.getAbsoluteTransform(e).getMatrix();return n.transform(l[0],l[1],l[2],l[3],l[4],l[5]),this._drawCachedHitCanvas(n),n.restore(),this}if(!s)return this;n.save(),n._applyLineJoin(this);if(!(this===e)){var c=this.getAbsoluteTransform(e).getMatrix();n.transform(c[0],c[1],c[2],c[3],c[4],c[5])}return s.call(this,n,this),n.restore(),this}drawHitFromCache(t=0){var e,i,r,a,n,s=this._getCanvasCache(),o=this._getCachedSceneCanvas(),h=s.hit,l=h.getContext(),c=h.getWidth(),g=h.getHeight();l.clear(),l.drawImage(o._canvas,0,0,c,g);try{for(r=(i=(e=l.getImageData(0,0,c,g)).data).length,a=d._hexToRgb(this.colorKey),n=0;nt?(i[n]=a.r,i[n+1]=a.g,i[n+2]=a.b,i[n+3]=255):i[n+3]=0;l.putImageData(e,0,0)}catch(t){d.error("Unable to draw hit graph from cached scene canvas. "+t.message)}return this}hasPointerCapture(t){return Y(t,this)}setPointerCapture(t){X(t,this)}releaseCapture(t){j(t)}}et.prototype._fillFunc=function(t){t.fill()},et.prototype._strokeFunc=function(t){t.stroke()},et.prototype._fillFuncHit=function(t){t.fill()},et.prototype._strokeFuncHit=function(t){t.stroke()},et.prototype._centroid=!1,et.prototype.nodeType="Shape",r(et),et.prototype.eventListeners={},et.prototype.on.call(et.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",(function(){this._clearCache("hasShadow")})),et.prototype.on.call(et.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",(function(){this._clearCache("shadowRGBA")})),et.prototype.on.call(et.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva",(function(){this._clearCache("patternImage")})),et.prototype.on.call(et.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",(function(){this._clearCache("linearGradient")})),et.prototype.on.call(et.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",(function(){this._clearCache("radialGradient")})),y.addGetterSetter(et,"stroke",void 0,m()),y.addGetterSetter(et,"strokeWidth",2,u()),y.addGetterSetter(et,"fillAfterStrokeEnabled",!1),y.addGetterSetter(et,"hitStrokeWidth","auto",p()),y.addGetterSetter(et,"strokeHitEnabled",!0,_()),y.addGetterSetter(et,"perfectDrawEnabled",!0,_()),y.addGetterSetter(et,"shadowForStrokeEnabled",!0,_()),y.addGetterSetter(et,"lineJoin"),y.addGetterSetter(et,"lineCap"),y.addGetterSetter(et,"sceneFunc"),y.addGetterSetter(et,"hitFunc"),y.addGetterSetter(et,"dash"),y.addGetterSetter(et,"dashOffset",0,u()),y.addGetterSetter(et,"shadowColor",void 0,v()),y.addGetterSetter(et,"shadowBlur",0,u()),y.addGetterSetter(et,"shadowOpacity",1,u()),y.addComponentsGetterSetter(et,"shadowOffset",["x","y"]),y.addGetterSetter(et,"shadowOffsetX",0,u()),y.addGetterSetter(et,"shadowOffsetY",0,u()),y.addGetterSetter(et,"fillPatternImage"),y.addGetterSetter(et,"fill",void 0,m()),y.addGetterSetter(et,"fillPatternX",0,u()),y.addGetterSetter(et,"fillPatternY",0,u()),y.addGetterSetter(et,"fillLinearGradientColorStops"),y.addGetterSetter(et,"strokeLinearGradientColorStops"),y.addGetterSetter(et,"fillRadialGradientStartRadius",0),y.addGetterSetter(et,"fillRadialGradientEndRadius",0),y.addGetterSetter(et,"fillRadialGradientColorStops"),y.addGetterSetter(et,"fillPatternRepeat","repeat"),y.addGetterSetter(et,"fillEnabled",!0),y.addGetterSetter(et,"strokeEnabled",!0),y.addGetterSetter(et,"shadowEnabled",!0),y.addGetterSetter(et,"dashEnabled",!0),y.addGetterSetter(et,"strokeScaleEnabled",!0),y.addGetterSetter(et,"fillPriority","color"),y.addComponentsGetterSetter(et,"fillPatternOffset",["x","y"]),y.addGetterSetter(et,"fillPatternOffsetX",0,u()),y.addGetterSetter(et,"fillPatternOffsetY",0,u()),y.addComponentsGetterSetter(et,"fillPatternScale",["x","y"]),y.addGetterSetter(et,"fillPatternScaleX",1,u()),y.addGetterSetter(et,"fillPatternScaleY",1,u()),y.addComponentsGetterSetter(et,"fillLinearGradientStartPoint",["x","y"]),y.addComponentsGetterSetter(et,"strokeLinearGradientStartPoint",["x","y"]),y.addGetterSetter(et,"fillLinearGradientStartPointX",0),y.addGetterSetter(et,"strokeLinearGradientStartPointX",0),y.addGetterSetter(et,"fillLinearGradientStartPointY",0),y.addGetterSetter(et,"strokeLinearGradientStartPointY",0),y.addComponentsGetterSetter(et,"fillLinearGradientEndPoint",["x","y"]),y.addComponentsGetterSetter(et,"strokeLinearGradientEndPoint",["x","y"]),y.addGetterSetter(et,"fillLinearGradientEndPointX",0),y.addGetterSetter(et,"strokeLinearGradientEndPointX",0),y.addGetterSetter(et,"fillLinearGradientEndPointY",0),y.addGetterSetter(et,"strokeLinearGradientEndPointY",0),y.addComponentsGetterSetter(et,"fillRadialGradientStartPoint",["x","y"]),y.addGetterSetter(et,"fillRadialGradientStartPointX",0),y.addGetterSetter(et,"fillRadialGradientStartPointY",0),y.addComponentsGetterSetter(et,"fillRadialGradientEndPoint",["x","y"]),y.addGetterSetter(et,"fillRadialGradientEndPointX",0),y.addGetterSetter(et,"fillRadialGradientEndPointY",0),y.addGetterSetter(et,"fillPatternRotation",0),y.backCompat(et,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});var it=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],rt=it.length;class at extends B{constructor(t){super(t),this.canvas=new k,this.hitCanvas=new T({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(t){return this.getContext().clear(t),this.getHitCanvas().getContext().clear(t),this}setZIndex(t){super.setZIndex(t);var e=this.getStage();return e&&e.content&&(e.content.removeChild(this.getNativeCanvasElement()),t{this.draw(),this._waitingForDraw=!1})),this}getIntersection(t,e){if(!this.isListening()||!this.isVisible())return null;for(var i=1,r=!1;;){for(let a=0;a0?{antialiased:!0}:{}}drawScene(t,e){var i=this.getLayer(),r=t||i&&i.getCanvas();return this._fire("beforeDraw",{node:this}),this.clearBeforeDraw()&&r.getContext().clear(),B.prototype.drawScene.call(this,r,e),this._fire("draw",{node:this}),this}drawHit(t,e){var i=this.getLayer(),r=t||i&&i.hitCanvas;return i&&i.clearBeforeDraw()&&i.getHitCanvas().getContext().clear(),B.prototype.drawHit.call(this,r,e),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){d.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return d.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(this.parent&&this.parent.content){var t=this.parent;!!this.hitCanvas._canvas.parentNode?t.content.removeChild(this.hitCanvas._canvas):t.content.appendChild(this.hitCanvas._canvas)}}}at.prototype.nodeType="Layer",r(at),y.addGetterSetter(at,"imageSmoothingEnabled",!0),y.addGetterSetter(at,"clearBeforeDraw",!0),y.addGetterSetter(at,"hitGraphEnabled",!0,_());class nt extends at{constructor(t){super(t),this.listening(!1),d.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}nt.prototype.nodeType="FastLayer",r(nt);class st extends B{_validateAdd(t){var e=t.getType();"Group"!==e&&"Shape"!==e&&d.throw("You may only add groups and shapes to groups.")}}st.prototype.nodeType="Group",r(st);var ot=e.performance&&e.performance.now?function(){return e.performance.now()}:function(){return(new Date).getTime()};class ht{constructor(t,e){this.id=ht.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:ot(),frameRate:0},this.func=t,this.setLayers(e)}setLayers(t){var e=[];return e=t?t.length>0?t:[t]:[],this.layers=e,this}getLayers(){return this.layers}addLayer(t){var e,i=this.layers,r=i.length;for(e=0;ethis.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():t<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=t,this.update())}getTime(){return this._time}setPosition(t){this.prevPos=this._pos,this.propFunc(t),this._pos=t}getPosition(t){return void 0===t&&(t=this._time),this.func(t,this.begin,this._change,this.duration)}play(){this.state=2,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=3,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(t){this.pause(),this._time=t,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){var t=this.getTimer()-this._startTime;2===this.state?this.setTime(t):3===this.state&&this.setTime(this.duration-t)}pause(){this.state=1,this.fire("onPause")}getTimer(){return(new Date).getTime()}}class ut{constructor(t){var e,r,a=this,n=t.node,s=n._id,o=t.easing||ft.Linear,h=!!t.yoyo;e=void 0===t.duration?.3:0===t.duration?.001:t.duration,this.node=n,this._id=dt++;var l=n.getLayer()||(n instanceof i.Stage?n.getLayers():null);for(r in l||d.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new ht((function(){a.tween.onEnterFrame()}),l),this.tween=new gt(r,(function(t){a._tweenFunc(t)}),o,0,1,1e3*e,h),this._addListeners(),ut.attrs[s]||(ut.attrs[s]={}),ut.attrs[s][this._id]||(ut.attrs[s][this._id]={}),ut.tweens[s]||(ut.tweens[s]={}),t)void 0===lt[r]&&this._addAttr(r,t[r]);this.reset(),this.onFinish=t.onFinish,this.onReset=t.onReset,this.onUpdate=t.onUpdate}_addAttr(t,e){var i,r,a,n,s,o,h,l,c=this.node,g=c._id;if((a=ut.tweens[g][t])&&delete ut.attrs[g][a][t],i=c.getAttr(t),d._isArray(e))if(r=[],s=Math.max(e.length,i.length),"points"===t&&e.length!==i.length&&(e.length>i.length?(h=i,i=d._prepareArrayForTween(i,e,c.closed())):(o=e,e=d._prepareArrayForTween(e,i,c.closed()))),0===t.indexOf("fill"))for(n=0;n{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{var t=this.node,e=ut.attrs[t._id][this._id];e.points&&e.points.trueEnd&&t.setAttr("points",e.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{var t=this.node,e=ut.attrs[t._id][this._id];e.points&&e.points.trueStart&&t.points(e.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(t){return this.tween.seek(1e3*t),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){var t,e=this.node._id,i=this._id,r=ut.tweens[e];for(t in this.pause(),r)delete ut.tweens[e][t];delete ut.attrs[e][i]}}ut.attrs={},ut.tweens={},O.prototype.to=function(t){var e=t.onFinish;t.node=this,t.onFinish=function(){this.destroy(),e&&e()},new ut(t).play()};const ft={BackEaseIn(t,e,i,r){var a=1.70158;return i*(t/=r)*t*((a+1)*t-a)+e},BackEaseOut(t,e,i,r){var a=1.70158;return i*((t=t/r-1)*t*((a+1)*t+a)+1)+e},BackEaseInOut(t,e,i,r){var a=1.70158;return(t/=r/2)<1?i/2*(t*t*((1+(a*=1.525))*t-a))+e:i/2*((t-=2)*t*((1+(a*=1.525))*t+a)+2)+e},ElasticEaseIn(t,e,i,r,a,n){var s=0;return 0===t?e:1==(t/=r)?e+i:(n||(n=.3*r),!a||a(t/=r)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e,BounceEaseIn:(t,e,i,r)=>i-ft.BounceEaseOut(r-t,0,i,r)+e,BounceEaseInOut:(t,e,i,r)=>ti*(t/=r)*t+e,EaseOut:(t,e,i,r)=>-i*(t/=r)*(t-2)+e,EaseInOut:(t,e,i,r)=>(t/=r/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e,StrongEaseIn:(t,e,i,r)=>i*(t/=r)*t*t*t*t+e,StrongEaseOut:(t,e,i,r)=>i*((t=t/r-1)*t*t*t*t+1)+e,StrongEaseInOut:(t,e,i,r)=>(t/=r/2)<1?i/2*t*t*t*t*t+e:i/2*((t-=2)*t*t*t*t+2)+e,Linear:(t,e,i,r)=>i*t/r+e},pt=d._assign(i,{Util:d,Transform:a,Node:O,ids:M,names:G,Container:B,Stage:J,stages:V,Layer:at,FastLayer:nt,Group:st,DD:A,Shape:et,shapes:tt,Animation:ht,Tween:ut,Easings:ft,Context:b,Canvas:P});class vt extends et{_sceneFunc(t){var e=i.getAngle(this.angle()),r=this.clockwise();t.beginPath(),t.arc(0,0,this.outerRadius(),0,e,r),t.arc(0,0,this.innerRadius(),e,0,!r),t.closePath(),t.fillStrokeShape(this)}getWidth(){return 2*this.outerRadius()}getHeight(){return 2*this.outerRadius()}setWidth(t){this.outerRadius(t/2)}setHeight(t){this.outerRadius(t/2)}}vt.prototype._centroid=!0,vt.prototype.className="Arc",vt.prototype._attrsAffectingSize=["innerRadius","outerRadius"],r(vt),y.addGetterSetter(vt,"innerRadius",0,u()),y.addGetterSetter(vt,"outerRadius",0,u()),y.addGetterSetter(vt,"angle",0,u()),y.addGetterSetter(vt,"clockwise",!1,_());class mt extends et{constructor(t){super(t),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",(function(){this._clearCache("tensionPoints")}))}_sceneFunc(t){var e,i,r,a=this.points(),n=a.length,s=this.tension(),o=this.closed(),h=this.bezier();if(n){if(t.beginPath(),t.moveTo(a[0],a[1]),0!==s&&n>4){for(i=(e=this.getTensionPoints()).length,r=o?0:4,o||t.quadraticCurveTo(e[0],e[1],e[2],e[3]);r4;a&&(r=this.getTensionPoints());var n,s,o=i.length;a?(n=i[o-2]-(r[r.length-2]+r[r.length-4])/2,s=i[o-1]-(r[r.length-1]+r[r.length-3])/2):(n=i[o-2]-i[o-4],s=i[o-1]-i[o-3]);var h=(Math.atan2(s,n)+e)%e,l=this.pointerLength(),d=this.pointerWidth();this.pointerAtEnding()&&(t.save(),t.beginPath(),t.translate(i[o-2],i[o-1]),t.rotate(h),t.moveTo(0,0),t.lineTo(-l,d/2),t.lineTo(-l,-d/2),t.closePath(),t.restore()),this.pointerAtBeginning()&&(t.save(),t.translate(i[0],i[1]),a?(n=(r[0]+r[2])/2-i[0],s=(r[1]+r[3])/2-i[1]):(n=i[2]-i[0],s=i[3]-i[1]),t.rotate((Math.atan2(-s,-n)+e)%e),t.moveTo(0,0),t.lineTo(-l,d/2),t.lineTo(-l,-d/2),t.closePath(),t.restore());var c=this.dashEnabled();c&&(this.attrs.dashEnabled=!1,t.setLineDash([])),t.fillStrokeShape(this),c&&(this.attrs.dashEnabled=!0)}getSelfRect(){const t=super.getSelfRect(),e=this.pointerWidth()/2;return{x:t.x-e,y:t.y-e,width:t.width+2*e,height:t.height+2*e}}}_t.prototype.className="Arrow",r(_t),y.addGetterSetter(_t,"pointerLength",10,u()),y.addGetterSetter(_t,"pointerWidth",10,u()),y.addGetterSetter(_t,"pointerAtBeginning",!1),y.addGetterSetter(_t,"pointerAtEnding",!0);class yt extends et{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.attrs.radius||0,0,2*Math.PI,!1),t.closePath(),t.fillStrokeShape(this)}getWidth(){return 2*this.radius()}getHeight(){return 2*this.radius()}setWidth(t){this.radius()!==t/2&&this.radius(t/2)}setHeight(t){this.radius()!==t/2&&this.radius(t/2)}}yt.prototype._centroid=!0,yt.prototype.className="Circle",yt.prototype._attrsAffectingSize=["radius"],r(yt),y.addGetterSetter(yt,"radius",0,u());class xt extends et{_sceneFunc(t){var e=this.radiusX(),i=this.radiusY();t.beginPath(),t.save(),e!==i&&t.scale(1,i/e),t.arc(0,0,e,0,2*Math.PI,!1),t.restore(),t.closePath(),t.fillStrokeShape(this)}getWidth(){return 2*this.radiusX()}getHeight(){return 2*this.radiusY()}setWidth(t){this.radiusX(t/2)}setHeight(t){this.radiusY(t/2)}}xt.prototype.className="Ellipse",xt.prototype._centroid=!0,xt.prototype._attrsAffectingSize=["radiusX","radiusY"],r(xt),y.addComponentsGetterSetter(xt,"radius",["x","y"]),y.addGetterSetter(xt,"radiusX",0,u()),y.addGetterSetter(xt,"radiusY",0,u());class bt extends et{constructor(t){super(t),this.on("imageChange.konva",()=>{this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const t=this.image();t&&t.addEventListener&&t.addEventListener("load",()=>{this._requestDraw()})}_useBufferCanvas(){return super._useBufferCanvas(!0)}_sceneFunc(t){const e=this.getWidth(),i=this.getHeight(),r=this.attrs.image;let a;if(r){const t=this.attrs.cropWidth,n=this.attrs.cropHeight;a=t&&n?[r,this.cropX(),this.cropY(),t,n,0,0,e,i]:[r,0,0,e,i]}(this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,e,i),t.closePath(),t.fillStrokeShape(this)),r&&t.drawImage.apply(t,a)}_hitFunc(t){var e=this.width(),i=this.height();t.beginPath(),t.rect(0,0,e,i),t.closePath(),t.fillStrokeShape(this)}getWidth(){var t,e;return null!==(t=this.attrs.width)&&void 0!==t?t:null===(e=this.image())||void 0===e?void 0:e.width}getHeight(){var t,e;return null!==(t=this.attrs.height)&&void 0!==t?t:null===(e=this.image())||void 0===e?void 0:e.height}static fromURL(t,e){var i=d.createImageElement();i.onload=function(){var t=new bt({image:i});e(t)},i.crossOrigin="Anonymous",i.src=t}}bt.prototype.className="Image",r(bt),y.addGetterSetter(bt,"image"),y.addComponentsGetterSetter(bt,"crop",["x","y","width","height"]),y.addGetterSetter(bt,"cropX",0,u()),y.addGetterSetter(bt,"cropY",0,u()),y.addGetterSetter(bt,"cropWidth",0,u()),y.addGetterSetter(bt,"cropHeight",0,u());var St=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height"],wt=St.length;class Ct extends st{constructor(t){super(t),this.on("add.konva",(function(t){this._addListeners(t.child),this._sync()}))}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(t){var e,i=this,r=function(){i._sync()};for(e=0;el?h:l,p=h>l?1:h/l,v=h>l?l/h:1;t.translate(s,o),t.rotate(g),t.scale(p,v),t.arc(0,0,f,d,d+c,1-u),t.scale(1/p,1/v),t.rotate(-g),t.translate(-s,-o);break;case"z":i=!0,t.closePath()}}i||this.hasFill()?t.fillStrokeShape(this):t.strokeShape(this)}getSelfRect(){var t=[];this.dataArray.forEach((function(e){if("A"===e.command){var i=e.points[4],r=e.points[5],a=e.points[4]+r,n=Math.PI/180;if(Math.abs(i-a)a;r-=n){const i=kt.getPointOnEllipticalArc(e.points[0],e.points[1],e.points[2],e.points[3],r,0);t.push(i.x,i.y)}else for(let r=i+n;rthis.dataArray[i].pathLength;)t-=this.dataArray[i].pathLength,++i;if(i===r)return{x:(e=this.dataArray[i-1].points.slice(-2))[0],y:e[1]};if(t<.01)return{x:(e=this.dataArray[i].points.slice(0,2))[0],y:e[1]};var a=this.dataArray[i],n=a.points;switch(a.command){case"L":return kt.getPointOnLine(t,a.start.x,a.start.y,n[0],n[1]);case"C":return kt.getPointOnCubicBezier(t/a.pathLength,a.start.x,a.start.y,n[0],n[1],n[2],n[3],n[4],n[5]);case"Q":return kt.getPointOnQuadraticBezier(t/a.pathLength,a.start.x,a.start.y,n[0],n[1],n[2],n[3]);case"A":var s=n[0],o=n[1],h=n[2],l=n[3],d=n[4],c=n[5],g=n[6];return d+=c*t/a.pathLength,kt.getPointOnEllipticalArc(s,o,h,l,d,g)}return null}static getLineLength(t,e,i,r){return Math.sqrt((i-t)*(i-t)+(r-e)*(r-e))}static getPointOnLine(t,e,i,r,a,n,s){void 0===n&&(n=e),void 0===s&&(s=i);var o=(a-i)/(r-e+1e-8),h=Math.sqrt(t*t/(1+o*o));r0&&!isNaN(u[0]);){var m,_,y,x,b,S,w,C,P,k,T=null,A=[],M=h,G=l;switch(g){case"l":h+=u.shift(),l+=u.shift(),T="L",A.push(h,l);break;case"L":h=u.shift(),l=u.shift(),A.push(h,l);break;case"m":var E=u.shift(),R=u.shift();if(h+=E,l+=R,T="M",s.length>2&&"z"===s[s.length-1].command)for(var L=s.length-2;L>=0;L--)if("M"===s[L].command){h=s[L].points[0]+E,l=s[L].points[1]+R;break}A.push(h,l),g="l";break;case"M":h=u.shift(),l=u.shift(),T="M",A.push(h,l),g="L";break;case"h":h+=u.shift(),T="L",A.push(h,l);break;case"H":h=u.shift(),T="L",A.push(h,l);break;case"v":l+=u.shift(),T="L",A.push(h,l);break;case"V":l=u.shift(),T="L",A.push(h,l);break;case"C":A.push(u.shift(),u.shift(),u.shift(),u.shift()),h=u.shift(),l=u.shift(),A.push(h,l);break;case"c":A.push(h+u.shift(),l+u.shift(),h+u.shift(),l+u.shift()),h+=u.shift(),l+=u.shift(),T="C",A.push(h,l);break;case"S":_=h,y=l,"C"===(m=s[s.length-1]).command&&(_=h+(h-m.points[2]),y=l+(l-m.points[3])),A.push(_,y,u.shift(),u.shift()),h=u.shift(),l=u.shift(),T="C",A.push(h,l);break;case"s":_=h,y=l,"C"===(m=s[s.length-1]).command&&(_=h+(h-m.points[2]),y=l+(l-m.points[3])),A.push(_,y,h+u.shift(),l+u.shift()),h+=u.shift(),l+=u.shift(),T="C",A.push(h,l);break;case"Q":A.push(u.shift(),u.shift()),h=u.shift(),l=u.shift(),A.push(h,l);break;case"q":A.push(h+u.shift(),l+u.shift()),h+=u.shift(),l+=u.shift(),T="Q",A.push(h,l);break;case"T":_=h,y=l,"Q"===(m=s[s.length-1]).command&&(_=h+(h-m.points[0]),y=l+(l-m.points[1])),h=u.shift(),l=u.shift(),T="Q",A.push(_,y,h,l);break;case"t":_=h,y=l,"Q"===(m=s[s.length-1]).command&&(_=h+(h-m.points[0]),y=l+(l-m.points[1])),h+=u.shift(),l+=u.shift(),T="Q",A.push(_,y,h,l);break;case"A":x=u.shift(),b=u.shift(),S=u.shift(),w=u.shift(),C=u.shift(),P=h,k=l,h=u.shift(),l=u.shift(),T="A",A=this.convertEndpointToCenterParameterization(P,k,h,l,w,C,x,b,S);break;case"a":x=u.shift(),b=u.shift(),S=u.shift(),w=u.shift(),C=u.shift(),P=h,k=l,h+=u.shift(),l+=u.shift(),T="A",A=this.convertEndpointToCenterParameterization(P,k,h,l,w,C,x,b,S)}s.push({command:T||g,points:A,start:{x:M,y:G},pathLength:this.calcLength(M,G,T||g,A)})}"z"!==g&&"Z"!==g||s.push({command:"z",points:[],start:void 0,pathLength:0})}return s}static calcLength(t,e,i,r){var a,n,s,o,h=kt;switch(i){case"L":return h.getLineLength(t,e,r[0],r[1]);case"C":for(a=0,n=h.getPointOnCubicBezier(0,t,e,r[0],r[1],r[2],r[3],r[4],r[5]),o=.01;o<=1;o+=.01)s=h.getPointOnCubicBezier(o,t,e,r[0],r[1],r[2],r[3],r[4],r[5]),a+=h.getLineLength(n.x,n.y,s.x,s.y),n=s;return a;case"Q":for(a=0,n=h.getPointOnQuadraticBezier(0,t,e,r[0],r[1],r[2],r[3]),o=.01;o<=1;o+=.01)s=h.getPointOnQuadraticBezier(o,t,e,r[0],r[1],r[2],r[3]),a+=h.getLineLength(n.x,n.y,s.x,s.y),n=s;return a;case"A":a=0;var l=r[4],d=r[5],c=r[4]+d,g=Math.PI/180;if(Math.abs(l-c)c;o-=g)s=h.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],o,0),a+=h.getLineLength(n.x,n.y,s.x,s.y),n=s;else for(o=l+g;o1&&(s*=Math.sqrt(g),o*=Math.sqrt(g));var u=Math.sqrt((s*s*(o*o)-s*s*(c*c)-o*o*(d*d))/(s*s*(c*c)+o*o*(d*d)));a===n&&(u*=-1),isNaN(u)&&(u=0);var f=u*s*c/o,p=u*-o*d/s,v=(t+i)/2+Math.cos(l)*f-Math.sin(l)*p,m=(e+r)/2+Math.sin(l)*f+Math.cos(l)*p,_=function(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])},y=function(t,e){return(t[0]*e[0]+t[1]*e[1])/(_(t)*_(e))},x=function(t,e){return(t[0]*e[1]=1&&(C=0),0===n&&C>0&&(C-=2*Math.PI),1===n&&C<0&&(C+=2*Math.PI),[v,m,s,o,b,C,l,n]}}kt.prototype.className="Path",kt.prototype._attrsAffectingSize=["data"],r(kt),y.addGetterSetter(kt,"data");class Tt extends et{_sceneFunc(t){var e=this.cornerRadius(),i=this.width(),r=this.height();if(t.beginPath(),e){let a=0,n=0,s=0,o=0;"number"==typeof e?a=n=s=o=Math.min(e,i/2,r/2):(a=Math.min(e[0]||0,i/2,r/2),n=Math.min(e[1]||0,i/2,r/2),o=Math.min(e[2]||0,i/2,r/2),s=Math.min(e[3]||0,i/2,r/2)),t.moveTo(a,0),t.lineTo(i-n,0),t.arc(i-n,n,n,3*Math.PI/2,0,!1),t.lineTo(i,r-o),t.arc(i-o,r-o,o,0,Math.PI/2,!1),t.lineTo(s,r),t.arc(s,r-s,s,Math.PI/2,Math.PI,!1),t.lineTo(0,a),t.arc(a,a,a,Math.PI,3*Math.PI/2,!1)}else t.rect(0,0,i,r);t.closePath(),t.fillStrokeShape(this)}}Tt.prototype.className="Rect",r(Tt),y.addGetterSetter(Tt,"cornerRadius",0,f(4));class At extends et{_sceneFunc(t){const e=this._getPoints();t.beginPath(),t.moveTo(e[0].x,e[0].y);for(var i=1;i{e=Math.min(e,t.x),i=Math.max(i,t.x),r=Math.min(r,t.y),a=Math.max(a,t.y)}),{x:e,y:r,width:i-e,height:a-r}}getWidth(){return 2*this.radius()}getHeight(){return 2*this.radius()}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}At.prototype.className="RegularPolygon",At.prototype._centroid=!0,At.prototype._attrsAffectingSize=["radius"],r(At),y.addGetterSetter(At,"radius",0,u()),y.addGetterSetter(At,"sides",0,u());var Mt=2*Math.PI;class Gt extends et{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,Mt,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),Mt,0,!0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return 2*this.outerRadius()}getHeight(){return 2*this.outerRadius()}setWidth(t){this.outerRadius(t/2)}setHeight(t){this.outerRadius(t/2)}}Gt.prototype.className="Ring",Gt.prototype._centroid=!0,Gt.prototype._attrsAffectingSize=["innerRadius","outerRadius"],r(Gt),y.addGetterSetter(Gt,"innerRadius",0,u()),y.addGetterSetter(Gt,"outerRadius",0,u());class Et extends et{constructor(t){super(t),this._updated=!0,this.anim=new ht(()=>{var t=this._updated;return this._updated=!1,t}),this.on("animationChange.konva",(function(){this.frameIndex(0)})),this.on("frameIndexChange.konva",(function(){this._updated=!0})),this.on("frameRateChange.konva",(function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())}))}_sceneFunc(t){var e=this.animation(),i=this.frameIndex(),r=4*i,a=this.animations()[e],n=this.frameOffsets(),s=a[r+0],o=a[r+1],h=a[r+2],l=a[r+3],d=this.image();if((this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,h,l),t.closePath(),t.fillStrokeShape(this)),d)if(n){var c=n[e],g=2*i;t.drawImage(d,s,o,h,l,c[g+0],c[g+1],h,l)}else t.drawImage(d,s,o,h,l,0,0,h,l)}_hitFunc(t){var e=this.animation(),i=this.frameIndex(),r=4*i,a=this.animations()[e],n=this.frameOffsets(),s=a[r+2],o=a[r+3];if(t.beginPath(),n){var h=n[e],l=2*i;t.rect(h[l+0],h[l+1],s,o)}else t.rect(0,0,s,o);t.closePath(),t.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){var t=this;this.interval=setInterval((function(){t._updateIndex()}),1e3/this.frameRate())}start(){if(!this.isRunning()){var t=this.getLayer();this.anim.setLayers(t),this._setInterval(),this.anim.start()}}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){var t=this.frameIndex(),e=this.animation();t1&&(v+=s)}}}_hitFunc(t){var e=this.getWidth(),i=this.getHeight();t.beginPath(),t.rect(0,0,e,i),t.closePath(),t.fillStrokeShape(this)}setText(t){var e=d._isString(t)?t:null==t?"":t+"";return this._setAttr("text",e),this}getWidth(){return"auto"===this.attrs.width||void 0===this.attrs.width?this.getTextWidth()+2*this.padding():this.attrs.width}getHeight(){return"auto"===this.attrs.height||void 0===this.attrs.height?this.fontSize()*this.textArr.length*this.lineHeight()+2*this.padding():this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return d.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(t){var e,i=Ft(),r=this.fontSize();return i.save(),i.font=this._getContextFont(),e=i.measureText(t),i.restore(),{width:e.width,height:r}}_getContextFont(){return this.fontStyle()+" "+this.fontVariant()+" "+this.fontSize()+"px "+this.fontFamily().split(",").map(t=>{const e=(t=t.trim()).indexOf(" ")>=0,i=t.indexOf('"')>=0||t.indexOf("'")>=0;return e&&!i&&(t=`"${t}"`),t}).join(", ")}_addTextLine(t){"justify"===this.align()&&(t=t.trim());var e=this._getTextWidth(t);return this.textArr.push({text:t,width:e})}_getTextWidth(t){var e=this.letterSpacing(),i=t.length;return Ft().measureText(t).width+(i?e*(i-1):0)}_setTextData(){var t=this.text().split("\n"),e=+this.fontSize(),i=0,r=this.lineHeight()*e,a=this.attrs.width,n=this.attrs.height,s="auto"!==a&&void 0!==a,o="auto"!==n&&void 0!==n,h=this.padding(),l=a-2*h,d=n-2*h,c=0,g=this.wrap(),u="none"!==g,f="char"!==g&&u,p=this.ellipsis();this.textArr=[],Ft().font=this._getContextFont();for(var v=p?this._getTextWidth("…"):0,m=0,_=t.length;m<_;++m){var y=t[m],x=this._getTextWidth(y);if(s&&x>l)for(;y.length>0;){for(var b=0,S=y.length,w="",C=0;b>>1,k=y.slice(0,P+1),T=this._getTextWidth(k)+v;T<=l?(b=P+1,w=k,C=T):S=P}if(!w)break;if(f){var A,M=y[w.length];(A=(" "===M||"-"===M)&&C<=l?w.length:Math.max(w.lastIndexOf(" "),w.lastIndexOf("-"))+1)>0&&(b=A,w=w.slice(0,b),C=this._getTextWidth(w))}if(w=w.trimRight(),this._addTextLine(w),i=Math.max(i,C),c+=r,!u||o&&c+r>d){var G=this.textArr[this.textArr.length-1];if(G)if(p)this._getTextWidth(G.text+"…")0&&(x=this._getTextWidth(y))<=l){this._addTextLine(y),c+=r,i=Math.max(i,x);break}}else this._addTextLine(y),c+=r,i=Math.max(i,x);if(o&&c+r>d)break}this.textHeight=e,this.textWidth=i}getStrokeScaleEnabled(){return!0}}Bt.prototype._fillFunc=function(t){t.fillText(this._partialText,this._partialTextX,this._partialTextY)},Bt.prototype._strokeFunc=function(t){t.strokeText(this._partialText,this._partialTextX,this._partialTextY)},Bt.prototype.className="Text",Bt.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"],r(Bt),y.overWriteSetter(Bt,"width",p()),y.overWriteSetter(Bt,"height",p()),y.addGetterSetter(Bt,"fontFamily","Arial"),y.addGetterSetter(Bt,"fontSize",12,u()),y.addGetterSetter(Bt,"fontStyle","normal"),y.addGetterSetter(Bt,"fontVariant","normal"),y.addGetterSetter(Bt,"padding",0,u()),y.addGetterSetter(Bt,"align","left"),y.addGetterSetter(Bt,"verticalAlign","top"),y.addGetterSetter(Bt,"lineHeight",1,u()),y.addGetterSetter(Bt,"wrap","word"),y.addGetterSetter(Bt,"ellipsis",!1,_()),y.addGetterSetter(Bt,"letterSpacing",0,u()),y.addGetterSetter(Bt,"text","",v()),y.addGetterSetter(Bt,"textDecoration","");function Nt(t){t.fillText(this.partialText,0,0)}function zt(t){t.strokeText(this.partialText,0,0)}class Wt extends et{constructor(t){super(t),this.dummyCanvas=d.createCanvasElement(),this.dataArray=[],this.dataArray=kt.parsePathData(this.attrs.data),this.on("dataChange.konva",(function(){this.dataArray=kt.parsePathData(this.attrs.data),this._setTextData()})),this.on("textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva",this._setTextData),t&&t.getKerning&&(d.warn('getKerning TextPath API is deprecated. Please use "kerningFunc" instead.'),this.kerningFunc(t.getKerning)),this._setTextData()}_sceneFunc(t){t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",this.textBaseline()),t.setAttr("textAlign","left"),t.save();var e=this.textDecoration(),i=this.fill(),r=this.fontSize(),a=this.glyphInfo;"underline"===e&&t.beginPath();for(var n=0;n=1){var i=e[0].p0;t.moveTo(i.x,i.y)}for(var r=0;r0&&(s+=t.dataArray[o].pathLength);var h=0;"center"===r&&(h=Math.max(0,s/2-n/2)),"right"===r&&(h=Math.max(0,s-n));for(var l,d,c,g=Lt(this.text()),u=this.text().split(" ").length-1,f=-1,p=0,v=function(){p=0;for(var e=t.dataArray,i=f+1;i0)return f=i,e[i];"M"===e[i].command&&(l={x:e[i].points[0],y:e[i].points[1]})}return{}},m=function(e){var a=t._getTextSize(e).width+i;" "===e&&"justify"===r&&(a+=(s-n)/u);var o=0,h=0;for(d=void 0;Math.abs(a-o)/a>.01&&h<20;){h++;for(var g=o;void 0===c;)(c=v())&&g+c.pathLengtha?d=kt.getPointOnLine(a,l.x,l.y,c.points[0],c.points[1],l.x,l.y):c=void 0;break;case"A":var m=c.points[4],_=c.points[5],y=c.points[4]+_;0===p?p=m+1e-8:a>o?p+=Math.PI/180*_/Math.abs(_):p-=Math.PI/360*_/Math.abs(_),(_<0&&p=0&&p>y)&&(p=y,f=!0),d=kt.getPointOnEllipticalArc(c.points[0],c.points[1],c.points[2],c.points[3],p,c.points[6]);break;case"C":0===p?p=a>c.pathLength?1e-8:a/c.pathLength:a>o?p+=(a-o)/c.pathLength/2:p=Math.max(p-(o-a)/c.pathLength/2,0),p>1&&(p=1,f=!0),d=kt.getPointOnCubicBezier(p,c.start.x,c.start.y,c.points[0],c.points[1],c.points[2],c.points[3],c.points[4],c.points[5]);break;case"Q":0===p?p=a/c.pathLength:a>o?p+=(a-o)/c.pathLength:p-=(o-a)/c.pathLength,p>1&&(p=1,f=!0),d=kt.getPointOnQuadraticBezier(p,c.start.x,c.start.y,c.points[0],c.points[1],c.points[2],c.points[3])}void 0!==d&&(o=kt.getLineLength(l.x,l.y,d.x,d.y)),f&&(f=!1,c=void 0)}},_=h/(t._getTextSize("C").width+i)-1,y=0;y<_&&(m("C"),void 0!==l&&void 0!==d);y++)l=d;for(var x=0;xt+".tr-konva").join(" "),Yt=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange"].map(t=>t+".tr-konva").join(" "),Xt={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135};const jt="ontouchstart"in i._global;var Ut=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function qt(t,e,i){const r=i.x+(t.x-i.x)*Math.cos(e)-(t.y-i.y)*Math.sin(e),a=i.y+(t.x-i.x)*Math.sin(e)+(t.y-i.y)*Math.cos(e);return Object.assign(Object.assign({},t),{rotation:t.rotation+e,x:r,y:a})}function Kt(t,e){return qt(t,e,function(t){return{x:t.x+t.width/2*Math.cos(t.rotation)+t.height/2*Math.sin(-t.rotation),y:t.y+t.height/2*Math.cos(t.rotation)+t.width/2*Math.sin(t.rotation)}}(t))}class Vt extends st{constructor(t){super(t),this._transforming=!1,this._createElements(),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this.update=this.update.bind(this),this.on(Ht,this.update),this.getNode()&&this.update()}attachTo(t){return this.setNode(t),this}setNode(t){return d.warn("tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead."),this.setNodes([t])}getNode(){return this._nodes&&this._nodes[0]}setNodes(t=[]){return this._nodes&&this._nodes.length&&this.detach(),this._nodes=t,1===t.length?this.rotation(t[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(t=>{const e=t._attrsAffectingSize.map(t=>t+"Change.tr-konva").join(" "),i=()=>{1===this.nodes().length&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),this._transforming||this.isDragging()||this.update()};t.on(e,i),t.on(Yt,i),t.on("absoluteTransformChange.tr-konva",i),t.on("xChange.tr-konva yChange.tr-konva",i),this._proxyDrag(t)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(t){let e;t.on("dragstart.tr-konva",i=>{e=t.getAbsolutePosition(),this.isDragging()||t===this.findOne(".back")||this.startDrag(i,!1)}),t.on("dragmove.tr-konva",i=>{if(!e)return;const r=t.getAbsolutePosition(),a=r.x-e.x,n=r.y-e.y;this.nodes().forEach(e=>{if(e===t)return;if(e.isDragging())return;const r=e.getAbsolutePosition();e.setAbsolutePosition({x:r.x+a,y:r.y+n}),e.startDrag(i)}),e=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(t=>{t.off(".tr-konva")}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache("nodesRect"),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache("nodesRect",this.__getNodeRect)}__getNodeShape(t,e=this.rotation(),r){var a=t.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),n=t.getAbsoluteScale(r),s=t.getAbsolutePosition(r),o=a.x*n.x-t.offsetX()*n.x,h=a.y*n.y-t.offsetY()*n.y;const l=(i.getAngle(t.getAbsoluteRotation())+2*Math.PI)%(2*Math.PI);return qt({x:s.x+o*Math.cos(l)+h*Math.sin(-l),y:s.y+h*Math.cos(l)+o*Math.sin(l),width:a.width*n.x,height:a.height*n.y,rotation:l},-i.getAngle(e),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-1e8,y:-1e8,width:0,height:0,rotation:0};const t=[];this.nodes().map(e=>{const i=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()});var r=[{x:i.x,y:i.y},{x:i.x+i.width,y:i.y},{x:i.x+i.width,y:i.y+i.height},{x:i.x,y:i.y+i.height}],a=e.getAbsoluteTransform();r.forEach((function(e){var i=a.point(e);t.push(i)}))});const e=new a;var r,n,s,o;e.rotate(-i.getAngle(this.rotation())),t.forEach((function(t){var i=e.point(t);void 0===r&&(r=s=i.x,n=o=i.y),r=Math.min(r,i.x),n=Math.min(n,i.y),s=Math.max(s,i.x),o=Math.max(o,i.y)})),e.invert();const h=e.point({x:r,y:n});return{x:h.x,y:h.y,width:s-r,height:o-n,rotation:i.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),Ut.forEach(function(t){this._createAnchor(t)}.bind(this)),this._createAnchor("rotater")}_createAnchor(t){var e=new Tt({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:jt?10:"auto"}),r=this;e.on("mousedown touchstart",(function(t){r._handleMouseDown(t)})),e.on("dragstart",t=>{e.stopDrag(),t.cancelBubble=!0}),e.on("dragend",t=>{t.cancelBubble=!0}),e.on("mouseenter",()=>{var r=i.getAngle(this.rotation()),a=function(t,e){if("rotater"===t)return"crosshair";e+=d._degToRad(Xt[t]||0);var i=(d._radToDeg(e)%360+360)%360;return d._inRange(i,337.5,360)||d._inRange(i,0,22.5)?"ns-resize":d._inRange(i,22.5,67.5)?"nesw-resize":d._inRange(i,67.5,112.5)?"ew-resize":d._inRange(i,112.5,157.5)?"nwse-resize":d._inRange(i,157.5,202.5)?"ns-resize":d._inRange(i,202.5,247.5)?"nesw-resize":d._inRange(i,247.5,292.5)?"ew-resize":d._inRange(i,292.5,337.5)?"nwse-resize":(d.error("Transformer has unknown angle for cursor detection: "+i),"pointer")}(t,r);e.getStage().content&&(e.getStage().content.style.cursor=a),this._cursorChange=!0}),e.on("mouseout",()=>{e.getStage().content&&(e.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(e)}_createBack(){var t=new et({name:"back",width:0,height:0,draggable:!0,sceneFunc(t){var e=this.getParent(),i=e.padding();t.beginPath(),t.rect(-i,-i,this.width()+2*i,this.height()+2*i),t.moveTo(this.width()/2,-i),e.rotateEnabled()&&t.lineTo(this.width()/2,-e.rotateAnchorOffset()*d._sign(this.height())-i),t.fillStrokeShape(this)},hitFunc:(t,e)=>{if(this.shouldOverdrawWholeArea()){var i=this.padding();t.beginPath(),t.rect(-i,-i,e.width()+2*i,e.height()+2*i),t.fillStrokeShape(e)}}});this.add(t),this._proxyDrag(t),t.on("dragstart",t=>{t.cancelBubble=!0}),t.on("dragmove",t=>{t.cancelBubble=!0}),t.on("dragend",t=>{t.cancelBubble=!0})}_handleMouseDown(t){this._movingAnchorName=t.target.name().split(" ")[0];var e=this._getNodeRect(),i=e.width,r=e.height,a=Math.sqrt(Math.pow(i,2)+Math.pow(r,2));this.sin=Math.abs(r/a),this.cos=Math.abs(i/a),"undefined"!=typeof window&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;var n=t.target.getAbsolutePosition(),s=t.target.getStage().getPointerPosition();this._anchorDragOffset={x:s.x-n.x,y:s.y-n.y},this._fire("transformstart",{evt:t,target:this.getNode()}),this._nodes.forEach(e=>{e._fire("transformstart",{evt:t,target:e})})}_handleMouseMove(t){var e,r,a,n=this.findOne("."+this._movingAnchorName),s=n.getStage();s.setPointersPositions(t);const o=s.getPointerPosition();var h={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const l=n.getAbsolutePosition();n.setAbsolutePosition(h);const d=n.getAbsolutePosition();if(l.x!==d.x||l.y!==d.y)if("rotater"!==this._movingAnchorName){var c=this.keepRatio()||t.shiftKey,g=this.centeredScaling()||t.altKey;if("top-left"===this._movingAnchorName){if(c){var u=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};a=Math.sqrt(Math.pow(u.x-n.x(),2)+Math.pow(u.y-n.y(),2));var f=this.findOne(".top-left").x()>u.x?-1:1,p=this.findOne(".top-left").y()>u.y?-1:1;e=a*this.cos*f,r=a*this.sin*p,this.findOne(".top-left").x(u.x-e),this.findOne(".top-left").y(u.y-r)}}else if("top-center"===this._movingAnchorName)this.findOne(".top-left").y(n.y());else if("top-right"===this._movingAnchorName){if(c){u=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};a=Math.sqrt(Math.pow(n.x()-u.x,2)+Math.pow(u.y-n.y(),2));f=this.findOne(".top-right").x()u.y?-1:1;e=a*this.cos*f,r=a*this.sin*p,this.findOne(".top-right").x(u.x+e),this.findOne(".top-right").y(u.y-r)}var v=n.position();this.findOne(".top-left").y(v.y),this.findOne(".bottom-right").x(v.x)}else if("middle-left"===this._movingAnchorName)this.findOne(".top-left").x(n.x());else if("middle-right"===this._movingAnchorName)this.findOne(".bottom-right").x(n.x());else if("bottom-left"===this._movingAnchorName){if(c){u=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};a=Math.sqrt(Math.pow(u.x-n.x(),2)+Math.pow(n.y()-u.y,2));f=u.x{e._fire("transformend",{evt:t,target:e})}),this._movingAnchorName=null}}_fitNodesInto(t,e){var r=this._getNodeRect();if(d._inRange(t.width,2*-this.padding()-1,1))return void this.update();if(d._inRange(t.height,2*-this.padding()-1,1))return void this.update();var n=new a;if(n.rotate(i.getAngle(this.rotation())),this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const e=n.point({x:2*-this.padding(),y:0});t.x+=e.x,t.y+=e.y,t.width+=2*this.padding(),this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=e.x,this._anchorDragOffset.y-=e.y}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const e=n.point({x:2*this.padding(),y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=e.x,this._anchorDragOffset.y-=e.y,t.width+=2*this.padding()}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const e=n.point({x:0,y:2*-this.padding()});t.x+=e.x,t.y+=e.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=e.x,this._anchorDragOffset.y-=e.y,t.height+=2*this.padding()}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const e=n.point({x:0,y:2*this.padding()});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=e.x,this._anchorDragOffset.y-=e.y,t.height+=2*this.padding()}if(this.boundBoxFunc()){const e=this.boundBoxFunc()(r,t);e?t=e:d.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const s=new a;s.translate(r.x,r.y),s.rotate(r.rotation),s.scale(r.width/1e7,r.height/1e7);const o=new a;o.translate(t.x,t.y),o.rotate(t.rotation),o.scale(t.width/1e7,t.height/1e7);const h=o.multiply(s.invert());this._nodes.forEach(t=>{var i;const r=t.getParent().getAbsoluteTransform(),n=t.getTransform().copy();n.translate(t.offsetX(),t.offsetY());const s=new a;s.multiply(r.copy().invert()).multiply(h).multiply(r).multiply(n);const o=s.decompose();t.setAttrs(o),this._fire("transform",{evt:e,target:t}),t._fire("transform",{evt:e,target:t}),null===(i=t.getLayer())||void 0===i||i.batchDraw()}),this.rotation(d._getRotation(t.rotation)),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(t,e){this.findOne(t).setAttrs(e)}update(){var t,e=this._getNodeRect();this.rotation(d._getRotation(e.rotation));var i=e.width,r=e.height,a=this.enabledAnchors(),n=this.resizeEnabled(),s=this.padding(),o=this.anchorSize();this.find("._anchor").forEach(t=>{t.setAttrs({width:o,height:o,offsetX:o/2,offsetY:o/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:o/2+s,offsetY:o/2+s,visible:n&&a.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:i/2,y:0,offsetY:o/2+s,visible:n&&a.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:i,y:0,offsetX:o/2-s,offsetY:o/2+s,visible:n&&a.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:r/2,offsetX:o/2+s,visible:n&&a.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:i,y:r/2,offsetX:o/2-s,visible:n&&a.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:r,offsetX:o/2+s,offsetY:o/2-s,visible:n&&a.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:i/2,y:r,offsetY:o/2-s,visible:n&&a.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:i,y:r,offsetX:o/2-s,offsetY:o/2-s,visible:n&&a.indexOf("bottom-right")>=0}),this._batchChangeChild(".rotater",{x:i/2,y:-this.rotateAnchorOffset()*d._sign(r)-s,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:i,height:r,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),x:0,y:0}),null===(t=this.getLayer())||void 0===t||t.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();var t=this.findOne("."+this._movingAnchorName);t&&t.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),st.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return O.prototype.toObject.call(this)}}Vt.prototype.className="Transformer",r(Vt),y.addGetterSetter(Vt,"enabledAnchors",Ut,(function(t){return t instanceof Array||d.warn("enabledAnchors value should be an array"),t instanceof Array&&t.forEach((function(t){-1===Ut.indexOf(t)&&d.warn("Unknown anchor name: "+t+". Available names are: "+Ut.join(", "))})),t||[]})),y.addGetterSetter(Vt,"resizeEnabled",!0),y.addGetterSetter(Vt,"anchorSize",10,u()),y.addGetterSetter(Vt,"rotateEnabled",!0),y.addGetterSetter(Vt,"rotationSnaps",[]),y.addGetterSetter(Vt,"rotateAnchorOffset",50,u()),y.addGetterSetter(Vt,"rotationSnapTolerance",5,u()),y.addGetterSetter(Vt,"borderEnabled",!0),y.addGetterSetter(Vt,"anchorStroke","rgb(0, 161, 255)"),y.addGetterSetter(Vt,"anchorStrokeWidth",1,u()),y.addGetterSetter(Vt,"anchorFill","white"),y.addGetterSetter(Vt,"anchorCornerRadius",0,u()),y.addGetterSetter(Vt,"borderStroke","rgb(0, 161, 255)"),y.addGetterSetter(Vt,"borderStrokeWidth",1,u()),y.addGetterSetter(Vt,"borderDash"),y.addGetterSetter(Vt,"keepRatio",!0),y.addGetterSetter(Vt,"centeredScaling",!1),y.addGetterSetter(Vt,"ignoreStroke",!1),y.addGetterSetter(Vt,"padding",0,u()),y.addGetterSetter(Vt,"node"),y.addGetterSetter(Vt,"nodes"),y.addGetterSetter(Vt,"boundBoxFunc"),y.addGetterSetter(Vt,"shouldOverdrawWholeArea",!1),y.backCompat(Vt,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class Qt extends et{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,i.getAngle(this.angle()),this.clockwise()),t.lineTo(0,0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return 2*this.radius()}getHeight(){return 2*this.radius()}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}function Jt(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}Qt.prototype.className="Wedge",Qt.prototype._centroid=!0,Qt.prototype._attrsAffectingSize=["radius"],r(Qt),y.addGetterSetter(Qt,"radius",0,u()),y.addGetterSetter(Qt,"angle",0,u()),y.addGetterSetter(Qt,"clockwise",!1),y.backCompat(Qt,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});var Zt=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],$t=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];y.addGetterSetter(O,"blurRadius",0,u(),y.afterSetFilter);y.addGetterSetter(O,"brightness",0,u(),y.afterSetFilter);y.addGetterSetter(O,"contrast",0,u(),y.afterSetFilter);function te(t,e,i,r,a){var n=i-e,s=a-r;return 0===n?r+s/2:0===s?r:s*((t-e)/n)+r}y.addGetterSetter(O,"embossStrength",.5,u(),y.afterSetFilter),y.addGetterSetter(O,"embossWhiteLevel",.5,u(),y.afterSetFilter),y.addGetterSetter(O,"embossDirection","top-left",null,y.afterSetFilter),y.addGetterSetter(O,"embossBlend",!1,null,y.afterSetFilter);y.addGetterSetter(O,"enhance",0,u(),y.afterSetFilter);y.addGetterSetter(O,"hue",0,u(),y.afterSetFilter),y.addGetterSetter(O,"saturation",0,u(),y.afterSetFilter),y.addGetterSetter(O,"luminance",0,u(),y.afterSetFilter);y.addGetterSetter(O,"hue",0,u(),y.afterSetFilter),y.addGetterSetter(O,"saturation",0,u(),y.afterSetFilter),y.addGetterSetter(O,"value",0,u(),y.afterSetFilter);function ee(t,e,i){var r=4*(i*t.width+e),a=[];return a.push(t.data[r++],t.data[r++],t.data[r++],t.data[r++]),a}function ie(t,e){return Math.sqrt(Math.pow(t[0]-e[0],2)+Math.pow(t[1]-e[1],2)+Math.pow(t[2]-e[2],2))}y.addGetterSetter(O,"kaleidoscopePower",2,u(),y.afterSetFilter),y.addGetterSetter(O,"kaleidoscopeAngle",0,u(),y.afterSetFilter);y.addGetterSetter(O,"threshold",0,u(),y.afterSetFilter);y.addGetterSetter(O,"noise",.2,u(),y.afterSetFilter);y.addGetterSetter(O,"pixelSize",8,u(),y.afterSetFilter);y.addGetterSetter(O,"levels",.5,u(),y.afterSetFilter);y.addGetterSetter(O,"red",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),y.addGetterSetter(O,"green",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),y.addGetterSetter(O,"blue",0,g,y.afterSetFilter);y.addGetterSetter(O,"red",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),y.addGetterSetter(O,"green",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),y.addGetterSetter(O,"blue",0,g,y.afterSetFilter),y.addGetterSetter(O,"alpha",1,(function(t){return this._filterUpToDate=!1,t>1?1:t<0?0:t}));y.addGetterSetter(O,"threshold",.5,u(),y.afterSetFilter);return pt.Util._assign(pt,{Arc:vt,Arrow:_t,Circle:yt,Ellipse:xt,Image:bt,Label:Ct,Tag:Pt,Line:mt,Path:kt,Rect:Tt,RegularPolygon:At,Ring:Gt,Sprite:Et,Star:Rt,Text:Bt,TextPath:Wt,Transformer:Vt,Wedge:Qt,Filters:{Blur:function(t){var e=Math.round(this.blurRadius());e>0&&function(t,e){var i,r,a,n,s,o,h,l,d,c,g,u,f,p,v,m,_,y,x,b,S,w,C,P,k=t.data,T=t.width,A=t.height,M=e+e+1,G=T-1,E=A-1,R=e+1,L=R*(R+1)/2,D=new Jt,I=null,O=D,F=null,B=null,N=Zt[e],z=$t[e];for(a=1;a>z,0!==C?(C=255/C,k[o]=(l*N>>z)*C,k[o+1]=(d*N>>z)*C,k[o+2]=(c*N>>z)*C):k[o]=k[o+1]=k[o+2]=0,l-=u,d-=f,c-=p,g-=v,u-=F.r,f-=F.g,p-=F.b,v-=F.a,n=h+((n=i+e+1)>z,C>0?(C=255/C,k[n]=(l*N>>z)*C,k[n+1]=(d*N>>z)*C,k[n+2]=(c*N>>z)*C):k[n]=k[n+1]=k[n+2]=0,l-=u,d-=f,c-=p,g-=v,u-=F.r,f-=F.g,p-=F.b,v-=F.a,n=i+((n=r+R)255?255:n,s=(s*=255)<0?0:s>255?255:s,o=(o*=255)<0?0:o>255?255:o,r[e]=n,r[e+1]=s,r[e+2]=o},Emboss:function(t){var e=10*this.embossStrength(),i=255*this.embossWhiteLevel(),r=this.embossDirection(),a=this.embossBlend(),n=0,s=0,o=t.data,h=t.width,l=t.height,c=4*h,g=l;switch(r){case"top-left":n=-1,s=-1;break;case"top":n=-1,s=0;break;case"top-right":n=-1,s=1;break;case"right":n=0,s=1;break;case"bottom-right":n=1,s=1;break;case"bottom":n=1,s=0;break;case"bottom-left":n=1,s=-1;break;case"left":n=0,s=-1;break;default:d.error("Unknown emboss direction: "+r)}do{var u=(g-1)*c,f=n;g+f<1&&(f=0),g+f>l&&(f=0);var p=(g-1+f)*h*4,v=h;do{var m=u+4*(v-1),_=s;v+_<1&&(_=0),v+_>h&&(_=0);var y=p+4*(v-1+_),x=o[m]-o[y],b=o[m+1]-o[y+1],S=o[m+2]-o[y+2],w=x,C=w>0?w:-w;if((b>0?b:-b)>C&&(w=b),(S>0?S:-S)>C&&(w=S),w*=e,a){var P=o[m]+w,k=o[m+1]+w,T=o[m+2]+w;o[m]=P>255?255:P<0?0:P,o[m+1]=k>255?255:k<0?0:k,o[m+2]=T>255?255:T<0?0:T}else{var A=i-w;A<0?A=0:A>255&&(A=255),o[m]=o[m+1]=o[m+2]=A}}while(--v)}while(--g)},Enhance:function(t){var e,i,r,a,n=t.data,s=n.length,o=n[0],h=o,l=n[1],d=l,c=n[2],g=c,u=this.enhance();if(0!==u){for(a=0;ah&&(h=e),(i=n[a+1])d&&(d=i),(r=n[a+2])g&&(g=r);var f,p,v,m,_,y,x,b,S;for(h===o&&(h=255,o=0),d===l&&(d=255,l=0),g===c&&(g=255,c=0),u>0?(p=h+u*(255-h),v=o-u*(o-0),_=d+u*(255-d),y=l-u*(l-0),b=g+u*(255-g),S=c-u*(c-0)):(p=h+u*(h-(f=.5*(h+o))),v=o+u*(o-f),_=d+u*(d-(m=.5*(d+l))),y=l+u*(l-m),b=g+u*(g-(x=.5*(g+c))),S=c+u*(c-x)),a=0;am?s:m;var _,y,x,b,S=d,w=l,C=360/w*Math.PI/180;for(y=0;yc&&(x=y,b=0,S=-1),i=0;iy?h:y;var x,b,S,w=g,C=c,P=i.polarRotation||0;for(a=0;a=0&&u=0&&f=0&&u=0&&f=1020?255:0}return s}(e=function(t,e,i){for(var r=[1,1,1,1,0,1,1,1,1],a=Math.round(Math.sqrt(r.length)),n=Math.floor(a/2),s=[],o=0;o=0&&u=0&&f=m))for(i=c;i=_||(a+=b[(r=4*(m*i+e))+0],n+=b[r+1],s+=b[r+2],o+=b[r+3],p+=1);for(a/=p,n/=p,s/=p,o/=p,e=h;e=m))for(i=c;i=_||(b[(r=4*(m*i+e))+0]=a,b[r+1]=n,b[r+2]=s,b[r+3]=o)}},Posterize:function(t){var e,i=Math.round(254*this.levels())+1,r=t.data,a=r.length,n=255/i;for(e=0;e127&&(h=255-h),l>127&&(l=255-l),d>127&&(d=255-d),e[o]=h,e[o+1]=l,e[o+2]=d}while(--s)}while(--a)},Threshold:function(t){var e,i=255*this.threshold(),r=t.data,a=r.length;for(e=0;ei.angleDeg?e*t:e,enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_mouseListenClick:!1,_touchListenClick:!1,_pointerListenClick:!1,_mouseInDblClickWindow:!1,_touchInDblClickWindow:!1,_pointerInDblClickWindow:!1,pixelRatio:"undefined"!=typeof window&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging:()=>i.DD.isDragging,isDragReady:()=>!!i.DD.node,document:e.document,_injectGlobal(t){e.Konva=t}},r=t=>{i[t.prototype.getClassName()]=t};i._injectGlobal(i);class a{constructor(t=[1,0,0,1,0,0]){this.dirty=!1,this.m=t&&t.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new a(this.m)}copyInto(t){t.m[0]=this.m[0],t.m[1]=this.m[1],t.m[2]=this.m[2],t.m[3]=this.m[3],t.m[4]=this.m[4],t.m[5]=this.m[5]}point(t){var e=this.m;return{x:e[0]*t.x+e[2]*t.y+e[4],y:e[1]*t.x+e[3]*t.y+e[5]}}translate(t,e){return this.m[4]+=this.m[0]*t+this.m[2]*e,this.m[5]+=this.m[1]*t+this.m[3]*e,this}scale(t,e){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=e,this.m[3]*=e,this}rotate(t){var e=Math.cos(t),i=Math.sin(t),r=this.m[0]*e+this.m[2]*i,a=this.m[1]*e+this.m[3]*i,n=this.m[0]*-i+this.m[2]*e,s=this.m[1]*-i+this.m[3]*e;return this.m[0]=r,this.m[1]=a,this.m[2]=n,this.m[3]=s,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(t,e){var i=this.m[0]+this.m[2]*e,r=this.m[1]+this.m[3]*e,a=this.m[2]+this.m[0]*t,n=this.m[3]+this.m[1]*t;return this.m[0]=i,this.m[1]=r,this.m[2]=a,this.m[3]=n,this}multiply(t){var e=this.m[0]*t.m[0]+this.m[2]*t.m[1],i=this.m[1]*t.m[0]+this.m[3]*t.m[1],r=this.m[0]*t.m[2]+this.m[2]*t.m[3],a=this.m[1]*t.m[2]+this.m[3]*t.m[3],n=this.m[0]*t.m[4]+this.m[2]*t.m[5]+this.m[4],s=this.m[1]*t.m[4]+this.m[3]*t.m[5]+this.m[5];return this.m[0]=e,this.m[1]=i,this.m[2]=r,this.m[3]=a,this.m[4]=n,this.m[5]=s,this}invert(){var t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),e=this.m[3]*t,i=-this.m[1]*t,r=-this.m[2]*t,a=this.m[0]*t,n=t*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),s=t*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=e,this.m[1]=i,this.m[2]=r,this.m[3]=a,this.m[4]=n,this.m[5]=s,this}getMatrix(){return this.m}setAbsolutePosition(t,e){var i=this.m[0],r=this.m[1],a=this.m[2],n=this.m[3],s=this.m[4],o=(i*(e-this.m[5])-r*(t-s))/(i*n-r*a),h=(t-s-a*o)/i;return this.translate(h,o)}decompose(){var t=this.m[0],e=this.m[1],i=this.m[2],r=this.m[3],a=t*r-e*i;let n={x:this.m[4],y:this.m[5],rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(0!=t||0!=e){var s=Math.sqrt(t*t+e*e);n.rotation=e>0?Math.acos(t/s):-Math.acos(t/s),n.scaleX=s,n.scaleY=a/s,n.skewX=(t*i+e*r)/a,n.skewY=0}else if(0!=i||0!=r){var o=Math.sqrt(i*i+r*r);n.rotation=Math.PI/2-(r>0?Math.acos(-i/o):-Math.acos(i/o)),n.scaleX=a/o,n.scaleY=o,n.skewX=0,n.skewY=(t*i+e*r)/a}return n.rotation=c._getRotation(n.rotation),n}}var n=Math.PI/180,s=180/Math.PI,o={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},h=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/,l=[];const d="undefined"!=typeof requestAnimationFrame&&requestAnimationFrame||function(t){setTimeout(t,60)},c={_isElement:t=>!(!t||1!=t.nodeType),_isFunction:t=>!!(t&&t.constructor&&t.call&&t.apply),_isPlainObject:t=>!!t&&t.constructor===Object,_isArray:t=>"[object Array]"===Object.prototype.toString.call(t),_isNumber:t=>"[object Number]"===Object.prototype.toString.call(t)&&!isNaN(t)&&isFinite(t),_isString:t=>"[object String]"===Object.prototype.toString.call(t),_isBoolean:t=>"[object Boolean]"===Object.prototype.toString.call(t),isObject:t=>t instanceof Object,isValidSelector(t){if("string"!=typeof t)return!1;var e=t[0];return"#"===e||"."===e||e===e.toUpperCase()},_sign:t=>0===t||t>0?1:-1,requestAnimFrame(t){l.push(t),1===l.length&&d((function(){const t=l;l=[],t.forEach((function(t){t()}))}))},createCanvasElement(){var t=document.createElement("canvas");try{t.style=t.style||{}}catch(t){}return t},createImageElement:()=>document.createElement("img"),_isInDocument(t){for(;t=t.parentNode;)if(t==document)return!0;return!1},_urlToImage(t,e){var i=c.createImageElement();i.onload=function(){e(i)},i.src=t},_rgbToHex:(t,e,i)=>((1<<24)+(t<<16)+(e<<8)+i).toString(16).slice(1),_hexToRgb(t){t=t.replace("#","");var e=parseInt(t,16);return{r:e>>16&255,g:e>>8&255,b:255&e}},getRandomColor(){for(var t=(16777215*Math.random()<<0).toString(16);t.length<6;)t="0"+t;return"#"+t},getRGB(t){var e;return t in o?{r:(e=o[t])[0],g:e[1],b:e[2]}:"#"===t[0]?this._hexToRgb(t.substring(1)):"rgb("===t.substr(0,4)?(e=h.exec(t.replace(/ /g,"")),{r:parseInt(e[1],10),g:parseInt(e[2],10),b:parseInt(e[3],10)}):{r:0,g:0,b:0}},colorToRGBA:t=>(t=t||"black",c._namedColorToRBA(t)||c._hex3ColorToRGBA(t)||c._hex6ColorToRGBA(t)||c._rgbColorToRGBA(t)||c._rgbaColorToRGBA(t)||c._hslColorToRGBA(t)),_namedColorToRBA(t){var e=o[t.toLowerCase()];return e?{r:e[0],g:e[1],b:e[2],a:1}:null},_rgbColorToRGBA(t){if(0===t.indexOf("rgb(")){var e=(t=t.match(/rgb\(([^)]+)\)/)[1]).split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:1}}},_rgbaColorToRGBA(t){if(0===t.indexOf("rgba(")){var e=(t=t.match(/rgba\(([^)]+)\)/)[1]).split(/ *, */).map(Number);return{r:e[0],g:e[1],b:e[2],a:e[3]}}},_hex6ColorToRGBA(t){if("#"===t[0]&&7===t.length)return{r:parseInt(t.slice(1,3),16),g:parseInt(t.slice(3,5),16),b:parseInt(t.slice(5,7),16),a:1}},_hex3ColorToRGBA(t){if("#"===t[0]&&4===t.length)return{r:parseInt(t[1]+t[1],16),g:parseInt(t[2]+t[2],16),b:parseInt(t[3]+t[3],16),a:1}},_hslColorToRGBA(t){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(t)){const[e,...i]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(t),r=Number(i[0])/360,a=Number(i[1])/100,n=Number(i[2])/100;let s,o,h;if(0===a)return h=255*n,{r:Math.round(h),g:Math.round(h),b:Math.round(h),a:1};s=n<.5?n*(1+a):n+a-n*a;const l=2*n-s,d=[0,0,0];for(let t=0;t<3;t++)o=r+1/3*-(t-1),o<0&&o++,o>1&&o--,h=6*o<1?l+6*(s-l)*o:2*o<1?s:3*o<2?l+(s-l)*(2/3-o)*6:l,d[t]=255*h;return{r:Math.round(d[0]),g:Math.round(d[1]),b:Math.round(d[2]),a:1}}},haveIntersection:(t,e)=>!(e.x>t.x+t.width||e.x+e.widtht.y+t.height||e.y+e.heightt.slice(0),degToRad:t=>t*n,radToDeg:t=>t*s,_degToRad:t=>(c.warn("Util._degToRad is removed. Please use public Util.degToRad instead."),c._degToRad(t)),_radToDeg:t=>(c.warn("Util._radToDeg is removed. Please use public Util.radToDeg instead."),c._radToDeg(t)),_getRotation:t=>i.angleDeg?c.radToDeg(t):t,_capitalize:t=>t.charAt(0).toUpperCase()+t.slice(1),throw(t){throw new Error("Konva error: "+t)},error(t){console.error("Konva error: "+t)},warn(t){i.showWarnings&&console.warn("Konva warning: "+t)},each(t,e){for(var i in t)e(i,t[i])},_inRange:(t,e,i)=>e<=t&&t1?(s=i,o=r,h=(i-a)*(i-a)+(r-n)*(r-n)):h=((s=t+d*(i-t))-a)*(s-a)+((o=e+d*(r-e))-n)*(o-n)}return[s,o,h]},_getProjectionToLine(t,e,i){var r=c.cloneObject(t),a=Number.MAX_VALUE;return e.forEach((function(n,s){if(i||s!==e.length-1){var o=e[(s+1)%e.length],h=c._getProjectionToSegment(n.x,n.y,o.x,o.y,t.x,t.y),l=h[0],d=h[1],g=h[2];ge.length){var s=e;e=t,t=s}for(r=0;rt.touches?t.changedTouches[0].identifier:999};function g(t){return c._isString(t)?'"'+t+'"':"[object Number]"===Object.prototype.toString.call(t)||c._isBoolean(t)?t:Object.prototype.toString.call(t)}function u(t){return t>255?255:t<0?0:Math.round(t)}function f(){if(i.isUnminified)return function(t,e){return c._isNumber(t)||c.warn(g(t)+' is a not valid value for "'+e+'" attribute. The value should be a number.'),t}}function p(t){if(i.isUnminified)return function(e,i){let r=c._isNumber(e),a=c._isArray(e)&&e.length==t;return r||a||c.warn(g(e)+' is a not valid value for "'+i+'" attribute. The value should be a number or Array('+t+")"),e}}function v(){if(i.isUnminified)return function(t,e){return c._isNumber(t)||"auto"===t||c.warn(g(t)+' is a not valid value for "'+e+'" attribute. The value should be a number or "auto".'),t}}function m(){if(i.isUnminified)return function(t,e){return c._isString(t)||c.warn(g(t)+' is a not valid value for "'+e+'" attribute. The value should be a string.'),t}}function _(){if(i.isUnminified)return function(t,e){const i=c._isString(t),r="[object CanvasGradient]"===Object.prototype.toString.call(t)||t&&t.addColorStop;return i||r||c.warn(g(t)+' is a not valid value for "'+e+'" attribute. The value should be a string or a native gradient.'),t}}function y(){if(i.isUnminified)return function(t,e){return!0===t||!1===t||c.warn(g(t)+' is a not valid value for "'+e+'" attribute. The value should be a boolean.'),t}}const x={addGetterSetter(t,e,i,r,a){x.addGetter(t,e,i),x.addSetter(t,e,r,a),x.addOverloadedGetterSetter(t,e)},addGetter(t,e,i){var r="get"+c._capitalize(e);t.prototype[r]=t.prototype[r]||function(){var t=this.attrs[e];return void 0===t?i:t}},addSetter(t,e,i,r){var a="set"+c._capitalize(e);t.prototype[a]||x.overWriteSetter(t,e,i,r)},overWriteSetter(t,e,i,r){var a="set"+c._capitalize(e);t.prototype[a]=function(t){return i&&null!=t&&(t=i.call(this,t,e)),this._setAttr(e,t),r&&r.call(this),this}},addComponentsGetterSetter(t,e,r,a,n){var s,o,h=r.length,l=c._capitalize,d="get"+l(e),u="set"+l(e);t.prototype[d]=function(){var t={};for(s=0;s"number"==typeof t?Math.floor(t):t)),h+="("+n.join(",")+")")):(h+=r.property,t||(h+="="+r.val)),h+=";";return h}clearTrace(){this.traceArr=[]}_trace(t){var e=this.traceArr;e.push(t),e.length>=100&&e.shift()}reset(){var t=this.getCanvas().getPixelRatio();this.setTransform(1*t,0,0,1*t,0,0)}getCanvas(){return this.canvas}clear(t){var e=this.getCanvas();t?this.clearRect(t.x||0,t.y||0,t.width||0,t.height||0):this.clearRect(0,0,e.getWidth()/e.pixelRatio,e.getHeight()/e.pixelRatio)}_applyLineCap(t){var e=t.getLineCap();e&&this.setAttr("lineCap",e)}_applyOpacity(t){var e=t.getAbsoluteOpacity();1!==e&&this.setAttr("globalAlpha",e)}_applyLineJoin(t){var e=t.attrs.lineJoin;e&&this.setAttr("lineJoin",e)}setAttr(t,e){this._context[t]=e}arc(t,e,i,r,a,n){this._context.arc(t,e,i,r,a,n)}arcTo(t,e,i,r,a){this._context.arcTo(t,e,i,r,a)}beginPath(){this._context.beginPath()}bezierCurveTo(t,e,i,r,a,n){this._context.bezierCurveTo(t,e,i,r,a,n)}clearRect(t,e,i,r){this._context.clearRect(t,e,i,r)}clip(){this._context.clip()}closePath(){this._context.closePath()}createImageData(t,e){var i=arguments;return 2===i.length?this._context.createImageData(t,e):1===i.length?this._context.createImageData(t):void 0}createLinearGradient(t,e,i,r){return this._context.createLinearGradient(t,e,i,r)}createPattern(t,e){return this._context.createPattern(t,e)}createRadialGradient(t,e,i,r,a,n){return this._context.createRadialGradient(t,e,i,r,a,n)}drawImage(t,e,i,r,a,n,s,o,h){var l=arguments,d=this._context;3===l.length?d.drawImage(t,e,i):5===l.length?d.drawImage(t,e,i,r,a):9===l.length&&d.drawImage(t,e,i,r,a,n,s,o,h)}ellipse(t,e,i,r,a,n,s,o){this._context.ellipse(t,e,i,r,a,n,s,o)}isPointInPath(t,e){return this._context.isPointInPath(t,e)}fill(t){t?this._context.fill(t):this._context.fill()}fillRect(t,e,i,r){this._context.fillRect(t,e,i,r)}strokeRect(t,e,i,r){this._context.strokeRect(t,e,i,r)}fillText(t,e,i,r){r?this._context.fillText(t,e,i,r):this._context.fillText(t,e,i)}measureText(t){return this._context.measureText(t)}getImageData(t,e,i,r){return this._context.getImageData(t,e,i,r)}lineTo(t,e){this._context.lineTo(t,e)}moveTo(t,e){this._context.moveTo(t,e)}rect(t,e,i,r){this._context.rect(t,e,i,r)}putImageData(t,e,i){this._context.putImageData(t,e,i)}quadraticCurveTo(t,e,i,r){this._context.quadraticCurveTo(t,e,i,r)}restore(){this._context.restore()}rotate(t){this._context.rotate(t)}save(){this._context.save()}scale(t,e){this._context.scale(t,e)}setLineDash(t){this._context.setLineDash?this._context.setLineDash(t):"mozDash"in this._context?this._context.mozDash=t:"webkitLineDash"in this._context&&(this._context.webkitLineDash=t)}getLineDash(){return this._context.getLineDash()}setTransform(t,e,i,r,a,n){this._context.setTransform(t,e,i,r,a,n)}stroke(t){t?this._context.stroke(t):this._context.stroke()}strokeText(t,e,i,r){this._context.strokeText(t,e,i,r)}transform(t,e,i,r,a,n){this._context.transform(t,e,i,r,a,n)}translate(t,e){this._context.translate(t,e)}_enableTrace(){var t,e,i=this,r=S.length,a=this.setAttr,n=function(t){var r,a=i[t];i[t]=function(){return e=b(Array.prototype.slice.call(arguments,0)),r=a.apply(i,arguments),i._trace({method:t,args:e}),r}};for(t=0;t{"dragging"===e.dragStatus&&(t=!0)}),t},justDragged:!1,get node(){var t;return G._dragElements.forEach(e=>{t=e.node}),t},_dragElements:new Map,_drag(t){const e=[];G._dragElements.forEach((i,r)=>{const{node:a}=i,n=a.getStage();n.setPointersPositions(t),void 0===i.pointerId&&(i.pointerId=c._getFirstPointerId(t));const s=n._changedPointerPositions.find(t=>t.id===i.pointerId);if(s){if("dragging"!==i.dragStatus){var o=a.dragDistance();if(Math.max(Math.abs(s.x-i.startPointerPos.x),Math.abs(s.y-i.startPointerPos.y)){e.fire("dragmove",{type:"dragmove",target:e,evt:t},!0)})},_endDragBefore(t){G._dragElements.forEach(e=>{const{node:r}=e,a=r.getStage();t&&a.setPointersPositions(t);if(!a._changedPointerPositions.find(t=>t.id===e.pointerId))return;"dragging"!==e.dragStatus&&"stopped"!==e.dragStatus||(G.justDragged=!0,i._mouseListenClick=!1,i._touchListenClick=!1,i._pointerListenClick=!1,e.dragStatus="stopped");const n=e.node.getLayer()||e.node instanceof i.Stage&&e.node;n&&n.batchDraw()})},_endDragAfter(t){G._dragElements.forEach((e,i)=>{"stopped"===e.dragStatus&&e.node.fire("dragend",{type:"dragend",target:e.node,evt:t},!0),"dragging"!==e.dragStatus&&G._dragElements.delete(i)})}};i.isBrowser&&(window.addEventListener("mouseup",G._endDragBefore,!0),window.addEventListener("touchend",G._endDragBefore,!0),window.addEventListener("mousemove",G._drag),window.addEventListener("touchmove",G._drag),window.addEventListener("mouseup",G._endDragAfter,!1),window.addEventListener("touchend",G._endDragAfter,!1));var E=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(" ");let R=1;class L{constructor(t){this._id=R++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(t),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(t){"transform"!==t&&"absoluteTransform"!==t||!this._cache.get(t)?t?this._cache.delete(t):this._cache.clear():this._cache.get(t).dirty=!0}_getCache(t,e){var i=this._cache.get(t);return(void 0===i||("transform"===t||"absoluteTransform"===t)&&!0===i.dirty)&&(i=e.call(this),this._cache.set(t,i)),i}_calculate(t,e,i){if(!this._attachedDepsListeners.get(t)){const i=e.map(t=>t+"Change.konva").join(" ");this.on(i,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,i)}_getCanvasCache(){return this._cache.get("canvas")}_clearSelfAndDescendantCache(t){this._clearCache(t),"absoluteTransform"===t&&this.fire("absoluteTransformChange")}clearCache(){return this._cache.delete("canvas"),this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(t){var e=t||{},i={};void 0!==e.x&&void 0!==e.y&&void 0!==e.width&&void 0!==e.height||(i=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()}));var r=Math.ceil(e.width||i.width),a=Math.ceil(e.height||i.height),n=e.pixelRatio,s=void 0===e.x?i.x:e.x,o=void 0===e.y?i.y:e.y,h=e.offset||0,l=e.drawBorder||!1,d=e.hitCanvasPixelRatio||1;if(r&&a){s-=h,o-=h;var g=new A({pixelRatio:n,width:r+=2*h,height:a+=2*h}),u=new A({pixelRatio:n,width:0,height:0}),f=new M({pixelRatio:d,width:r,height:a}),p=g.getContext(),v=f.getContext();return f.isCache=!0,g.isCache=!0,this._cache.delete("canvas"),this._filterUpToDate=!1,!1===e.imageSmoothingEnabled&&(g.getContext()._context.imageSmoothingEnabled=!1,u.getContext()._context.imageSmoothingEnabled=!1),p.save(),v.save(),p.translate(-s,-o),v.translate(-s,-o),this._isUnderCache=!0,this._clearSelfAndDescendantCache("absoluteOpacity"),this._clearSelfAndDescendantCache("absoluteScale"),this.drawScene(g,this),this.drawHit(f,this),this._isUnderCache=!1,p.restore(),v.restore(),l&&(p.save(),p.beginPath(),p.rect(0,0,r,a),p.closePath(),p.setAttr("strokeStyle","red"),p.setAttr("lineWidth",5),p.stroke(),p.restore()),this._cache.set("canvas",{scene:g,filter:u,hit:f,x:s,y:o}),this._requestDraw(),this}c.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.")}isCached(){return this._cache.has("canvas")}getClientRect(t){throw new Error('abstract "getClientRect" method call')}_transformedRect(t,e){var i,r,a,n,s=[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x+t.width,y:t.y+t.height},{x:t.x,y:t.y+t.height}],o=this.getAbsoluteTransform(e);return s.forEach((function(t){var e=o.point(t);void 0===i&&(i=a=e.x,r=n=e.y),i=Math.min(i,e.x),r=Math.min(r,e.y),a=Math.max(a,e.x),n=Math.max(n,e.y)})),{x:i,y:r,width:a-i,height:n-r}}_drawCachedSceneCanvas(t){t.save(),t._applyOpacity(this),t._applyGlobalCompositeOperation(this);const e=this._getCanvasCache();t.translate(e.x,e.y);var i=this._getCachedSceneCanvas(),r=i.pixelRatio;t.drawImage(i._canvas,0,0,i.width/r,i.height/r),t.restore()}_drawCachedHitCanvas(t){var e=this._getCanvasCache(),i=e.hit;t.save(),t.translate(e.x,e.y),t.drawImage(i._canvas,0,0,i.width/i.pixelRatio,i.height/i.pixelRatio),t.restore()}_getCachedSceneCanvas(){var t,e,i,r,a=this.filters(),n=this._getCanvasCache(),s=n.scene,o=n.filter,h=o.getContext();if(a){if(!this._filterUpToDate){var l=s.pixelRatio;o.setSize(s.width/s.pixelRatio,s.height/s.pixelRatio);try{for(t=a.length,h.clear(),h.drawImage(s._canvas,0,0,s.getWidth()/l,s.getHeight()/l),e=h.getImageData(0,0,o.getWidth(),o.getHeight()),i=0;i{var e,i;if(!t)return this;for(e in t)"children"!==e&&(i="set"+c._capitalize(e),c._isFunction(this[i])?this[i](t[e]):this._setAttr(e,t[e]))}),this}isListening(){return this._getCache("listening",this._isListening)}_isListening(t){if(!this.listening())return!1;const e=this.getParent();return!e||e===t||this===t||e._isListening(t)}isVisible(){return this._getCache("visible",this._isVisible)}_isVisible(t){if(!this.visible())return!1;const e=this.getParent();return!e||e===t||this===t||e._isVisible(t)}shouldDrawHit(t,e=!1){if(t)return this._isVisible(t)&&this._isListening(t);var r=this.getLayer(),a=!1;G._dragElements.forEach(t=>{"dragging"===t.dragStatus&&("Stage"===t.node.nodeType||t.node.getLayer()===r)&&(a=!0)});var n=!e&&!i.hitOnDragEnabled&&a;return this.isListening()&&this.isVisible()&&!n}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){var t,e,i,r,a=this.getDepth(),n=this,s=0;return"Stage"!==n.nodeType&&function o(h){for(t=[],e=h.length,i=0;i0&&t[0].getDepth()<=a&&o(t)}(n.getStage().getChildren()),s}getDepth(){for(var t=0,e=this.parent;e;)t++,e=e.parent;return t}_batchTransformChanges(t){this._batchingTransformChange=!0,t(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")),this._needClearTransformCache=!1}setPosition(t){return this._batchTransformChanges(()=>{this.x(t.x),this.y(t.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){if(!this.getStage())return null;var t=this.getStage().getPointerPosition();if(!t)return null;var e=this.getAbsoluteTransform().copy();return e.invert(),e.point(t)}getAbsolutePosition(t){let e=!1,i=this.parent;for(;i;){if(i.isCached()){e=!0;break}i=i.parent}e&&!t&&(t=!0);var r=this.getAbsoluteTransform(t).getMatrix(),n=new a,s=this.offset();return n.m=r.slice(),n.translate(s.x,s.y),n.getTranslation()}setAbsolutePosition(t){var e=this._clearTransform();this.attrs.x=e.x,this.attrs.y=e.y,delete e.x,delete e.y,this._clearCache("transform");var i=this._getAbsoluteTransform().copy();return i.invert(),i.translate(t.x,t.y),t={x:this.attrs.x+i.getTranslation().x,y:this.attrs.y+i.getTranslation().y},this._setTransform(e),this.setPosition({x:t.x,y:t.y}),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform"),this}_setTransform(t){var e;for(e in t)this.attrs[e]=t[e]}_clearTransform(){var t={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,t}move(t){var e=t.x,i=t.y,r=this.x(),a=this.y();return void 0!==e&&(r+=e),void 0!==i&&(a+=i),this.setPosition({x:r,y:a}),this}_eachAncestorReverse(t,e){var i,r,a=[],n=this.getParent();if(!e||e._id!==this._id){for(a.unshift(this);n&&(!e||n._id!==e._id);)a.unshift(n),n=n.parent;for(i=a.length,r=0;r0&&(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0)}moveToBottom(){if(!this.parent)return c.warn("Node has no parent. moveToBottom function is ignored."),!1;var t=this.index;return t>0&&(this.parent.children.splice(t,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0)}setZIndex(t){if(!this.parent)return c.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&c.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");var e=this.index;return this.parent.children.splice(e,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache("absoluteOpacity",this._getAbsoluteOpacity)}_getAbsoluteOpacity(){var t=this.opacity(),e=this.getParent();return e&&!e._isUnderCache&&(t*=e.getAbsoluteOpacity()),t}moveTo(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this}toObject(){var t,e,i,r,a={},n=this.getAttrs();for(t in a.attrs={},n)e=n[t],c.isObject(e)&&!c._isPlainObject(e)&&!c._isArray(e)||(i="function"==typeof this[t]&&this[t],delete n[t],r=i?i.call(this):null,n[t]=e,r!==e&&(a.attrs[t]=e));return a.className=this.getClassName(),c._prepareToStringify(a)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(t,e,i){var r=[];e&&this._isMatch(t)&&r.push(this);for(var a=this.parent;a;){if(a===i)return r;a._isMatch(t)&&r.push(a),a=a.parent}return r}isAncestorOf(t){return!1}findAncestor(t,e,i){return this.findAncestors(t,e,i)[0]}_isMatch(t){if(!t)return!1;if("function"==typeof t)return t(this);var e,i,r=t.replace(/ /g,"").split(","),a=r.length;for(e=0;e=0)&&!this.isDragging()){var e=!1;G._dragElements.forEach(t=>{this.isAncestorOf(t.node)&&(e=!0)}),e||this._createDragElement(t)}}))}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const t=G._dragElements.get(this._id),e=t&&"dragging"===t.dragStatus,i=t&&"ready"===t.dragStatus;e?this.stopDrag():i&&G._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(t={x:0,y:0}){const e=this.getStage();if(!e)return!1;const i={x:-t.x,y:-t.y,width:e.width()+t.x,height:e.height()+t.y};return c.haveIntersection(i,this.getClientRect())}static create(t,e){return c._isString(t)&&(t=JSON.parse(t)),this._createNode(t,e)}static _createNode(t,e){var r,a,n,s=L.prototype.getClassName.call(t),o=t.children;e&&(t.attrs.container=e),i[s]||(c.warn('Can not find a node with class name "'+s+'". Fallback to "Shape".'),s="Shape");if(r=new(0,i[s])(t.attrs),o)for(a=o.length,n=0;n0}removeChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.remove()}),this.children=[],this}destroyChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.destroy()}),this.children=[],this}add(...t){if(arguments.length>1){for(var e=0;e0?e[0]:void 0}_generalFind(t,e){var i=[];return this._descendants(r=>{const a=r._isMatch(t);return a&&i.push(r),!(!a||!e)}),i}_descendants(t){let e=!1;const i=this.getChildren();for(const r of i){if(e=t(r),e)return!0;if(r.hasChildren()&&(e=r._descendants(t),e))return!0}return!1}toObject(){var t=L.prototype.toObject.call(this);return t.children=[],this.getChildren().forEach(e=>{t.children.push(e.toObject())}),t}isAncestorOf(t){for(var e=t.getParent();e;){if(e._id===this._id)return!0;e=e.getParent()}return!1}clone(t){var e=L.prototype.clone.call(this,t);return this.getChildren().forEach((function(t){e.add(t.clone())})),e}getAllIntersections(t){var e=[];return this.find("Shape").forEach((function(i){i.isVisible()&&i.intersects(t)&&e.push(i)})),e}_clearSelfAndDescendantCache(t){var e;super._clearSelfAndDescendantCache(t),this.isCached()||null===(e=this.children)||void 0===e||e.forEach((function(e){e._clearSelfAndDescendantCache(t)}))}_setChildrenIndices(){var t;null===(t=this.children)||void 0===t||t.forEach((function(t,e){t.index=e})),this._requestDraw()}drawScene(t,e){var i=this.getLayer(),r=t||i&&i.getCanvas(),a=r&&r.getContext(),n=this._getCanvasCache(),s=n&&n.scene,o=r&&r.isCache;if(!this.isVisible()&&!o)return this;if(s){a.save();var h=this.getAbsoluteTransform(e).getMatrix();a.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedSceneCanvas(a),a.restore()}else this._drawChildren("drawScene",r,e);return this}drawHit(t,e){if(!this.shouldDrawHit(e))return this;var i=this.getLayer(),r=t||i&&i.hitCanvas,a=r&&r.getContext(),n=this._getCanvasCache();if(n&&n.hit){a.save();var s=this.getAbsoluteTransform(e).getMatrix();a.transform(s[0],s[1],s[2],s[3],s[4],s[5]),this._drawCachedHitCanvas(a),a.restore()}else this._drawChildren("drawHit",r,e);return this}_drawChildren(t,e,i){var r,a=e&&e.getContext(),n=this.clipWidth(),s=this.clipHeight(),o=this.clipFunc(),h=n&&s||o;const l=i===this;if(h){a.save();var d=this.getAbsoluteTransform(i),c=d.getMatrix();if(a.transform(c[0],c[1],c[2],c[3],c[4],c[5]),a.beginPath(),o)o.call(this,a,this);else{var g=this.clipX(),u=this.clipY();a.rect(g,u,n,s)}a.clip(),c=d.copy().invert().getMatrix(),a.transform(c[0],c[1],c[2],c[3],c[4],c[5])}var f=!l&&"source-over"!==this.globalCompositeOperation()&&"drawScene"===t;f&&(a.save(),a._applyGlobalCompositeOperation(this)),null===(r=this.children)||void 0===r||r.forEach((function(r){r[t](e,i)})),f&&a.restore(),h&&a.restore()}getClientRect(t){var e,i,r,a,n,s=(t=t||{}).skipTransform,o=t.relativeTo,h={x:1/0,y:1/0,width:0,height:0},l=this;null===(e=this.children)||void 0===e||e.forEach((function(e){if(e.visible()){var s=e.getClientRect({relativeTo:l,skipShadow:t.skipShadow,skipStroke:t.skipStroke});0===s.width&&0===s.height||(void 0===i?(i=s.x,r=s.y,a=s.x+s.width,n=s.y+s.height):(i=Math.min(i,s.x),r=Math.min(r,s.y),a=Math.max(a,s.x+s.width),n=Math.max(n,s.y+s.height)))}}));for(var d=this.find("Shape"),c=!1,g=0;gt.indexOf("pointer")>=0?"pointer":t.indexOf("touch")>=0?"touch":"mouse",U=t=>{const e=j(t);return"pointer"===e?i.pointerEventsEnabled&&X.pointer:"touch"===e?X.touch:"mouse"===e?X.mouse:void 0};function q(t={}){return(t.clipFunc||t.clipWidth||t.clipHeight)&&c.warn("Stage does not support clipping. Please use clip for Layers or Groups."),t}const V=[];class K extends O{constructor(t){super(q(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),V.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{q(this.attrs)}),this._checkVisibility()}_validateAdd(t){const e="Layer"===t.getType(),i="FastLayer"===t.getType();e||i||c.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const t=this.visible()?"":"none";this.content.style.display=t}setContainer(t){if("string"==typeof t){if("."===t.charAt(0)){var e=t.slice(1);t=document.getElementsByClassName(e)[0]}else{var i;i="#"!==t.charAt(0)?t:t.slice(1),t=document.getElementById(i)}if(!t)throw"Can not find container in document with id "+i}return this._setAttr("container",t),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),t.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){var t,e=this.children,i=e.length;for(t=0;t-1&&V.splice(e,1),this}getPointerPosition(){const t=this._pointerPositions[0]||this._changedPointerPositions[0];return t?{x:t.x,y:t.y}:(c.warn("Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);"),null)}_getPointerById(t){return this._pointerPositions.find(e=>e.id===t)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(t){(t=t||{}).x=t.x||0,t.y=t.y||0,t.width=t.width||this.width(),t.height=t.height||this.height();var e=new A({width:t.width,height:t.height,pixelRatio:t.pixelRatio||1}),i=e.getContext()._context,r=this.children;return(t.x||t.y)&&i.translate(-1*t.x,-1*t.y),r.forEach((function(e){if(e.isVisible()){var r=e._toKonvaCanvas(t);i.drawImage(r._canvas,t.x,t.y,r.getWidth()/r.getPixelRatio(),r.getHeight()/r.getPixelRatio())}})),e}getIntersection(t){if(!t)return null;var e,i=this.children;for(e=i.length-1;e>=0;e--){const r=i[e].getIntersection(t);if(r)return r}return null}_resizeDOM(){var t=this.width(),e=this.height();this.content&&(this.content.style.width=t+"px",this.content.style.height=e+"px"),this.bufferCanvas.setSize(t,e),this.bufferHitCanvas.setSize(t,e),this.children.forEach(i=>{i.setSize({width:t,height:e}),i.draw()})}add(t,...e){if(arguments.length>1){for(var r=0;r5&&c.warn("The stage has "+a+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),t.setSize({width:this.width(),height:this.height()}),t.draw(),i.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return z(t,this)}setPointerCapture(t){W(t,this)}releaseCapture(t){H(t)}getLayers(){return this.children}_bindContentEvents(){i.isBrowser&&Y.forEach(([t,e])=>{this.content.addEventListener(t,t=>{this[e](t)})})}_pointerenter(t){this.setPointersPositions(t);const e=U(t.type);this._fire(e.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const e=U(t.type);this._fire(e.pointerover,{evt:t,target:this,currentTarget:this})}_getTargetShape(t){let e=this[t+"targetShape"];return e&&!e.getStage()&&(e=null),e}_pointerleave(t){const e=U(t.type),r=j(t.type);if(e){this.setPointersPositions(t);var a=this._getTargetShape(r),n=!G.isDragging||i.hitOnDragEnabled;a&&n?(a._fireAndBubble(e.pointerout,{evt:t}),a._fireAndBubble(e.pointerleave,{evt:t}),this._fire(e.pointerleave,{evt:t,target:this,currentTarget:this}),this[r+"targetShape"]=null):n&&(this._fire(e.pointerleave,{evt:t,target:this,currentTarget:this}),this._fire(e.pointerout,{evt:t,target:this,currentTarget:this})),this.pointerPos=void 0,this._pointerPositions=[]}}_pointerdown(t){const e=U(t.type),r=j(t.type);if(e){this.setPointersPositions(t);var a=!1;this._changedPointerPositions.forEach(n=>{var s=this.getIntersection(n);G.justDragged=!1,i["_"+r+"ListenClick"]=!0;if(!(s&&s.isListening()))return;i.capturePointerEventsEnabled&&s.setPointerCapture(n.id),this[r+"ClickStartShape"]=s,s._fireAndBubble(e.pointerdown,{evt:t,pointerId:n.id}),a=!0;const o=t.type.indexOf("touch")>=0;s.preventDefault()&&t.cancelable&&o&&t.preventDefault()}),a||this._fire(e.pointerdown,{evt:t,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}}_pointermove(t){const e=U(t.type),r=j(t.type);if(!e)return;if(G.isDragging&&G.node.preventDefault()&&t.cancelable&&t.preventDefault(),this.setPointersPositions(t),!(!G.isDragging||i.hitOnDragEnabled))return;var a={};let n=!1;var s=this._getTargetShape(r);this._changedPointerPositions.forEach(i=>{const o=N(i.id)||this.getIntersection(i),h=i.id,l={evt:t,pointerId:h};var d=s!==o;if(d&&s&&(s._fireAndBubble(e.pointerout,l,o),s._fireAndBubble(e.pointerleave,l,o)),o){if(a[o._id])return;a[o._id]=!0}o&&o.isListening()?(n=!0,d&&(o._fireAndBubble(e.pointerover,l,s),o._fireAndBubble(e.pointerenter,l,s),this[r+"targetShape"]=o),o._fireAndBubble(e.pointermove,l)):s&&(this._fire(e.pointerover,{evt:t,target:this,currentTarget:this,pointerId:h}),this[r+"targetShape"]=null)}),n||this._fire(e.pointermove,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(t){const e=U(t.type),r=j(t.type);if(!e)return;this.setPointersPositions(t);const a=this[r+"ClickStartShape"],n=this[r+"ClickEndShape"];var s={};let o=!1;this._changedPointerPositions.forEach(h=>{const l=N(h.id)||this.getIntersection(h);if(l){if(l.releaseCapture(h.id),s[l._id])return;s[l._id]=!0}const d=h.id,c={evt:t,pointerId:d};let g=!1;i["_"+r+"InDblClickWindow"]?(g=!0,clearTimeout(this[r+"DblTimeout"])):G.justDragged||(i["_"+r+"InDblClickWindow"]=!0,clearTimeout(this[r+"DblTimeout"])),this[r+"DblTimeout"]=setTimeout((function(){i["_"+r+"InDblClickWindow"]=!1}),i.dblClickWindow),l&&l.isListening()?(o=!0,this[r+"ClickEndShape"]=l,l._fireAndBubble(e.pointerup,c),i["_"+r+"ListenClick"]&&a&&a===l&&(l._fireAndBubble(e.pointerclick,c),g&&n&&n===l&&l._fireAndBubble(e.pointerdblclick,c))):(this[r+"ClickEndShape"]=null,i["_"+r+"ListenClick"]&&this._fire(e.pointerclick,{evt:t,target:this,currentTarget:this,pointerId:d}),g&&this._fire(e.pointerdblclick,{evt:t,target:this,currentTarget:this,pointerId:d}))}),o||this._fire(e.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),i["_"+r+"ListenClick"]=!1,t.cancelable&&t.preventDefault()}_contextmenu(t){this.setPointersPositions(t);var e=this.getIntersection(this.getPointerPosition());e&&e.isListening()?e._fireAndBubble("contextmenu",{evt:t}):this._fire("contextmenu",{evt:t,target:this,currentTarget:this})}_wheel(t){this.setPointersPositions(t);var e=this.getIntersection(this.getPointerPosition());e&&e.isListening()?e._fireAndBubble("wheel",{evt:t}):this._fire("wheel",{evt:t,target:this,currentTarget:this})}_pointercancel(t){this.setPointersPositions(t);const e=N(t.pointerId)||this.getIntersection(this.getPointerPosition());e&&e._fireAndBubble("pointerup",B(t)),H(t.pointerId)}_lostpointercapture(t){H(t.pointerId)}setPointersPositions(t){var e=this._getContentPosition(),i=null,r=null;void 0!==(t=t||window.event).touches?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(t.touches,t=>{this._pointerPositions.push({id:t.identifier,x:(t.clientX-e.left)/e.scaleX,y:(t.clientY-e.top)/e.scaleY})}),Array.prototype.forEach.call(t.changedTouches||t.touches,t=>{this._changedPointerPositions.push({id:t.identifier,x:(t.clientX-e.left)/e.scaleX,y:(t.clientY-e.top)/e.scaleY})})):(i=(t.clientX-e.left)/e.scaleX,r=(t.clientY-e.top)/e.scaleY,this.pointerPos={x:i,y:r},this._pointerPositions=[{x:i,y:r,id:c._getFirstPointerId(t)}],this._changedPointerPositions=[{x:i,y:r,id:c._getFirstPointerId(t)}])}_setPointerPosition(t){c.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(t)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};var t=this.content.getBoundingClientRect();return{top:t.top,left:t.left,scaleX:t.width/this.content.clientWidth||1,scaleY:t.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new A({width:this.width(),height:this.height()}),this.bufferHitCanvas=new M({pixelRatio:1,width:this.width(),height:this.height()}),i.isBrowser){var t=this.container();if(!t)throw"Stage has no container. A container is required.";t.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),t.appendChild(this.content),this._resizeDOM()}}cache(){return c.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach((function(t){t.batchDraw()})),this}}K.prototype.nodeType="Stage",r(K),x.addGetterSetter(K,"container");let Q;function J(){return Q||(Q=c.createCanvasElement().getContext("2d"),Q)}const Z={};class $ extends L{constructor(t){let e;for(super(t);e=c.getRandomColor(),!e||e in Z;);this.colorKey=e,Z[e]=this}getContext(){return this.getLayer().getContext()}getCanvas(){return this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache("hasShadow",this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&0!==this.shadowOpacity()&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache("patternImage",this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const t=J().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(t&&t.setTransform){const e=new a;e.translate(this.fillPatternX(),this.fillPatternX()),e.rotate(i.getAngle(this.fillPatternRotation())),e.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),e.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const r=e.getMatrix();t.setTransform({a:r[0],b:r[1],c:r[2],d:r[3],e:r[4],f:r[5]})}return t}}_getLinearGradient(){return this._getCache("linearGradient",this.__getLinearGradient)}__getLinearGradient(){var t=this.fillLinearGradientColorStops();if(t){for(var e=J(),i=this.fillLinearGradientStartPoint(),r=this.fillLinearGradientEndPoint(),a=e.createLinearGradient(i.x,i.y,r.x,r.y),n=0;nthis.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!(!this.stroke()&&!this.strokeLinearGradientColorStops()))}hasHitStroke(){const t=this.hitStrokeWidth();return"auto"===t?this.hasStroke():this.strokeEnabled()&&!!t}intersects(t){var e=this.getStage().bufferHitCanvas;return e.getContext().clear(),this.drawHit(e,null,!0),e.context.getImageData(Math.round(t.x),Math.round(t.y),1,1).data[3]>0}destroy(){return L.prototype.destroy.call(this),delete Z[this.colorKey],delete this.colorKey,this}_useBufferCanvas(t){var e;if(!this.getStage())return!1;if(!(null===(e=this.attrs.perfectDrawEnabled)||void 0===e||e))return!1;const i=t||this.hasFill(),r=this.hasStroke(),a=1!==this.getAbsoluteOpacity();if(i&&r&&a)return!0;const n=this.hasShadow(),s=this.shadowForStrokeEnabled();return!!(i&&r&&n&&s)}setStrokeHitEnabled(t){c.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),t?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return 0!==this.hitStrokeWidth()}getSelfRect(){var t=this.size();return{x:this._centroid?-t.width/2:0,y:this._centroid?-t.height/2:0,width:t.width,height:t.height}}getClientRect(t={}){const e=t.skipTransform,i=t.relativeTo,r=this.getSelfRect(),a=!t.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,n=r.width+a,s=r.height+a,o=!t.skipShadow&&this.hasShadow(),h=o?this.shadowOffsetX():0,l=o?this.shadowOffsetY():0,d=n+Math.abs(h),c=s+Math.abs(l),g=o&&this.shadowBlur()||0,u=d+2*g,f=c+2*g;let p=0;Math.round(a/2)!==a/2&&(p=1);const v={width:u+p,height:f+p,x:-Math.round(a/2+g)+Math.min(h,0)+r.x,y:-Math.round(a/2+g)+Math.min(l,0)+r.y};return e?v:this._transformedRect(v,i)}drawScene(t,e){var i,r,a=this.getLayer(),n=t||a.getCanvas(),s=n.getContext(),o=this._getCanvasCache(),h=this.getSceneFunc(),l=this.hasShadow(),d=n.isCache,c=n.isCache,g=e===this;if(!this.isVisible()&&!d)return this;if(o){s.save();var u=this.getAbsoluteTransform(e).getMatrix();return s.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(s),s.restore(),this}if(!h)return this;if(s.save(),this._useBufferCanvas()&&!c){(r=(i=this.getStage().bufferCanvas).getContext()).clear(),r.save(),r._applyLineJoin(this);var f=this.getAbsoluteTransform(e).getMatrix();r.transform(f[0],f[1],f[2],f[3],f[4],f[5]),h.call(this,r,this),r.restore();var p=i.pixelRatio;l&&s._applyShadow(this),s._applyOpacity(this),s._applyGlobalCompositeOperation(this),s.drawImage(i._canvas,0,0,i.width/p,i.height/p)}else{if(s._applyLineJoin(this),!g){f=this.getAbsoluteTransform(e).getMatrix();s.transform(f[0],f[1],f[2],f[3],f[4],f[5]),s._applyOpacity(this),s._applyGlobalCompositeOperation(this)}l&&s._applyShadow(this),h.call(this,s,this)}return s.restore(),this}drawHit(t,e,i=!1){if(!this.shouldDrawHit(e,i))return this;var r=this.getLayer(),a=t||r.hitCanvas,n=a&&a.getContext(),s=this.hitFunc()||this.sceneFunc(),o=this._getCanvasCache(),h=o&&o.hit;if(this.colorKey||c.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),h){n.save();var l=this.getAbsoluteTransform(e).getMatrix();return n.transform(l[0],l[1],l[2],l[3],l[4],l[5]),this._drawCachedHitCanvas(n),n.restore(),this}if(!s)return this;n.save(),n._applyLineJoin(this);if(!(this===e)){var d=this.getAbsoluteTransform(e).getMatrix();n.transform(d[0],d[1],d[2],d[3],d[4],d[5])}return s.call(this,n,this),n.restore(),this}drawHitFromCache(t=0){var e,i,r,a,n,s=this._getCanvasCache(),o=this._getCachedSceneCanvas(),h=s.hit,l=h.getContext(),d=h.getWidth(),g=h.getHeight();l.clear(),l.drawImage(o._canvas,0,0,d,g);try{for(r=(i=(e=l.getImageData(0,0,d,g)).data).length,a=c._hexToRgb(this.colorKey),n=0;nt?(i[n]=a.r,i[n+1]=a.g,i[n+2]=a.b,i[n+3]=255):i[n+3]=0;l.putImageData(e,0,0)}catch(t){c.error("Unable to draw hit graph from cached scene canvas. "+t.message)}return this}hasPointerCapture(t){return z(t,this)}setPointerCapture(t){W(t,this)}releaseCapture(t){H(t)}}$.prototype._fillFunc=function(t){t.fill()},$.prototype._strokeFunc=function(t){t.stroke()},$.prototype._fillFuncHit=function(t){t.fill()},$.prototype._strokeFuncHit=function(t){t.stroke()},$.prototype._centroid=!1,$.prototype.nodeType="Shape",r($),$.prototype.eventListeners={},$.prototype.on.call($.prototype,"shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",(function(){this._clearCache("hasShadow")})),$.prototype.on.call($.prototype,"shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",(function(){this._clearCache("shadowRGBA")})),$.prototype.on.call($.prototype,"fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetX.konva fillPatternOffsetY.konva fillPatternRotation.konva",(function(){this._clearCache("patternImage")})),$.prototype.on.call($.prototype,"fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",(function(){this._clearCache("linearGradient")})),$.prototype.on.call($.prototype,"fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",(function(){this._clearCache("radialGradient")})),x.addGetterSetter($,"stroke",void 0,_()),x.addGetterSetter($,"strokeWidth",2,f()),x.addGetterSetter($,"fillAfterStrokeEnabled",!1),x.addGetterSetter($,"hitStrokeWidth","auto",v()),x.addGetterSetter($,"strokeHitEnabled",!0,y()),x.addGetterSetter($,"perfectDrawEnabled",!0,y()),x.addGetterSetter($,"shadowForStrokeEnabled",!0,y()),x.addGetterSetter($,"lineJoin"),x.addGetterSetter($,"lineCap"),x.addGetterSetter($,"sceneFunc"),x.addGetterSetter($,"hitFunc"),x.addGetterSetter($,"dash"),x.addGetterSetter($,"dashOffset",0,f()),x.addGetterSetter($,"shadowColor",void 0,m()),x.addGetterSetter($,"shadowBlur",0,f()),x.addGetterSetter($,"shadowOpacity",1,f()),x.addComponentsGetterSetter($,"shadowOffset",["x","y"]),x.addGetterSetter($,"shadowOffsetX",0,f()),x.addGetterSetter($,"shadowOffsetY",0,f()),x.addGetterSetter($,"fillPatternImage"),x.addGetterSetter($,"fill",void 0,_()),x.addGetterSetter($,"fillPatternX",0,f()),x.addGetterSetter($,"fillPatternY",0,f()),x.addGetterSetter($,"fillLinearGradientColorStops"),x.addGetterSetter($,"strokeLinearGradientColorStops"),x.addGetterSetter($,"fillRadialGradientStartRadius",0),x.addGetterSetter($,"fillRadialGradientEndRadius",0),x.addGetterSetter($,"fillRadialGradientColorStops"),x.addGetterSetter($,"fillPatternRepeat","repeat"),x.addGetterSetter($,"fillEnabled",!0),x.addGetterSetter($,"strokeEnabled",!0),x.addGetterSetter($,"shadowEnabled",!0),x.addGetterSetter($,"dashEnabled",!0),x.addGetterSetter($,"strokeScaleEnabled",!0),x.addGetterSetter($,"fillPriority","color"),x.addComponentsGetterSetter($,"fillPatternOffset",["x","y"]),x.addGetterSetter($,"fillPatternOffsetX",0,f()),x.addGetterSetter($,"fillPatternOffsetY",0,f()),x.addComponentsGetterSetter($,"fillPatternScale",["x","y"]),x.addGetterSetter($,"fillPatternScaleX",1,f()),x.addGetterSetter($,"fillPatternScaleY",1,f()),x.addComponentsGetterSetter($,"fillLinearGradientStartPoint",["x","y"]),x.addComponentsGetterSetter($,"strokeLinearGradientStartPoint",["x","y"]),x.addGetterSetter($,"fillLinearGradientStartPointX",0),x.addGetterSetter($,"strokeLinearGradientStartPointX",0),x.addGetterSetter($,"fillLinearGradientStartPointY",0),x.addGetterSetter($,"strokeLinearGradientStartPointY",0),x.addComponentsGetterSetter($,"fillLinearGradientEndPoint",["x","y"]),x.addComponentsGetterSetter($,"strokeLinearGradientEndPoint",["x","y"]),x.addGetterSetter($,"fillLinearGradientEndPointX",0),x.addGetterSetter($,"strokeLinearGradientEndPointX",0),x.addGetterSetter($,"fillLinearGradientEndPointY",0),x.addGetterSetter($,"strokeLinearGradientEndPointY",0),x.addComponentsGetterSetter($,"fillRadialGradientStartPoint",["x","y"]),x.addGetterSetter($,"fillRadialGradientStartPointX",0),x.addGetterSetter($,"fillRadialGradientStartPointY",0),x.addComponentsGetterSetter($,"fillRadialGradientEndPoint",["x","y"]),x.addGetterSetter($,"fillRadialGradientEndPointX",0),x.addGetterSetter($,"fillRadialGradientEndPointY",0),x.addGetterSetter($,"fillPatternRotation",0),x.backCompat($,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});var tt=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],et=tt.length;class it extends O{constructor(t){super(t),this.canvas=new A,this.hitCanvas=new M({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(t){return this.getContext().clear(t),this.getHitCanvas().getContext().clear(t),this}setZIndex(t){super.setZIndex(t);var e=this.getStage();return e&&e.content&&(e.content.removeChild(this.getNativeCanvasElement()),t{this.draw(),this._waitingForDraw=!1})),this}getIntersection(t){if(!this.isListening()||!this.isVisible())return null;for(var e=1,i=!1;;){for(let r=0;r0?{antialiased:!0}:{}}drawScene(t,e){var i=this.getLayer(),r=t||i&&i.getCanvas();return this._fire("beforeDraw",{node:this}),this.clearBeforeDraw()&&r.getContext().clear(),O.prototype.drawScene.call(this,r,e),this._fire("draw",{node:this}),this}drawHit(t,e){var i=this.getLayer(),r=t||i&&i.hitCanvas;return i&&i.clearBeforeDraw()&&i.getHitCanvas().getContext().clear(),O.prototype.drawHit.call(this,r,e),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){c.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return c.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(this.parent&&this.parent.content){var t=this.parent;!!this.hitCanvas._canvas.parentNode?t.content.removeChild(this.hitCanvas._canvas):t.content.appendChild(this.hitCanvas._canvas)}}}it.prototype.nodeType="Layer",r(it),x.addGetterSetter(it,"imageSmoothingEnabled",!0),x.addGetterSetter(it,"clearBeforeDraw",!0),x.addGetterSetter(it,"hitGraphEnabled",!0,y());class rt extends it{constructor(t){super(t),this.listening(!1),c.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}rt.prototype.nodeType="FastLayer",r(rt);class at extends O{_validateAdd(t){var e=t.getType();"Group"!==e&&"Shape"!==e&&c.throw("You may only add groups and shapes to groups.")}}at.prototype.nodeType="Group",r(at);var nt=e.performance&&e.performance.now?function(){return e.performance.now()}:function(){return(new Date).getTime()};class st{constructor(t,e){this.id=st.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:nt(),frameRate:0},this.func=t,this.setLayers(e)}setLayers(t){var e=[];return e=t?t.length>0?t:[t]:[],this.layers=e,this}getLayers(){return this.layers}addLayer(t){var e,i=this.layers,r=i.length;for(e=0;ethis.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():t<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=t,this.update())}getTime(){return this._time}setPosition(t){this.prevPos=this._pos,this.propFunc(t),this._pos=t}getPosition(t){return void 0===t&&(t=this._time),this.func(t,this.begin,this._change,this.duration)}play(){this.state=2,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=3,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(t){this.pause(),this._time=t,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){var t=this.getTimer()-this._startTime;2===this.state?this.setTime(t):3===this.state&&this.setTime(this.duration-t)}pause(){this.state=1,this.fire("onPause")}getTimer(){return(new Date).getTime()}}class ct{constructor(t){var e,r,a=this,n=t.node,s=n._id,o=t.easing||gt.Linear,h=!!t.yoyo;e=void 0===t.duration?.3:0===t.duration?.001:t.duration,this.node=n,this._id=ht++;var l=n.getLayer()||(n instanceof i.Stage?n.getLayers():null);for(r in l||c.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new st((function(){a.tween.onEnterFrame()}),l),this.tween=new dt(r,(function(t){a._tweenFunc(t)}),o,0,1,1e3*e,h),this._addListeners(),ct.attrs[s]||(ct.attrs[s]={}),ct.attrs[s][this._id]||(ct.attrs[s][this._id]={}),ct.tweens[s]||(ct.tweens[s]={}),t)void 0===ot[r]&&this._addAttr(r,t[r]);this.reset(),this.onFinish=t.onFinish,this.onReset=t.onReset,this.onUpdate=t.onUpdate}_addAttr(t,e){var i,r,a,n,s,o,h,l,d=this.node,g=d._id;if((a=ct.tweens[g][t])&&delete ct.attrs[g][a][t],i=d.getAttr(t),c._isArray(e))if(r=[],s=Math.max(e.length,i.length),"points"===t&&e.length!==i.length&&(e.length>i.length?(h=i,i=c._prepareArrayForTween(i,e,d.closed())):(o=e,e=c._prepareArrayForTween(e,i,d.closed()))),0===t.indexOf("fill"))for(n=0;n{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{var t=this.node,e=ct.attrs[t._id][this._id];e.points&&e.points.trueEnd&&t.setAttr("points",e.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{var t=this.node,e=ct.attrs[t._id][this._id];e.points&&e.points.trueStart&&t.points(e.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(t){return this.tween.seek(1e3*t),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){var t,e=this.node._id,i=this._id,r=ct.tweens[e];for(t in this.pause(),r)delete ct.tweens[e][t];delete ct.attrs[e][i]}}ct.attrs={},ct.tweens={},L.prototype.to=function(t){var e=t.onFinish;t.node=this,t.onFinish=function(){this.destroy(),e&&e()},new ct(t).play()};const gt={BackEaseIn(t,e,i,r){var a=1.70158;return i*(t/=r)*t*((a+1)*t-a)+e},BackEaseOut(t,e,i,r){var a=1.70158;return i*((t=t/r-1)*t*((a+1)*t+a)+1)+e},BackEaseInOut(t,e,i,r){var a=1.70158;return(t/=r/2)<1?i/2*(t*t*((1+(a*=1.525))*t-a))+e:i/2*((t-=2)*t*((1+(a*=1.525))*t+a)+2)+e},ElasticEaseIn(t,e,i,r,a,n){var s=0;return 0===t?e:1==(t/=r)?e+i:(n||(n=.3*r),!a||a(t/=r)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e,BounceEaseIn:(t,e,i,r)=>i-gt.BounceEaseOut(r-t,0,i,r)+e,BounceEaseInOut:(t,e,i,r)=>ti*(t/=r)*t+e,EaseOut:(t,e,i,r)=>-i*(t/=r)*(t-2)+e,EaseInOut:(t,e,i,r)=>(t/=r/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e,StrongEaseIn:(t,e,i,r)=>i*(t/=r)*t*t*t*t+e,StrongEaseOut:(t,e,i,r)=>i*((t=t/r-1)*t*t*t*t+1)+e,StrongEaseInOut:(t,e,i,r)=>(t/=r/2)<1?i/2*t*t*t*t*t+e:i/2*((t-=2)*t*t*t*t+2)+e,Linear:(t,e,i,r)=>i*t/r+e},ut=c._assign(i,{Util:c,Transform:a,Node:L,Container:O,Stage:K,stages:V,Layer:it,FastLayer:rt,Group:at,DD:G,Shape:$,shapes:Z,Animation:st,Tween:ct,Easings:gt,Context:w,Canvas:T});class ft extends ${_sceneFunc(t){var e=i.getAngle(this.angle()),r=this.clockwise();t.beginPath(),t.arc(0,0,this.outerRadius(),0,e,r),t.arc(0,0,this.innerRadius(),e,0,!r),t.closePath(),t.fillStrokeShape(this)}getWidth(){return 2*this.outerRadius()}getHeight(){return 2*this.outerRadius()}setWidth(t){this.outerRadius(t/2)}setHeight(t){this.outerRadius(t/2)}}function pt(t,e,i,r,a,n,s){var o=Math.sqrt(Math.pow(i-t,2)+Math.pow(r-e,2)),h=Math.sqrt(Math.pow(a-i,2)+Math.pow(n-r,2)),l=s*o/(o+h),d=s*h/(o+h);return[i-l*(a-t),r-l*(n-e),i+d*(a-t),r+d*(n-e)]}function vt(t,e){var i,r,a=t.length,n=[];for(i=2;i4){for(i=(e=this.getTensionPoints()).length,r=o?0:4,o||t.quadraticCurveTo(e[0],e[1],e[2],e[3]);rl?h:l,p=h>l?1:h/l,v=h>l?l/h:1;t.translate(s,o),t.rotate(g),t.scale(p,v),t.arc(0,0,f,d,d+c,1-u),t.scale(1/p,1/v),t.rotate(-g),t.translate(-s,-o);break;case"z":i=!0,t.closePath()}}i||this.hasFill()?t.fillStrokeShape(this):t.strokeShape(this)}getSelfRect(){var t=[];this.dataArray.forEach((function(e){if("A"===e.command){var i=e.points[4],r=e.points[5],a=e.points[4]+r,n=Math.PI/180;if(Math.abs(i-a)a;r-=n){const i=_t.getPointOnEllipticalArc(e.points[0],e.points[1],e.points[2],e.points[3],r,0);t.push(i.x,i.y)}else for(let r=i+n;rthis.dataArray[i].pathLength;)t-=this.dataArray[i].pathLength,++i;if(i===r)return{x:(e=this.dataArray[i-1].points.slice(-2))[0],y:e[1]};if(t<.01)return{x:(e=this.dataArray[i].points.slice(0,2))[0],y:e[1]};var a=this.dataArray[i],n=a.points;switch(a.command){case"L":return _t.getPointOnLine(t,a.start.x,a.start.y,n[0],n[1]);case"C":return _t.getPointOnCubicBezier(t/a.pathLength,a.start.x,a.start.y,n[0],n[1],n[2],n[3],n[4],n[5]);case"Q":return _t.getPointOnQuadraticBezier(t/a.pathLength,a.start.x,a.start.y,n[0],n[1],n[2],n[3]);case"A":var s=n[0],o=n[1],h=n[2],l=n[3],d=n[4],c=n[5],g=n[6];return d+=c*t/a.pathLength,_t.getPointOnEllipticalArc(s,o,h,l,d,g)}return null}static getLineLength(t,e,i,r){return Math.sqrt((i-t)*(i-t)+(r-e)*(r-e))}static getPointOnLine(t,e,i,r,a,n,s){void 0===n&&(n=e),void 0===s&&(s=i);var o=(a-i)/(r-e+1e-8),h=Math.sqrt(t*t/(1+o*o));r0&&!isNaN(u[0]);){var m,_,y,x,b,S,w,C,k,P,T=null,A=[],M=h,G=l;switch(g){case"l":h+=u.shift(),l+=u.shift(),T="L",A.push(h,l);break;case"L":h=u.shift(),l=u.shift(),A.push(h,l);break;case"m":var E=u.shift(),R=u.shift();if(h+=E,l+=R,T="M",s.length>2&&"z"===s[s.length-1].command)for(var L=s.length-2;L>=0;L--)if("M"===s[L].command){h=s[L].points[0]+E,l=s[L].points[1]+R;break}A.push(h,l),g="l";break;case"M":h=u.shift(),l=u.shift(),T="M",A.push(h,l),g="L";break;case"h":h+=u.shift(),T="L",A.push(h,l);break;case"H":h=u.shift(),T="L",A.push(h,l);break;case"v":l+=u.shift(),T="L",A.push(h,l);break;case"V":l=u.shift(),T="L",A.push(h,l);break;case"C":A.push(u.shift(),u.shift(),u.shift(),u.shift()),h=u.shift(),l=u.shift(),A.push(h,l);break;case"c":A.push(h+u.shift(),l+u.shift(),h+u.shift(),l+u.shift()),h+=u.shift(),l+=u.shift(),T="C",A.push(h,l);break;case"S":_=h,y=l,"C"===(m=s[s.length-1]).command&&(_=h+(h-m.points[2]),y=l+(l-m.points[3])),A.push(_,y,u.shift(),u.shift()),h=u.shift(),l=u.shift(),T="C",A.push(h,l);break;case"s":_=h,y=l,"C"===(m=s[s.length-1]).command&&(_=h+(h-m.points[2]),y=l+(l-m.points[3])),A.push(_,y,h+u.shift(),l+u.shift()),h+=u.shift(),l+=u.shift(),T="C",A.push(h,l);break;case"Q":A.push(u.shift(),u.shift()),h=u.shift(),l=u.shift(),A.push(h,l);break;case"q":A.push(h+u.shift(),l+u.shift()),h+=u.shift(),l+=u.shift(),T="Q",A.push(h,l);break;case"T":_=h,y=l,"Q"===(m=s[s.length-1]).command&&(_=h+(h-m.points[0]),y=l+(l-m.points[1])),h=u.shift(),l=u.shift(),T="Q",A.push(_,y,h,l);break;case"t":_=h,y=l,"Q"===(m=s[s.length-1]).command&&(_=h+(h-m.points[0]),y=l+(l-m.points[1])),h+=u.shift(),l+=u.shift(),T="Q",A.push(_,y,h,l);break;case"A":x=u.shift(),b=u.shift(),S=u.shift(),w=u.shift(),C=u.shift(),k=h,P=l,h=u.shift(),l=u.shift(),T="A",A=this.convertEndpointToCenterParameterization(k,P,h,l,w,C,x,b,S);break;case"a":x=u.shift(),b=u.shift(),S=u.shift(),w=u.shift(),C=u.shift(),k=h,P=l,h+=u.shift(),l+=u.shift(),T="A",A=this.convertEndpointToCenterParameterization(k,P,h,l,w,C,x,b,S)}s.push({command:T||g,points:A,start:{x:M,y:G},pathLength:this.calcLength(M,G,T||g,A)})}"z"!==g&&"Z"!==g||s.push({command:"z",points:[],start:void 0,pathLength:0})}return s}static calcLength(t,e,i,r){var a,n,s,o,h=_t;switch(i){case"L":return h.getLineLength(t,e,r[0],r[1]);case"C":for(a=0,n=h.getPointOnCubicBezier(0,t,e,r[0],r[1],r[2],r[3],r[4],r[5]),o=.01;o<=1;o+=.01)s=h.getPointOnCubicBezier(o,t,e,r[0],r[1],r[2],r[3],r[4],r[5]),a+=h.getLineLength(n.x,n.y,s.x,s.y),n=s;return a;case"Q":for(a=0,n=h.getPointOnQuadraticBezier(0,t,e,r[0],r[1],r[2],r[3]),o=.01;o<=1;o+=.01)s=h.getPointOnQuadraticBezier(o,t,e,r[0],r[1],r[2],r[3]),a+=h.getLineLength(n.x,n.y,s.x,s.y),n=s;return a;case"A":a=0;var l=r[4],d=r[5],c=r[4]+d,g=Math.PI/180;if(Math.abs(l-c)c;o-=g)s=h.getPointOnEllipticalArc(r[0],r[1],r[2],r[3],o,0),a+=h.getLineLength(n.x,n.y,s.x,s.y),n=s;else for(o=l+g;o1&&(s*=Math.sqrt(g),o*=Math.sqrt(g));var u=Math.sqrt((s*s*(o*o)-s*s*(c*c)-o*o*(d*d))/(s*s*(c*c)+o*o*(d*d)));a===n&&(u*=-1),isNaN(u)&&(u=0);var f=u*s*c/o,p=u*-o*d/s,v=(t+i)/2+Math.cos(l)*f-Math.sin(l)*p,m=(e+r)/2+Math.sin(l)*f+Math.cos(l)*p,_=function(t){return Math.sqrt(t[0]*t[0]+t[1]*t[1])},y=function(t,e){return(t[0]*e[0]+t[1]*e[1])/(_(t)*_(e))},x=function(t,e){return(t[0]*e[1]=1&&(C=0),0===n&&C>0&&(C-=2*Math.PI),1===n&&C<0&&(C+=2*Math.PI),[v,m,s,o,b,C,l,n]}}_t.prototype.className="Path",_t.prototype._attrsAffectingSize=["data"],r(_t),x.addGetterSetter(_t,"data");class yt extends mt{_sceneFunc(t){super._sceneFunc(t);var e=2*Math.PI,i=this.points(),r=i,a=0!==this.tension()&&i.length>4;a&&(r=this.getTensionPoints());var n,s,o=this.pointerLength(),h=i.length;if(a){const t=[r[r.length-4],r[r.length-3],r[r.length-2],r[r.length-1],i[h-2],i[h-1]],e=_t.calcLength(r[r.length-4],r[r.length-3],"C",t),a=_t.getPointOnQuadraticBezier(Math.min(1,1-o/e),t[0],t[1],t[2],t[3],t[4],t[5]);n=i[h-2]-a.x,s=i[h-1]-a.y}else n=i[h-2]-i[h-4],s=i[h-1]-i[h-3];var l=(Math.atan2(s,n)+e)%e,d=this.pointerWidth();this.pointerAtEnding()&&(t.save(),t.beginPath(),t.translate(i[h-2],i[h-1]),t.rotate(l),t.moveTo(0,0),t.lineTo(-o,d/2),t.lineTo(-o,-d/2),t.closePath(),t.restore()),this.pointerAtBeginning()&&(t.save(),t.translate(i[0],i[1]),a?(n=(r[0]+r[2])/2-i[0],s=(r[1]+r[3])/2-i[1]):(n=i[2]-i[0],s=i[3]-i[1]),t.rotate((Math.atan2(-s,-n)+e)%e),t.moveTo(0,0),t.lineTo(-o,d/2),t.lineTo(-o,-d/2),t.closePath(),t.restore());var c=this.dashEnabled();c&&(this.attrs.dashEnabled=!1,t.setLineDash([])),t.fillStrokeShape(this),c&&(this.attrs.dashEnabled=!0)}getSelfRect(){const t=super.getSelfRect(),e=this.pointerWidth()/2;return{x:t.x-e,y:t.y-e,width:t.width+2*e,height:t.height+2*e}}}yt.prototype.className="Arrow",r(yt),x.addGetterSetter(yt,"pointerLength",10,f()),x.addGetterSetter(yt,"pointerWidth",10,f()),x.addGetterSetter(yt,"pointerAtBeginning",!1),x.addGetterSetter(yt,"pointerAtEnding",!0);class xt extends ${_sceneFunc(t){t.beginPath(),t.arc(0,0,this.attrs.radius||0,0,2*Math.PI,!1),t.closePath(),t.fillStrokeShape(this)}getWidth(){return 2*this.radius()}getHeight(){return 2*this.radius()}setWidth(t){this.radius()!==t/2&&this.radius(t/2)}setHeight(t){this.radius()!==t/2&&this.radius(t/2)}}xt.prototype._centroid=!0,xt.prototype.className="Circle",xt.prototype._attrsAffectingSize=["radius"],r(xt),x.addGetterSetter(xt,"radius",0,f());class bt extends ${_sceneFunc(t){var e=this.radiusX(),i=this.radiusY();t.beginPath(),t.save(),e!==i&&t.scale(1,i/e),t.arc(0,0,e,0,2*Math.PI,!1),t.restore(),t.closePath(),t.fillStrokeShape(this)}getWidth(){return 2*this.radiusX()}getHeight(){return 2*this.radiusY()}setWidth(t){this.radiusX(t/2)}setHeight(t){this.radiusY(t/2)}}bt.prototype.className="Ellipse",bt.prototype._centroid=!0,bt.prototype._attrsAffectingSize=["radiusX","radiusY"],r(bt),x.addComponentsGetterSetter(bt,"radius",["x","y"]),x.addGetterSetter(bt,"radiusX",0,f()),x.addGetterSetter(bt,"radiusY",0,f());class St extends ${constructor(t){super(t),this.on("imageChange.konva",()=>{this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const t=this.image();t&&t.addEventListener&&t.addEventListener("load",()=>{this._requestDraw()})}_useBufferCanvas(){return super._useBufferCanvas(!0)}_sceneFunc(t){const e=this.getWidth(),i=this.getHeight(),r=this.attrs.image;let a;if(r){const t=this.attrs.cropWidth,n=this.attrs.cropHeight;a=t&&n?[r,this.cropX(),this.cropY(),t,n,0,0,e,i]:[r,0,0,e,i]}(this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,e,i),t.closePath(),t.fillStrokeShape(this)),r&&t.drawImage.apply(t,a)}_hitFunc(t){var e=this.width(),i=this.height();t.beginPath(),t.rect(0,0,e,i),t.closePath(),t.fillStrokeShape(this)}getWidth(){var t,e;return null!==(t=this.attrs.width)&&void 0!==t?t:null===(e=this.image())||void 0===e?void 0:e.width}getHeight(){var t,e;return null!==(t=this.attrs.height)&&void 0!==t?t:null===(e=this.image())||void 0===e?void 0:e.height}static fromURL(t,e){var i=c.createImageElement();i.onload=function(){var t=new St({image:i});e(t)},i.crossOrigin="Anonymous",i.src=t}}St.prototype.className="Image",r(St),x.addGetterSetter(St,"image"),x.addComponentsGetterSetter(St,"crop",["x","y","width","height"]),x.addGetterSetter(St,"cropX",0,f()),x.addGetterSetter(St,"cropY",0,f()),x.addGetterSetter(St,"cropWidth",0,f()),x.addGetterSetter(St,"cropHeight",0,f());var wt=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height"],Ct=wt.length;class kt extends at{constructor(t){super(t),this.on("add.konva",(function(t){this._addListeners(t.child),this._sync()}))}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(t){var e,i=this,r=function(){i._sync()};for(e=0;e{e=Math.min(e,t.x),i=Math.max(i,t.x),r=Math.min(r,t.y),a=Math.max(a,t.y)}),{x:e,y:r,width:i-e,height:a-r}}getWidth(){return 2*this.radius()}getHeight(){return 2*this.radius()}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}At.prototype.className="RegularPolygon",At.prototype._centroid=!0,At.prototype._attrsAffectingSize=["radius"],r(At),x.addGetterSetter(At,"radius",0,f()),x.addGetterSetter(At,"sides",0,f());var Mt=2*Math.PI;class Gt extends ${_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,Mt,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),Mt,0,!0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return 2*this.outerRadius()}getHeight(){return 2*this.outerRadius()}setWidth(t){this.outerRadius(t/2)}setHeight(t){this.outerRadius(t/2)}}Gt.prototype.className="Ring",Gt.prototype._centroid=!0,Gt.prototype._attrsAffectingSize=["innerRadius","outerRadius"],r(Gt),x.addGetterSetter(Gt,"innerRadius",0,f()),x.addGetterSetter(Gt,"outerRadius",0,f());class Et extends ${constructor(t){super(t),this._updated=!0,this.anim=new st(()=>{var t=this._updated;return this._updated=!1,t}),this.on("animationChange.konva",(function(){this.frameIndex(0)})),this.on("frameIndexChange.konva",(function(){this._updated=!0})),this.on("frameRateChange.konva",(function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())}))}_sceneFunc(t){var e=this.animation(),i=this.frameIndex(),r=4*i,a=this.animations()[e],n=this.frameOffsets(),s=a[r+0],o=a[r+1],h=a[r+2],l=a[r+3],d=this.image();if((this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,h,l),t.closePath(),t.fillStrokeShape(this)),d)if(n){var c=n[e],g=2*i;t.drawImage(d,s,o,h,l,c[g+0],c[g+1],h,l)}else t.drawImage(d,s,o,h,l,0,0,h,l)}_hitFunc(t){var e=this.animation(),i=this.frameIndex(),r=4*i,a=this.animations()[e],n=this.frameOffsets(),s=a[r+2],o=a[r+3];if(t.beginPath(),n){var h=n[e],l=2*i;t.rect(h[l+0],h[l+1],s,o)}else t.rect(0,0,s,o);t.closePath(),t.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){var t=this;this.interval=setInterval((function(){t._updateIndex()}),1e3/this.frameRate())}start(){if(!this.isRunning()){var t=this.getLayer();this.anim.setLayers(t),this._setInterval(),this.anim.start()}}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){var t=this.frameIndex(),e=this.animation();t1&&(v+=s)}}}_hitFunc(t){var e=this.getWidth(),i=this.getHeight();t.beginPath(),t.rect(0,0,e,i),t.closePath(),t.fillStrokeShape(this)}setText(t){var e=c._isString(t)?t:null==t?"":t+"";return this._setAttr("text",e),this}getWidth(){return"auto"===this.attrs.width||void 0===this.attrs.width?this.getTextWidth()+2*this.padding():this.attrs.width}getHeight(){return"auto"===this.attrs.height||void 0===this.attrs.height?this.fontSize()*this.textArr.length*this.lineHeight()+2*this.padding():this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return c.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(t){var e,i=Ft(),r=this.fontSize();return i.save(),i.font=this._getContextFont(),e=i.measureText(t),i.restore(),{width:e.width,height:r}}_getContextFont(){return this.fontStyle()+" "+this.fontVariant()+" "+this.fontSize()+"px "+this.fontFamily().split(",").map(t=>{const e=(t=t.trim()).indexOf(" ")>=0,i=t.indexOf('"')>=0||t.indexOf("'")>=0;return e&&!i&&(t=`"${t}"`),t}).join(", ")}_addTextLine(t){"justify"===this.align()&&(t=t.trim());var e=this._getTextWidth(t);return this.textArr.push({text:t,width:e})}_getTextWidth(t){var e=this.letterSpacing(),i=t.length;return Ft().measureText(t).width+(i?e*(i-1):0)}_setTextData(){var t=this.text().split("\n"),e=+this.fontSize(),i=0,r=this.lineHeight()*e,a=this.attrs.width,n=this.attrs.height,s="auto"!==a&&void 0!==a,o="auto"!==n&&void 0!==n,h=this.padding(),l=a-2*h,d=n-2*h,c=0,g=this.wrap(),u="none"!==g,f="char"!==g&&u,p=this.ellipsis();this.textArr=[],Ft().font=this._getContextFont();for(var v=p?this._getTextWidth("…"):0,m=0,_=t.length;m<_;++m){var y=t[m],x=this._getTextWidth(y);if(s&&x>l)for(;y.length>0;){for(var b=0,S=y.length,w="",C=0;b>>1,P=y.slice(0,k+1),T=this._getTextWidth(P)+v;T<=l?(b=k+1,w=P,C=T):S=k}if(!w)break;if(f){var A,M=y[w.length];(A=(" "===M||"-"===M)&&C<=l?w.length:Math.max(w.lastIndexOf(" "),w.lastIndexOf("-"))+1)>0&&(b=A,w=w.slice(0,b),C=this._getTextWidth(w))}if(w=w.trimRight(),this._addTextLine(w),i=Math.max(i,C),c+=r,!u||o&&c+r>d){var G=this.textArr[this.textArr.length-1];if(G)if(p)this._getTextWidth(G.text+"…")0&&(x=this._getTextWidth(y))<=l){this._addTextLine(y),c+=r,i=Math.max(i,x);break}}else this._addTextLine(y),c+=r,i=Math.max(i,x);if(o&&c+r>d)break}this.textHeight=e,this.textWidth=i}getStrokeScaleEnabled(){return!0}}Nt.prototype._fillFunc=function(t){t.fillText(this._partialText,this._partialTextX,this._partialTextY)},Nt.prototype._strokeFunc=function(t){t.strokeText(this._partialText,this._partialTextX,this._partialTextY)},Nt.prototype.className="Text",Nt.prototype._attrsAffectingSize=["text","fontSize","padding","wrap","lineHeight","letterSpacing"],r(Nt),x.overWriteSetter(Nt,"width",v()),x.overWriteSetter(Nt,"height",v()),x.addGetterSetter(Nt,"fontFamily","Arial"),x.addGetterSetter(Nt,"fontSize",12,f()),x.addGetterSetter(Nt,"fontStyle","normal"),x.addGetterSetter(Nt,"fontVariant","normal"),x.addGetterSetter(Nt,"padding",0,f()),x.addGetterSetter(Nt,"align","left"),x.addGetterSetter(Nt,"verticalAlign","top"),x.addGetterSetter(Nt,"lineHeight",1,f()),x.addGetterSetter(Nt,"wrap","word"),x.addGetterSetter(Nt,"ellipsis",!1,y()),x.addGetterSetter(Nt,"letterSpacing",0,f()),x.addGetterSetter(Nt,"text","",m()),x.addGetterSetter(Nt,"textDecoration","");function Bt(t){t.fillText(this.partialText,0,0)}function zt(t){t.strokeText(this.partialText,0,0)}class Wt extends ${constructor(t){super(t),this.dummyCanvas=c.createCanvasElement(),this.dataArray=[],this.dataArray=_t.parsePathData(this.attrs.data),this.on("dataChange.konva",(function(){this.dataArray=_t.parsePathData(this.attrs.data),this._setTextData()})),this.on("textChange.konva alignChange.konva letterSpacingChange.konva kerningFuncChange.konva fontSizeChange.konva",this._setTextData),this._setTextData()}_sceneFunc(t){t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",this.textBaseline()),t.setAttr("textAlign","left"),t.save();var e=this.textDecoration(),i=this.fill(),r=this.fontSize(),a=this.glyphInfo;"underline"===e&&t.beginPath();for(var n=0;n=1){var i=e[0].p0;t.moveTo(i.x,i.y)}for(var r=0;r0&&(s+=t.dataArray[o].pathLength);var h=0;"center"===r&&(h=Math.max(0,s/2-n/2)),"right"===r&&(h=Math.max(0,s-n));for(var l,d,c,g=Lt(this.text()),u=this.text().split(" ").length-1,f=-1,p=0,v=function(){p=0;for(var e=t.dataArray,i=f+1;i0)return f=i,e[i];"M"===e[i].command&&(l={x:e[i].points[0],y:e[i].points[1]})}return{}},m=function(e){var a=t._getTextSize(e).width+i;" "===e&&"justify"===r&&(a+=(s-n)/u);var o=0,h=0;for(d=void 0;Math.abs(a-o)/a>.01&&h<20;){h++;for(var g=o;void 0===c;)(c=v())&&g+c.pathLengtha?d=_t.getPointOnLine(a,l.x,l.y,c.points[0],c.points[1],l.x,l.y):c=void 0;break;case"A":var m=c.points[4],_=c.points[5],y=c.points[4]+_;0===p?p=m+1e-8:a>o?p+=Math.PI/180*_/Math.abs(_):p-=Math.PI/360*_/Math.abs(_),(_<0&&p=0&&p>y)&&(p=y,f=!0),d=_t.getPointOnEllipticalArc(c.points[0],c.points[1],c.points[2],c.points[3],p,c.points[6]);break;case"C":0===p?p=a>c.pathLength?1e-8:a/c.pathLength:a>o?p+=(a-o)/c.pathLength/2:p=Math.max(p-(o-a)/c.pathLength/2,0),p>1&&(p=1,f=!0),d=_t.getPointOnCubicBezier(p,c.start.x,c.start.y,c.points[0],c.points[1],c.points[2],c.points[3],c.points[4],c.points[5]);break;case"Q":0===p?p=a/c.pathLength:a>o?p+=(a-o)/c.pathLength:p-=(o-a)/c.pathLength,p>1&&(p=1,f=!0),d=_t.getPointOnQuadraticBezier(p,c.start.x,c.start.y,c.points[0],c.points[1],c.points[2],c.points[3])}void 0!==d&&(o=_t.getLineLength(l.x,l.y,d.x,d.y)),f&&(f=!1,c=void 0)}},_=h/(t._getTextSize("C").width+i)-1,y=0;y<_&&(m("C"),void 0!==l&&void 0!==d);y++)l=d;for(var x=0;xt+".tr-konva").join(" "),Yt=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange"].map(t=>t+".tr-konva").join(" "),Xt={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135};const jt="ontouchstart"in i._global;var Ut=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function qt(t,e,i){const r=i.x+(t.x-i.x)*Math.cos(e)-(t.y-i.y)*Math.sin(e),a=i.y+(t.x-i.x)*Math.sin(e)+(t.y-i.y)*Math.cos(e);return Object.assign(Object.assign({},t),{rotation:t.rotation+e,x:r,y:a})}function Vt(t,e){return qt(t,e,function(t){return{x:t.x+t.width/2*Math.cos(t.rotation)+t.height/2*Math.sin(-t.rotation),y:t.y+t.height/2*Math.cos(t.rotation)+t.width/2*Math.sin(t.rotation)}}(t))}class Kt extends at{constructor(t){super(t),this._transforming=!1,this._createElements(),this._handleMouseMove=this._handleMouseMove.bind(this),this._handleMouseUp=this._handleMouseUp.bind(this),this.update=this.update.bind(this),this.on(Ht,this.update),this.getNode()&&this.update()}attachTo(t){return this.setNode(t),this}setNode(t){return c.warn("tr.setNode(shape), tr.node(shape) and tr.attachTo(shape) methods are deprecated. Please use tr.nodes(nodesArray) instead."),this.setNodes([t])}getNode(){return this._nodes&&this._nodes[0]}setNodes(t=[]){return this._nodes&&this._nodes.length&&this.detach(),this._nodes=t,1===t.length?this.rotation(t[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(t=>{const e=t._attrsAffectingSize.map(t=>t+"Change.tr-konva").join(" "),i=()=>{1===this.nodes().length&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),this._transforming||this.isDragging()||this.update()};t.on(e,i),t.on(Yt,i),t.on("absoluteTransformChange.tr-konva",i),t.on("xChange.tr-konva yChange.tr-konva",i),this._proxyDrag(t)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(t){let e;t.on("dragstart.tr-konva",i=>{e=t.getAbsolutePosition(),this.isDragging()||t===this.findOne(".back")||this.startDrag(i,!1)}),t.on("dragmove.tr-konva",i=>{if(!e)return;const r=t.getAbsolutePosition(),a=r.x-e.x,n=r.y-e.y;this.nodes().forEach(e=>{if(e===t)return;if(e.isDragging())return;const r=e.getAbsolutePosition();e.setAbsolutePosition({x:r.x+a,y:r.y+n}),e.startDrag(i)}),e=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(t=>{t.off(".tr-konva")}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache("nodesRect"),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache("nodesRect",this.__getNodeRect)}__getNodeShape(t,e=this.rotation(),r){var a=t.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),n=t.getAbsoluteScale(r),s=t.getAbsolutePosition(r),o=a.x*n.x-t.offsetX()*n.x,h=a.y*n.y-t.offsetY()*n.y;const l=(i.getAngle(t.getAbsoluteRotation())+2*Math.PI)%(2*Math.PI);return qt({x:s.x+o*Math.cos(l)+h*Math.sin(-l),y:s.y+h*Math.cos(l)+o*Math.sin(l),width:a.width*n.x,height:a.height*n.y,rotation:l},-i.getAngle(e),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-1e8,y:-1e8,width:0,height:0,rotation:0};const t=[];this.nodes().map(e=>{const i=e.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()});var r=[{x:i.x,y:i.y},{x:i.x+i.width,y:i.y},{x:i.x+i.width,y:i.y+i.height},{x:i.x,y:i.y+i.height}],a=e.getAbsoluteTransform();r.forEach((function(e){var i=a.point(e);t.push(i)}))});const e=new a;var r,n,s,o;e.rotate(-i.getAngle(this.rotation())),t.forEach((function(t){var i=e.point(t);void 0===r&&(r=s=i.x,n=o=i.y),r=Math.min(r,i.x),n=Math.min(n,i.y),s=Math.max(s,i.x),o=Math.max(o,i.y)})),e.invert();const h=e.point({x:r,y:n});return{x:h.x,y:h.y,width:s-r,height:o-n,rotation:i.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),Ut.forEach(function(t){this._createAnchor(t)}.bind(this)),this._createAnchor("rotater")}_createAnchor(t){var e=new Tt({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:jt?10:"auto"}),r=this;e.on("mousedown touchstart",(function(t){r._handleMouseDown(t)})),e.on("dragstart",t=>{e.stopDrag(),t.cancelBubble=!0}),e.on("dragend",t=>{t.cancelBubble=!0}),e.on("mouseenter",()=>{var r=i.getAngle(this.rotation()),a=function(t,e){if("rotater"===t)return"crosshair";e+=c.degToRad(Xt[t]||0);var i=(c.radToDeg(e)%360+360)%360;return c._inRange(i,337.5,360)||c._inRange(i,0,22.5)?"ns-resize":c._inRange(i,22.5,67.5)?"nesw-resize":c._inRange(i,67.5,112.5)?"ew-resize":c._inRange(i,112.5,157.5)?"nwse-resize":c._inRange(i,157.5,202.5)?"ns-resize":c._inRange(i,202.5,247.5)?"nesw-resize":c._inRange(i,247.5,292.5)?"ew-resize":c._inRange(i,292.5,337.5)?"nwse-resize":(c.error("Transformer has unknown angle for cursor detection: "+i),"pointer")}(t,r);e.getStage().content&&(e.getStage().content.style.cursor=a),this._cursorChange=!0}),e.on("mouseout",()=>{e.getStage().content&&(e.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(e)}_createBack(){var t=new $({name:"back",width:0,height:0,draggable:!0,sceneFunc(t){var e=this.getParent(),i=e.padding();t.beginPath(),t.rect(-i,-i,this.width()+2*i,this.height()+2*i),t.moveTo(this.width()/2,-i),e.rotateEnabled()&&t.lineTo(this.width()/2,-e.rotateAnchorOffset()*c._sign(this.height())-i),t.fillStrokeShape(this)},hitFunc:(t,e)=>{if(this.shouldOverdrawWholeArea()){var i=this.padding();t.beginPath(),t.rect(-i,-i,e.width()+2*i,e.height()+2*i),t.fillStrokeShape(e)}}});this.add(t),this._proxyDrag(t),t.on("dragstart",t=>{t.cancelBubble=!0}),t.on("dragmove",t=>{t.cancelBubble=!0}),t.on("dragend",t=>{t.cancelBubble=!0})}_handleMouseDown(t){this._movingAnchorName=t.target.name().split(" ")[0];var e=this._getNodeRect(),i=e.width,r=e.height,a=Math.sqrt(Math.pow(i,2)+Math.pow(r,2));this.sin=Math.abs(r/a),this.cos=Math.abs(i/a),"undefined"!=typeof window&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;var n=t.target.getAbsolutePosition(),s=t.target.getStage().getPointerPosition();this._anchorDragOffset={x:s.x-n.x,y:s.y-n.y},this._fire("transformstart",{evt:t,target:this.getNode()}),this._nodes.forEach(e=>{e._fire("transformstart",{evt:t,target:e})})}_handleMouseMove(t){var e,r,a,n=this.findOne("."+this._movingAnchorName),s=n.getStage();s.setPointersPositions(t);const o=s.getPointerPosition();var h={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const l=n.getAbsolutePosition();n.setAbsolutePosition(h);const d=n.getAbsolutePosition();if(l.x!==d.x||l.y!==d.y)if("rotater"!==this._movingAnchorName){var c=this.keepRatio()||t.shiftKey,g=this.centeredScaling()||t.altKey;if("top-left"===this._movingAnchorName){if(c){var u=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};a=Math.sqrt(Math.pow(u.x-n.x(),2)+Math.pow(u.y-n.y(),2));var f=this.findOne(".top-left").x()>u.x?-1:1,p=this.findOne(".top-left").y()>u.y?-1:1;e=a*this.cos*f,r=a*this.sin*p,this.findOne(".top-left").x(u.x-e),this.findOne(".top-left").y(u.y-r)}}else if("top-center"===this._movingAnchorName)this.findOne(".top-left").y(n.y());else if("top-right"===this._movingAnchorName){if(c){u=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};a=Math.sqrt(Math.pow(n.x()-u.x,2)+Math.pow(u.y-n.y(),2));f=this.findOne(".top-right").x()u.y?-1:1;e=a*this.cos*f,r=a*this.sin*p,this.findOne(".top-right").x(u.x+e),this.findOne(".top-right").y(u.y-r)}var v=n.position();this.findOne(".top-left").y(v.y),this.findOne(".bottom-right").x(v.x)}else if("middle-left"===this._movingAnchorName)this.findOne(".top-left").x(n.x());else if("middle-right"===this._movingAnchorName)this.findOne(".bottom-right").x(n.x());else if("bottom-left"===this._movingAnchorName){if(c){u=g?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};a=Math.sqrt(Math.pow(u.x-n.x(),2)+Math.pow(n.y()-u.y,2));f=u.x{e._fire("transformend",{evt:t,target:e})}),this._movingAnchorName=null}}_fitNodesInto(t,e){var r=this._getNodeRect();if(c._inRange(t.width,2*-this.padding()-1,1))return void this.update();if(c._inRange(t.height,2*-this.padding()-1,1))return void this.update();const n=this.flipEnabled();var s=new a;if(s.rotate(i.getAngle(this.rotation())),this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const e=s.point({x:2*-this.padding(),y:0});if(t.x+=e.x,t.y+=e.y,t.width+=2*this.padding(),this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=e.x,this._anchorDragOffset.y-=e.y,!n)return void this.update()}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const e=s.point({x:2*this.padding(),y:0});if(this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=e.x,this._anchorDragOffset.y-=e.y,t.width+=2*this.padding(),!n)return void this.update()}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const e=s.point({x:0,y:2*-this.padding()});if(t.x+=e.x,t.y+=e.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=e.x,this._anchorDragOffset.y-=e.y,t.height+=2*this.padding(),!n)return void this.update()}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const e=s.point({x:0,y:2*this.padding()});if(this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=e.x,this._anchorDragOffset.y-=e.y,t.height+=2*this.padding(),!n)return void this.update()}if(this.boundBoxFunc()){const e=this.boundBoxFunc()(r,t);e?t=e:c.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const o=new a;o.translate(r.x,r.y),o.rotate(r.rotation),o.scale(r.width/1e7,r.height/1e7);const h=new a;h.translate(t.x,t.y),h.rotate(t.rotation),h.scale(t.width/1e7,t.height/1e7);const l=h.multiply(o.invert());this._nodes.forEach(t=>{var i;const r=t.getParent().getAbsoluteTransform(),n=t.getTransform().copy();n.translate(t.offsetX(),t.offsetY());const s=new a;s.multiply(r.copy().invert()).multiply(l).multiply(r).multiply(n);const o=s.decompose();t.setAttrs(o),this._fire("transform",{evt:e,target:t}),t._fire("transform",{evt:e,target:t}),null===(i=t.getLayer())||void 0===i||i.batchDraw()}),this.rotation(c._getRotation(t.rotation)),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(t,e){this.findOne(t).setAttrs(e)}update(){var t,e=this._getNodeRect();this.rotation(c._getRotation(e.rotation));var i=e.width,r=e.height,a=this.enabledAnchors(),n=this.resizeEnabled(),s=this.padding(),o=this.anchorSize();this.find("._anchor").forEach(t=>{t.setAttrs({width:o,height:o,offsetX:o/2,offsetY:o/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:o/2+s,offsetY:o/2+s,visible:n&&a.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:i/2,y:0,offsetY:o/2+s,visible:n&&a.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:i,y:0,offsetX:o/2-s,offsetY:o/2+s,visible:n&&a.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:r/2,offsetX:o/2+s,visible:n&&a.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:i,y:r/2,offsetX:o/2-s,visible:n&&a.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:r,offsetX:o/2+s,offsetY:o/2-s,visible:n&&a.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:i/2,y:r,offsetY:o/2-s,visible:n&&a.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:i,y:r,offsetX:o/2-s,offsetY:o/2-s,visible:n&&a.indexOf("bottom-right")>=0}),this._batchChangeChild(".rotater",{x:i/2,y:-this.rotateAnchorOffset()*c._sign(r)-s,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:i,height:r,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),x:0,y:0}),null===(t=this.getLayer())||void 0===t||t.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();var t=this.findOne("."+this._movingAnchorName);t&&t.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),at.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}toObject(){return L.prototype.toObject.call(this)}}Kt.prototype.className="Transformer",r(Kt),x.addGetterSetter(Kt,"enabledAnchors",Ut,(function(t){return t instanceof Array||c.warn("enabledAnchors value should be an array"),t instanceof Array&&t.forEach((function(t){-1===Ut.indexOf(t)&&c.warn("Unknown anchor name: "+t+". Available names are: "+Ut.join(", "))})),t||[]})),x.addGetterSetter(Kt,"flipEnabled",!0,y()),x.addGetterSetter(Kt,"resizeEnabled",!0),x.addGetterSetter(Kt,"anchorSize",10,f()),x.addGetterSetter(Kt,"rotateEnabled",!0),x.addGetterSetter(Kt,"rotationSnaps",[]),x.addGetterSetter(Kt,"rotateAnchorOffset",50,f()),x.addGetterSetter(Kt,"rotationSnapTolerance",5,f()),x.addGetterSetter(Kt,"borderEnabled",!0),x.addGetterSetter(Kt,"anchorStroke","rgb(0, 161, 255)"),x.addGetterSetter(Kt,"anchorStrokeWidth",1,f()),x.addGetterSetter(Kt,"anchorFill","white"),x.addGetterSetter(Kt,"anchorCornerRadius",0,f()),x.addGetterSetter(Kt,"borderStroke","rgb(0, 161, 255)"),x.addGetterSetter(Kt,"borderStrokeWidth",1,f()),x.addGetterSetter(Kt,"borderDash"),x.addGetterSetter(Kt,"keepRatio",!0),x.addGetterSetter(Kt,"centeredScaling",!1),x.addGetterSetter(Kt,"ignoreStroke",!1),x.addGetterSetter(Kt,"padding",0,f()),x.addGetterSetter(Kt,"node"),x.addGetterSetter(Kt,"nodes"),x.addGetterSetter(Kt,"boundBoxFunc"),x.addGetterSetter(Kt,"shouldOverdrawWholeArea",!1),x.backCompat(Kt,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class Qt extends ${_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,i.getAngle(this.angle()),this.clockwise()),t.lineTo(0,0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return 2*this.radius()}getHeight(){return 2*this.radius()}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}function Jt(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}Qt.prototype.className="Wedge",Qt.prototype._centroid=!0,Qt.prototype._attrsAffectingSize=["radius"],r(Qt),x.addGetterSetter(Qt,"radius",0,f()),x.addGetterSetter(Qt,"angle",0,f()),x.addGetterSetter(Qt,"clockwise",!1),x.backCompat(Qt,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});var Zt=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],$t=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];x.addGetterSetter(L,"blurRadius",0,f(),x.afterSetFilter);x.addGetterSetter(L,"brightness",0,f(),x.afterSetFilter);x.addGetterSetter(L,"contrast",0,f(),x.afterSetFilter);function te(t,e,i,r,a){var n=i-e,s=a-r;return 0===n?r+s/2:0===s?r:s*((t-e)/n)+r}x.addGetterSetter(L,"embossStrength",.5,f(),x.afterSetFilter),x.addGetterSetter(L,"embossWhiteLevel",.5,f(),x.afterSetFilter),x.addGetterSetter(L,"embossDirection","top-left",null,x.afterSetFilter),x.addGetterSetter(L,"embossBlend",!1,null,x.afterSetFilter);x.addGetterSetter(L,"enhance",0,f(),x.afterSetFilter);x.addGetterSetter(L,"hue",0,f(),x.afterSetFilter),x.addGetterSetter(L,"saturation",0,f(),x.afterSetFilter),x.addGetterSetter(L,"luminance",0,f(),x.afterSetFilter);x.addGetterSetter(L,"hue",0,f(),x.afterSetFilter),x.addGetterSetter(L,"saturation",0,f(),x.afterSetFilter),x.addGetterSetter(L,"value",0,f(),x.afterSetFilter);function ee(t,e,i){var r=4*(i*t.width+e),a=[];return a.push(t.data[r++],t.data[r++],t.data[r++],t.data[r++]),a}function ie(t,e){return Math.sqrt(Math.pow(t[0]-e[0],2)+Math.pow(t[1]-e[1],2)+Math.pow(t[2]-e[2],2))}x.addGetterSetter(L,"kaleidoscopePower",2,f(),x.afterSetFilter),x.addGetterSetter(L,"kaleidoscopeAngle",0,f(),x.afterSetFilter);x.addGetterSetter(L,"threshold",0,f(),x.afterSetFilter);x.addGetterSetter(L,"noise",.2,f(),x.afterSetFilter);x.addGetterSetter(L,"pixelSize",8,f(),x.afterSetFilter);x.addGetterSetter(L,"levels",.5,f(),x.afterSetFilter);x.addGetterSetter(L,"red",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),x.addGetterSetter(L,"green",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),x.addGetterSetter(L,"blue",0,u,x.afterSetFilter);x.addGetterSetter(L,"red",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),x.addGetterSetter(L,"green",0,(function(t){return this._filterUpToDate=!1,t>255?255:t<0?0:Math.round(t)})),x.addGetterSetter(L,"blue",0,u,x.afterSetFilter),x.addGetterSetter(L,"alpha",1,(function(t){return this._filterUpToDate=!1,t>1?1:t<0?0:t}));x.addGetterSetter(L,"threshold",.5,f(),x.afterSetFilter);return ut.Util._assign(ut,{Arc:ft,Arrow:yt,Circle:xt,Ellipse:bt,Image:St,Label:kt,Tag:Pt,Line:mt,Path:_t,Rect:Tt,RegularPolygon:At,Ring:Gt,Sprite:Et,Star:Rt,Text:Nt,TextPath:Wt,Transformer:Kt,Wedge:Qt,Filters:{Blur:function(t){var e=Math.round(this.blurRadius());e>0&&function(t,e){var i,r,a,n,s,o,h,l,d,c,g,u,f,p,v,m,_,y,x,b,S,w,C,k,P=t.data,T=t.width,A=t.height,M=e+e+1,G=T-1,E=A-1,R=e+1,L=R*(R+1)/2,D=new Jt,O=null,I=D,F=null,N=null,B=Zt[e],z=$t[e];for(a=1;a>z,0!==C?(C=255/C,P[o]=(l*B>>z)*C,P[o+1]=(d*B>>z)*C,P[o+2]=(c*B>>z)*C):P[o]=P[o+1]=P[o+2]=0,l-=u,d-=f,c-=p,g-=v,u-=F.r,f-=F.g,p-=F.b,v-=F.a,n=h+((n=i+e+1)>z,C>0?(C=255/C,P[n]=(l*B>>z)*C,P[n+1]=(d*B>>z)*C,P[n+2]=(c*B>>z)*C):P[n]=P[n+1]=P[n+2]=0,l-=u,d-=f,c-=p,g-=v,u-=F.r,f-=F.g,p-=F.b,v-=F.a,n=i+((n=r+R)255?255:n,s=(s*=255)<0?0:s>255?255:s,o=(o*=255)<0?0:o>255?255:o,r[e]=n,r[e+1]=s,r[e+2]=o},Emboss:function(t){var e=10*this.embossStrength(),i=255*this.embossWhiteLevel(),r=this.embossDirection(),a=this.embossBlend(),n=0,s=0,o=t.data,h=t.width,l=t.height,d=4*h,g=l;switch(r){case"top-left":n=-1,s=-1;break;case"top":n=-1,s=0;break;case"top-right":n=-1,s=1;break;case"right":n=0,s=1;break;case"bottom-right":n=1,s=1;break;case"bottom":n=1,s=0;break;case"bottom-left":n=1,s=-1;break;case"left":n=0,s=-1;break;default:c.error("Unknown emboss direction: "+r)}do{var u=(g-1)*d,f=n;g+f<1&&(f=0),g+f>l&&(f=0);var p=(g-1+f)*h*4,v=h;do{var m=u+4*(v-1),_=s;v+_<1&&(_=0),v+_>h&&(_=0);var y=p+4*(v-1+_),x=o[m]-o[y],b=o[m+1]-o[y+1],S=o[m+2]-o[y+2],w=x,C=w>0?w:-w;if((b>0?b:-b)>C&&(w=b),(S>0?S:-S)>C&&(w=S),w*=e,a){var k=o[m]+w,P=o[m+1]+w,T=o[m+2]+w;o[m]=k>255?255:k<0?0:k,o[m+1]=P>255?255:P<0?0:P,o[m+2]=T>255?255:T<0?0:T}else{var A=i-w;A<0?A=0:A>255&&(A=255),o[m]=o[m+1]=o[m+2]=A}}while(--v)}while(--g)},Enhance:function(t){var e,i,r,a,n=t.data,s=n.length,o=n[0],h=o,l=n[1],d=l,c=n[2],g=c,u=this.enhance();if(0!==u){for(a=0;ah&&(h=e),(i=n[a+1])d&&(d=i),(r=n[a+2])g&&(g=r);var f,p,v,m,_,y,x,b,S;for(h===o&&(h=255,o=0),d===l&&(d=255,l=0),g===c&&(g=255,c=0),u>0?(p=h+u*(255-h),v=o-u*(o-0),_=d+u*(255-d),y=l-u*(l-0),b=g+u*(255-g),S=c-u*(c-0)):(p=h+u*(h-(f=.5*(h+o))),v=o+u*(o-f),_=d+u*(d-(m=.5*(d+l))),y=l+u*(l-m),b=g+u*(g-(x=.5*(g+c))),S=c+u*(c-x)),a=0;am?s:m;var _,y,x,b,S=d,w=l,C=360/w*Math.PI/180;for(y=0;yd&&(x=y,b=0,S=-1),i=0;iy?h:y;var x,b,S,w=g,C=c,k=i.polarRotation||0;for(a=0;a=0&&u=0&&f=0&&u=0&&f=1020?255:0}return s}(e=function(t,e,i){for(var r=[1,1,1,1,0,1,1,1,1],a=Math.round(Math.sqrt(r.length)),n=Math.floor(a/2),s=[],o=0;o=0&&u=0&&f=m))for(i=d;i=_||(a+=b[(r=4*(m*i+e))+0],n+=b[r+1],s+=b[r+2],o+=b[r+3],p+=1);for(a/=p,n/=p,s/=p,o/=p,e=h;e=m))for(i=d;i=_||(b[(r=4*(m*i+e))+0]=a,b[r+1]=n,b[r+2]=s,b[r+3]=o)}},Posterize:function(t){var e,i=Math.round(254*this.levels())+1,r=t.data,a=r.length,n=255/i;for(e=0;e127&&(h=255-h),l>127&&(l=255-l),d>127&&(d=255-d),e[o]=h,e[o+1]=l,e[o+2]=d}while(--s)}while(--a)},Threshold:function(t){var e,i=255*this.threshold(),r=t.data,a=r.length;for(e=0;e { + filePaths.forEach((filepath) => { + fs.readFile(filepath, 'utf8', (err, text) => { + if (!text.match(/import .* from/g)) { + return; + } + text = text.replace(/(import .* from\s+['"])(.*)(?=['"])/g, '$1$2.js'); + if (text.match(/export .* from/g)) { + text = text.replace(/(export .* from\s+['"])(.*)(?=['"])/g, '$1$2.js'); + } + + if (err) throw err; + + // stupid replacement back + text = text.replace( + "import * as canvas from 'canvas.js';", + "import * as canvas from 'canvas';" + ); + + console.log(`writing to ${filepath}`); + fs.writeFile(filepath, text, function (err) { + if (err) { + throw err; + } + }); + }); + }); +});