UNPKG

react-konva-image-editor

Version:

🖼 HTML5 Canvas API Image Editor based on React.js & Konva.js

1,876 lines (1,688 loc) • 1.77 MB
import * as React from 'react'; import React__default, { forwardRef, useContext, createContext, createElement, Fragment, useRef, useLayoutEffect, Children, isValidElement, cloneElement, useState, useMemo, useEffect, useCallback } from 'react'; import require$$2, { jsx, jsxs } from 'react/jsx-runtime'; import * as ReactDOM from 'react-dom'; import ReactDOM__default from 'react-dom'; var PI_OVER_180 = Math.PI / 180; function detectBrowser() { return typeof window !== 'undefined' && ({}.toString.call(window) === '[object Window]' || {}.toString.call(window) === '[object global]'); } var glob = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof WorkerGlobalScope !== 'undefined' ? self : {}; var Konva$2 = { _global: glob, version: '8.2.2', isBrowser: detectBrowser(), isUnminified: /param/.test(function (param) {}.toString()), dblClickWindow: 400, getAngle: function getAngle(angle) { return Konva$2.angleDeg ? angle * PI_OVER_180 : angle; }, enableTrace: false, pointerEventsEnabled: true, autoDrawEnabled: true, hitOnDragEnabled: false, capturePointerEventsEnabled: false, _mouseListenClick: false, _touchListenClick: false, _pointerListenClick: false, _mouseInDblClickWindow: false, _touchInDblClickWindow: false, _pointerInDblClickWindow: false, _mouseDblClickPointerId: null, _touchDblClickPointerId: null, _pointerDblClickPointerId: null, pixelRatio: typeof window !== 'undefined' && window.devicePixelRatio || 1, dragDistance: 3, angleDeg: true, showWarnings: true, dragButtons: [0, 1], isDragging: function isDragging() { return Konva$2['DD'].isDragging; }, isDragReady: function isDragReady() { return !!Konva$2['DD'].node; }, document: glob.document, _injectGlobal: function _injectGlobal(Konva) { glob.Konva = Konva; } }; var _registerNode = function _registerNode(NodeClass) { Konva$2[NodeClass.prototype.getClassName()] = NodeClass; }; Konva$2._injectGlobal(Konva$2); function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function (obj) { return typeof obj; }; } else { _typeof = function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf$1(subClass, superClass); } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } function _setPrototypeOf$1(o, p) { _setPrototypeOf$1 = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf$1(o, p); } function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } } function _assertThisInitialized$1(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _possibleConstructorReturn(self, call) { if (call && (typeof call === "object" || typeof call === "function")) { return call; } else if (call !== void 0) { throw new TypeError("Derived constructors may only return object or undefined"); } return _assertThisInitialized$1(self); } function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; } function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); } function _taggedTemplateLiteral(strings, raw) { if (!raw) { raw = strings.slice(0); } return Object.freeze(Object.defineProperties(strings, { raw: { value: Object.freeze(raw) } })); } function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableRest(); } function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); } function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _createForOfIteratorHelper(o, allowArrayLike) { var it = typeof Symbol !== "undefined" && o[Symbol.iterator] || o["@@iterator"]; if (!it) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function () {}; return { s: F, n: function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function (e) { throw e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function () { it = it.call(o); }, n: function () { var step = it.next(); normalCompletion = step.done; return step; }, e: function (e) { didErr = true; err = e; }, f: function () { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; } var Transform = /*#__PURE__*/function () { function Transform() { var m = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [1, 0, 0, 1, 0, 0]; _classCallCheck(this, Transform); this.dirty = false; this.m = m && m.slice() || [1, 0, 0, 1, 0, 0]; } _createClass(Transform, [{ key: "reset", value: function 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; } }, { key: "copy", value: function copy() { return new Transform(this.m); } }, { key: "copyInto", value: function copyInto(tr) { tr.m[0] = this.m[0]; tr.m[1] = this.m[1]; tr.m[2] = this.m[2]; tr.m[3] = this.m[3]; tr.m[4] = this.m[4]; tr.m[5] = this.m[5]; } }, { key: "point", value: function point(_point) { var m = this.m; return { x: m[0] * _point.x + m[2] * _point.y + m[4], y: m[1] * _point.x + m[3] * _point.y + m[5] }; } }, { key: "translate", value: function translate(x, y) { this.m[4] += this.m[0] * x + this.m[2] * y; this.m[5] += this.m[1] * x + this.m[3] * y; return this; } }, { key: "scale", value: function scale(sx, sy) { this.m[0] *= sx; this.m[1] *= sx; this.m[2] *= sy; this.m[3] *= sy; return this; } }, { key: "rotate", value: function rotate(rad) { var c = Math.cos(rad); var s = Math.sin(rad); var m11 = this.m[0] * c + this.m[2] * s; var m12 = this.m[1] * c + this.m[3] * s; var m21 = this.m[0] * -s + this.m[2] * c; var m22 = this.m[1] * -s + this.m[3] * c; this.m[0] = m11; this.m[1] = m12; this.m[2] = m21; this.m[3] = m22; return this; } }, { key: "getTranslation", value: function getTranslation() { return { x: this.m[4], y: this.m[5] }; } }, { key: "skew", value: function skew(sx, sy) { var m11 = this.m[0] + this.m[2] * sy; var m12 = this.m[1] + this.m[3] * sy; var m21 = this.m[2] + this.m[0] * sx; var m22 = this.m[3] + this.m[1] * sx; this.m[0] = m11; this.m[1] = m12; this.m[2] = m21; this.m[3] = m22; return this; } }, { key: "multiply", value: function multiply(matrix) { var m11 = this.m[0] * matrix.m[0] + this.m[2] * matrix.m[1]; var m12 = this.m[1] * matrix.m[0] + this.m[3] * matrix.m[1]; var m21 = this.m[0] * matrix.m[2] + this.m[2] * matrix.m[3]; var m22 = this.m[1] * matrix.m[2] + this.m[3] * matrix.m[3]; var dx = this.m[0] * matrix.m[4] + this.m[2] * matrix.m[5] + this.m[4]; var dy = this.m[1] * matrix.m[4] + this.m[3] * matrix.m[5] + this.m[5]; this.m[0] = m11; this.m[1] = m12; this.m[2] = m21; this.m[3] = m22; this.m[4] = dx; this.m[5] = dy; return this; } }, { key: "invert", value: function invert() { var d = 1 / (this.m[0] * this.m[3] - this.m[1] * this.m[2]); var m0 = this.m[3] * d; var m1 = -this.m[1] * d; var m2 = -this.m[2] * d; var m3 = this.m[0] * d; var m4 = d * (this.m[2] * this.m[5] - this.m[3] * this.m[4]); var m5 = d * (this.m[1] * this.m[4] - this.m[0] * this.m[5]); this.m[0] = m0; this.m[1] = m1; this.m[2] = m2; this.m[3] = m3; this.m[4] = m4; this.m[5] = m5; return this; } }, { key: "getMatrix", value: function getMatrix() { return this.m; } }, { key: "setAbsolutePosition", value: function setAbsolutePosition(x, y) { var m0 = this.m[0], m1 = this.m[1], m2 = this.m[2], m3 = this.m[3], m4 = this.m[4], m5 = this.m[5], yt = (m0 * (y - m5) - m1 * (x - m4)) / (m0 * m3 - m1 * m2), xt = (x - m4 - m2 * yt) / m0; return this.translate(xt, yt); } }, { key: "decompose", value: function decompose() { var a = this.m[0]; var b = this.m[1]; var c = this.m[2]; var d = this.m[3]; var e = this.m[4]; var f = this.m[5]; var delta = a * d - b * c; var result = { x: e, y: f, rotation: 0, scaleX: 0, scaleY: 0, skewX: 0, skewY: 0 }; if (a != 0 || b != 0) { var r = Math.sqrt(a * a + b * b); result.rotation = b > 0 ? Math.acos(a / r) : -Math.acos(a / r); result.scaleX = r; result.scaleY = delta / r; result.skewX = (a * c + b * d) / delta; result.skewY = 0; } else if (c != 0 || d != 0) { var s = Math.sqrt(c * c + d * d); result.rotation = Math.PI / 2 - (d > 0 ? Math.acos(-c / s) : -Math.acos(c / s)); result.scaleX = delta / s; result.scaleY = s; result.skewX = 0; result.skewY = (a * c + b * d) / delta; } else ; result.rotation = Util._getRotation(result.rotation); return result; } }]); return Transform; }(); 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], 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] }, RGB_REGEX = /rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/, animQueue = []; var req = typeof requestAnimationFrame !== 'undefined' && requestAnimationFrame || function (f) { setTimeout(f, 60); }; var Util = { _isElement: function _isElement(obj) { return !!(obj && obj.nodeType == 1); }, _isFunction: function _isFunction(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); }, _isPlainObject: function _isPlainObject(obj) { return !!obj && obj.constructor === Object; }, _isArray: function _isArray(obj) { return Object.prototype.toString.call(obj) === OBJECT_ARRAY; }, _isNumber: function _isNumber(obj) { return Object.prototype.toString.call(obj) === OBJECT_NUMBER && !isNaN(obj) && isFinite(obj); }, _isString: function _isString(obj) { return Object.prototype.toString.call(obj) === OBJECT_STRING; }, _isBoolean: function _isBoolean(obj) { return Object.prototype.toString.call(obj) === OBJECT_BOOLEAN; }, isObject: function isObject(val) { return val instanceof Object; }, isValidSelector: function isValidSelector(selector) { if (typeof selector !== 'string') { return false; } var firstChar = selector[0]; return firstChar === '#' || firstChar === '.' || firstChar === firstChar.toUpperCase(); }, _sign: function _sign(number) { if (number === 0) { return 1; } if (number > 0) { return 1; } else { return -1; } }, requestAnimFrame: function requestAnimFrame(callback) { animQueue.push(callback); if (animQueue.length === 1) { req(function () { var queue = animQueue; animQueue = []; queue.forEach(function (cb) { cb(); }); }); } }, createCanvasElement: function createCanvasElement() { var canvas = document.createElement('canvas'); try { canvas.style = canvas.style || {}; } catch (e) {} return canvas; }, createImageElement: function createImageElement() { return document.createElement('img'); }, _isInDocument: function _isInDocument(el) { while (el = el.parentNode) { if (el == document) { return true; } } return false; }, _urlToImage: function _urlToImage(url, callback) { var imageObj = Util.createImageElement(); imageObj.onload = function () { callback(imageObj); }; imageObj.src = url; }, _rgbToHex: function _rgbToHex(r, g, b) { return ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1); }, _hexToRgb: function _hexToRgb(hex) { hex = hex.replace(HASH$1, EMPTY_STRING$1); var bigint = parseInt(hex, 16); return { r: bigint >> 16 & 255, g: bigint >> 8 & 255, b: bigint & 255 }; }, getRandomColor: function getRandomColor() { var randColor = (Math.random() * 0xffffff << 0).toString(16); while (randColor.length < 6) { randColor = ZERO + randColor; } return HASH$1 + randColor; }, getRGB: function getRGB(color) { var rgb; if (color in COLORS) { rgb = COLORS[color]; return { r: rgb[0], g: rgb[1], b: rgb[2] }; } else if (color[0] === HASH$1) { return this._hexToRgb(color.substring(1)); } else if (color.substr(0, 4) === RGB_PAREN) { rgb = RGB_REGEX.exec(color.replace(/ /g, '')); return { r: parseInt(rgb[1], 10), g: parseInt(rgb[2], 10), b: parseInt(rgb[3], 10) }; } else { return { r: 0, g: 0, b: 0 }; } }, colorToRGBA: function colorToRGBA(str) { str = str || 'black'; return Util._namedColorToRBA(str) || Util._hex3ColorToRGBA(str) || Util._hex6ColorToRGBA(str) || Util._rgbColorToRGBA(str) || Util._rgbaColorToRGBA(str) || Util._hslColorToRGBA(str); }, _namedColorToRBA: function _namedColorToRBA(str) { var c = COLORS[str.toLowerCase()]; if (!c) { return null; } return { r: c[0], g: c[1], b: c[2], a: 1 }; }, _rgbColorToRGBA: function _rgbColorToRGBA(str) { if (str.indexOf('rgb(') === 0) { str = str.match(/rgb\(([^)]+)\)/)[1]; var parts = str.split(/ *, */).map(Number); return { r: parts[0], g: parts[1], b: parts[2], a: 1 }; } }, _rgbaColorToRGBA: function _rgbaColorToRGBA(str) { if (str.indexOf('rgba(') === 0) { str = str.match(/rgba\(([^)]+)\)/)[1]; var parts = str.split(/ *, */).map(Number); return { r: parts[0], g: parts[1], b: parts[2], a: parts[3] }; } }, _hex6ColorToRGBA: function _hex6ColorToRGBA(str) { if (str[0] === '#' && str.length === 7) { return { r: parseInt(str.slice(1, 3), 16), g: parseInt(str.slice(3, 5), 16), b: parseInt(str.slice(5, 7), 16), a: 1 }; } }, _hex3ColorToRGBA: function _hex3ColorToRGBA(str) { if (str[0] === '#' && str.length === 4) { return { r: parseInt(str[1] + str[1], 16), g: parseInt(str[2] + str[2], 16), b: parseInt(str[3] + str[3], 16), a: 1 }; } }, _hslColorToRGBA: function _hslColorToRGBA(str) { if (/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(str)) { var _$exec = /hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(str), _$exec2 = _toArray(_$exec); _$exec2[0]; var hsl = _$exec2.slice(1); var h = Number(hsl[0]) / 360; var s = Number(hsl[1]) / 100; var l = Number(hsl[2]) / 100; var t2; var t3; var val; if (s === 0) { val = l * 255; return { r: Math.round(val), g: Math.round(val), b: Math.round(val), a: 1 }; } if (l < 0.5) { t2 = l * (1 + s); } else { t2 = l + s - l * s; } var t1 = 2 * l - t2; var rgb = [0, 0, 0]; for (var i = 0; i < 3; i++) { t3 = h + 1 / 3 * -(i - 1); if (t3 < 0) { t3++; } if (t3 > 1) { t3--; } if (6 * t3 < 1) { val = t1 + (t2 - t1) * 6 * t3; } else if (2 * t3 < 1) { val = t2; } else if (3 * t3 < 2) { val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; } else { val = t1; } rgb[i] = val * 255; } return { r: Math.round(rgb[0]), g: Math.round(rgb[1]), b: Math.round(rgb[2]), a: 1 }; } }, haveIntersection: function haveIntersection(r1, r2) { return !(r2.x > r1.x + r1.width || r2.x + r2.width < r1.x || r2.y > r1.y + r1.height || r2.y + r2.height < r1.y); }, cloneObject: function cloneObject(obj) { var retObj = {}; for (var key in obj) { if (this._isPlainObject(obj[key])) { retObj[key] = this.cloneObject(obj[key]); } else if (this._isArray(obj[key])) { retObj[key] = this.cloneArray(obj[key]); } else { retObj[key] = obj[key]; } } return retObj; }, cloneArray: function cloneArray(arr) { return arr.slice(0); }, degToRad: function degToRad(deg) { return deg * PI_OVER_DEG180; }, radToDeg: function radToDeg(rad) { return rad * DEG180_OVER_PI; }, _degToRad: function _degToRad(deg) { Util.warn('Util._degToRad is removed. Please use public Util.degToRad instead.'); return Util.degToRad(deg); }, _radToDeg: function _radToDeg(rad) { Util.warn('Util._radToDeg is removed. Please use public Util.radToDeg instead.'); return Util.radToDeg(rad); }, _getRotation: function _getRotation(radians) { return Konva$2.angleDeg ? Util.radToDeg(radians) : radians; }, _capitalize: function _capitalize(str) { return str.charAt(0).toUpperCase() + str.slice(1); }, "throw": function _throw(str) { throw new Error(KONVA_ERROR + str); }, error: function error(str) { console.error(KONVA_ERROR + str); }, warn: function warn(str) { if (!Konva$2.showWarnings) { return; } console.warn(KONVA_WARNING + str); }, each: function each(obj, func) { for (var key in obj) { func(key, obj[key]); } }, _inRange: function _inRange(val, left, right) { return left <= val && val < right; }, _getProjectionToSegment: function _getProjectionToSegment(x1, y1, x2, y2, x3, y3) { var x, y, dist; var pd2 = (x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2); if (pd2 == 0) { x = x1; y = y1; dist = (x3 - x2) * (x3 - x2) + (y3 - y2) * (y3 - y2); } else { var u = ((x3 - x1) * (x2 - x1) + (y3 - y1) * (y2 - y1)) / pd2; if (u < 0) { x = x1; y = y1; dist = (x1 - x3) * (x1 - x3) + (y1 - y3) * (y1 - y3); } else if (u > 1.0) { x = x2; y = y2; dist = (x2 - x3) * (x2 - x3) + (y2 - y3) * (y2 - y3); } else { x = x1 + u * (x2 - x1); y = y1 + u * (y2 - y1); dist = (x - x3) * (x - x3) + (y - y3) * (y - y3); } } return [x, y, dist]; }, _getProjectionToLine: function _getProjectionToLine(pt, line, isClosed) { var pc = Util.cloneObject(pt); var dist = Number.MAX_VALUE; line.forEach(function (p1, i) { if (!isClosed && i === line.length - 1) { return; } var p2 = line[(i + 1) % line.length]; var proj = Util._getProjectionToSegment(p1.x, p1.y, p2.x, p2.y, pt.x, pt.y); var px = proj[0], py = proj[1], pdist = proj[2]; if (pdist < dist) { pc.x = px; pc.y = py; dist = pdist; } }); return pc; }, _prepareArrayForTween: function _prepareArrayForTween(startArray, endArray, isClosed) { var n, start = [], end = []; if (startArray.length > endArray.length) { var temp = endArray; endArray = startArray; startArray = temp; } for (n = 0; n < startArray.length; n += 2) { start.push({ x: startArray[n], y: startArray[n + 1] }); } for (n = 0; n < endArray.length; n += 2) { end.push({ x: endArray[n], y: endArray[n + 1] }); } var newStart = []; end.forEach(function (point) { var pr = Util._getProjectionToLine(point, start, isClosed); newStart.push(pr.x); newStart.push(pr.y); }); return newStart; }, _prepareToStringify: function _prepareToStringify(obj) { var desc; obj.visitedByCircularReferenceRemoval = true; for (var key in obj) { if (!(obj.hasOwnProperty(key) && obj[key] && _typeof(obj[key]) == 'object')) { continue; } desc = Object.getOwnPropertyDescriptor(obj, key); if (obj[key].visitedByCircularReferenceRemoval || Util._isElement(obj[key])) { if (desc.configurable) { delete obj[key]; } else { return null; } } else if (Util._prepareToStringify(obj[key]) === null) { if (desc.configurable) { delete obj[key]; } else { return null; } } } delete obj.visitedByCircularReferenceRemoval; return obj; }, _assign: function _assign(target, source) { for (var key in source) { target[key] = source[key]; } return target; }, _getFirstPointerId: function _getFirstPointerId(evt) { if (!evt.touches) { return 999; } else { return evt.changedTouches[0].identifier; } } }; function _formatValue(val) { if (Util._isString(val)) { return '"' + val + '"'; } if (Object.prototype.toString.call(val) === '[object Number]') { return val; } if (Util._isBoolean(val)) { return val; } return Object.prototype.toString.call(val); } function RGBComponent(val) { if (val > 255) { return 255; } else if (val < 0) { return 0; } return Math.round(val); } function getNumberValidator() { if (Konva$2.isUnminified) { return function (val, attr) { if (!Util._isNumber(val)) { Util.warn(_formatValue(val) + ' is a not valid value for "' + attr + '" attribute. The value should be a number.'); } return val; }; } } function getNumberOrArrayOfNumbersValidator(noOfElements) { if (Konva$2.isUnminified) { return function (val, attr) { var isNumber = Util._isNumber(val); var isValidArray = Util._isArray(val) && val.length == noOfElements; if (!isNumber && !isValidArray) { Util.warn(_formatValue(val) + ' is a not valid value for "' + attr + '" attribute. The value should be a number or Array<number>(' + noOfElements + ')'); } return val; }; } } function getNumberOrAutoValidator() { if (Konva$2.isUnminified) { return function (val, attr) { var isNumber = Util._isNumber(val); var isAuto = val === 'auto'; if (!(isNumber || isAuto)) { Util.warn(_formatValue(val) + ' is a not valid value for "' + attr + '" attribute. The value should be a number or "auto".'); } return val; }; } } function getStringValidator() { if (Konva$2.isUnminified) { return function (val, attr) { if (!Util._isString(val)) { Util.warn(_formatValue(val) + ' is a not valid value for "' + attr + '" attribute. The value should be a string.'); } return val; }; } } function getStringOrGradientValidator() { if (Konva$2.isUnminified) { return function (val, attr) { var isString = Util._isString(val); var isGradient = Object.prototype.toString.call(val) === '[object CanvasGradient]' || val && val.addColorStop; if (!(isString || isGradient)) { Util.warn(_formatValue(val) + ' is a not valid value for "' + attr + '" attribute. The value should be a string or a native gradient.'); } return val; }; } } function getNumberArrayValidator() { if (Konva$2.isUnminified) { return function (val, attr) { if (!Util._isArray(val)) { Util.warn(_formatValue(val) + ' is a not valid value for "' + attr + '" attribute. The value should be a array of numbers.'); } else { val.forEach(function (item) { if (!Util._isNumber(item)) { Util.warn('"' + attr + '" attribute has non numeric element ' + item + '. Make sure that all elements are numbers.'); } }); } return val; }; } } function getBooleanValidator() { if (Konva$2.isUnminified) { return function (val, attr) { var isBool = val === true || val === false; if (!isBool) { Util.warn(_formatValue(val) + ' is a not valid value for "' + attr + '" attribute. The value should be a boolean.'); } return val; }; } } function getComponentValidator(components) { if (Konva$2.isUnminified) { return function (val, attr) { if (!Util.isObject(val)) { Util.warn(_formatValue(val) + ' is a not valid value for "' + attr + '" attribute. The value should be an object with properties ' + components); } return val; }; } } var GET = 'get', SET$1 = 'set'; var Factory = { addGetterSetter: function addGetterSetter(constructor, attr, def, validator, after) { Factory.addGetter(constructor, attr, def); Factory.addSetter(constructor, attr, validator, after); Factory.addOverloadedGetterSetter(constructor, attr); }, addGetter: function addGetter(constructor, attr, def) { var method = GET + Util._capitalize(attr); constructor.prototype[method] = constructor.prototype[method] || function () { var val = this.attrs[attr]; return val === undefined ? def : val; }; }, addSetter: function addSetter(constructor, attr, validator, after) { var method = SET$1 + Util._capitalize(attr); if (!constructor.prototype[method]) { Factory.overWriteSetter(constructor, attr, validator, after); } }, overWriteSetter: function overWriteSetter(constructor, attr, validator, after) { var method = SET$1 + Util._capitalize(attr); constructor.prototype[method] = function (val) { if (validator && val !== undefined && val !== null) { val = validator.call(this, val, attr); } this._setAttr(attr, val); if (after) { after.call(this); } return this; }; }, addComponentsGetterSetter: function addComponentsGetterSetter(constructor, attr, components, validator, after) { var len = components.length, capitalize = Util._capitalize, getter = GET + capitalize(attr), setter = SET$1 + capitalize(attr), n, component; constructor.prototype[getter] = function () { var ret = {}; for (n = 0; n < len; n++) { component = components[n]; ret[component] = this.getAttr(attr + capitalize(component)); } return ret; }; var basicValidator = getComponentValidator(components); constructor.prototype[setter] = function (val) { var oldVal = this.attrs[attr], key; if (validator) { val = validator.call(this, val); } if (basicValidator) { basicValidator.call(this, val, attr); } for (key in val) { if (!val.hasOwnProperty(key)) { continue; } this._setAttr(attr + capitalize(key), val[key]); } this._fireChangeEvent(attr, oldVal, val); if (after) { after.call(this); } return this; }; Factory.addOverloadedGetterSetter(constructor, attr); }, addOverloadedGetterSetter: function addOverloadedGetterSetter(constructor, attr) { var capitalizedAttr = Util._capitalize(attr), setter = SET$1 + capitalizedAttr, getter = GET + capitalizedAttr; constructor.prototype[attr] = function () { if (arguments.length) { this[setter](arguments[0]); return this; } return this[getter](); }; }, addDeprecatedGetterSetter: function addDeprecatedGetterSetter(constructor, attr, def, validator) { Util.error('Adding deprecated ' + attr); var method = GET + Util._capitalize(attr); var message = attr + ' property is deprecated and will be removed soon. Look at Konva change log for more information.'; constructor.prototype[method] = function () { Util.error(message); var val = this.attrs[attr]; return val === undefined ? def : val; }; Factory.addSetter(constructor, attr, validator, function () { Util.error(message); }); Factory.addOverloadedGetterSetter(constructor, attr); }, backCompat: function backCompat(constructor, methods) { Util.each(methods, function (oldMethodName, newMethodName) { var method = constructor.prototype[newMethodName]; var oldGetter = GET + Util._capitalize(oldMethodName); var oldSetter = SET$1 + Util._capitalize(oldMethodName); function deprecated() { method.apply(this, arguments); Util.error('"' + oldMethodName + '" method is deprecated and will be removed soon. Use ""' + newMethodName + '" instead.'); } constructor.prototype[oldMethodName] = deprecated; constructor.prototype[oldGetter] = deprecated; constructor.prototype[oldSetter] = deprecated; }); }, afterSetFilter: function afterSetFilter() { this._filterUpToDate = false; } }; 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 = '()', EQUALS = '=', CONTEXT_METHODS = ['arc', 'arcTo', 'beginPath', 'bezierCurveTo', 'clearRect', 'clip', 'closePath', 'createLinearGradient', 'createPattern', 'createRadialGradient', 'drawImage', 'ellipse', 'fill', 'fillText', 'getImageData', 'createImageData', 'lineTo', 'moveTo', 'putImageData', 'quadraticCurveTo', 'rect', 'restore', 'rotate', 'save', 'scale', 'setLineDash', 'setTransform', 'stroke', 'strokeText', 'transform', 'translate']; var CONTEXT_PROPERTIES = ['fillStyle', 'strokeStyle', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY', 'lineCap', 'lineDashOffset', 'lineJoin', 'lineWidth', 'miterLimit', 'font', 'textAlign', 'textBaseline', 'globalAlpha', 'globalCompositeOperation', 'imageSmoothingEnabled']; var traceArrMax = 100; var Context = /*#__PURE__*/function () { function Context(canvas) { _classCallCheck(this, Context); this.canvas = canvas; this._context = canvas._canvas.getContext('2d'); if (Konva$2.enableTrace) { this.traceArr = []; this._enableTrace(); } } _createClass(Context, [{ key: "fillShape", value: function fillShape(shape) { if (shape.fillEnabled()) { this._fill(shape); } } }, { key: "_fill", value: function _fill(shape) {} }, { key: "strokeShape", value: function strokeShape(shape) { if (shape.hasStroke()) { this._stroke(shape); } } }, { key: "_stroke", value: function _stroke(shape) {} }, { key: "fillStrokeShape", value: function fillStrokeShape(shape) { if (shape.attrs.fillAfterStrokeEnabled) { this.strokeShape(shape); this.fillShape(shape); } else { this.fillShape(shape); this.strokeShape(shape); } } }, { key: "getTrace", value: function getTrace(relaxed, rounded) { var traceArr = this.traceArr, len = traceArr.length, str = '', n, trace, method, args; for (n = 0; n < len; n++) { trace = traceArr[n]; method = trace.method; if (method) { args = trace.args; str += method; if (relaxed) { str += DOUBLE_PAREN; } else { if (Util._isArray(args[0])) { str += OPEN_PAREN_BRACKET + args.join(COMMA) + CLOSE_BRACKET_PAREN; } else { if (rounded) { args = args.map(function (a) { return typeof a === 'number' ? Math.floor(a) : a; }); } str += OPEN_PAREN + args.join(COMMA) + CLOSE_PAREN; } } } else { str += trace.property; if (!relaxed) { str += EQUALS + trace.val; } } str += SEMICOLON; } return str; } }, { key: "clearTrace", value: function clearTrace() { this.traceArr = []; } }, { key: "_trace", value: function _trace(str) { var traceArr = this.traceArr, len; traceArr.push(str); len = traceArr.length; if (len >= traceArrMax) { traceArr.shift(); } } }, { key: "reset", value: function reset() { var pixelRatio = this.getCanvas().getPixelRatio(); this.setTransform(1 * pixelRatio, 0, 0, 1 * pixelRatio, 0, 0); } }, { key: "getCanvas", value: function getCanvas() { return this.canvas; } }, { key: "clear", value: function clear(bounds) { var canvas = this.getCanvas(); if (bounds) { this.clearRect(bounds.x || 0, bounds.y || 0, bounds.width || 0, bounds.height || 0); } else { this.clearRect(0, 0, canvas.getWidth() / canvas.pixelRatio, canvas.getHeight() / canvas.pixelRatio); } } }, { key: "_applyLineCap", value: function _applyLineCap(shape) { var lineCap = shape.getLineCap(); if (lineCap) { this.setAttr('lineCap', lineCap); } } }, { key: "_applyOpacity", value: function _applyOpacity(shape) { var absOpacity = shape.getAbsoluteOpacity(); if (absOpacity !== 1) { this.setAttr('globalAlpha', absOpacity); } } }, { key: "_applyLineJoin", value: function _applyLineJoin(shape) { var lineJoin = shape.attrs.lineJoin; if (lineJoin) { this.setAttr('lineJoin', lineJoin); } } }, { key: "setAttr", value: function setAttr(attr, val) { this._context[attr] = val; } }, { key: "arc", value: function arc(a0, a1, a2, a3, a4, a5) { this._context.arc(a0, a1, a2, a3, a4, a5); } }, { key: "arcTo", value: function arcTo(a0, a1, a2, a3, a4) { this._context.arcTo(a0, a1, a2, a3, a4); } }, { key: "beginPath", value: function beginPath() { this._context.beginPath(); } }, { key: "bezierCurveTo", value: function bezierCurveTo(a0, a1, a2, a3, a4, a5) { this._context.bezierCurveTo(a0, a1, a2, a3, a4, a5); } }, { key: "clearRect", value: function clearRect(a0, a1, a2, a3) { this._context.clearRect(a0, a1, a2, a3); } }, { key: "clip", value: function clip() { this._context.clip(); } }, { key: "closePath", value: function closePath() { this._context.closePath(); } }, { key: "createImageData", value: function createImageData(a0, a1) { var a = arguments; if (a.length === 2) { return this._context.createImageData(a0, a1); } else if (a.length === 1) { return this._context.createImageData(a0); } } }, { key: "createLinearGradient", value: function createLinearGradient(a0, a1, a2, a3) { return this._context.createLinearGradient(a0, a1, a2, a3); } }, { key: "createPattern", value: function createPattern(a0, a1) { return this._context.createPattern(a0, a1); } }, { key: "createRadialGradient", value: function createRadialGradient(a0, a1, a2, a3, a4, a5) { return this._context.createRadialGradient(a0, a1, a2, a3, a4, a5); } }, { key: "drawImage", value: function drawImage(a0, a1, a2, a3, a4, a5, a6, a7, a8) { var a = arguments, _context = this._context; if (a.length === 3) { _context.drawImage(a0, a1, a2); } else if (a.length === 5) { _context.drawImage(a0, a1, a2, a3, a4); } else if (a.length === 9) { _context.drawImage(a0, a1, a2, a3, a4, a5, a6, a7, a8); } } }, { key: "ellipse", value: function ellipse(a0, a1, a2, a3, a4, a5, a6, a7) { this._context.ellipse(a0, a1, a2, a3, a4, a5, a6, a7); } }, { key: "isPointInPath", value: function isPointInPath(x, y) { return this._context.isPointInPath(x, y); } }, { key: "fill", value: function fill(path2d) { if (path2d) { this._context.fill(path2d); } else { this._context.fill(); } } }, { key: "fillRect", value: function fillRect(x, y, width, height) { this._context.fillRect(x, y, width, height); } }, { key: "strokeRect", value: function strokeRect(x, y, width, height) { this._context.strokeRect(x, y, width, height); } }, { key: "fillText", value: function fillText(text, x, y, maxWidth) { if (maxWidth) { this._context.fillText(text, x, y, maxWidth); } else { this._context.fillText(text, x, y); } } }, { key: "measureText", value: function measureText(text) { return this._context.measureText(text); } }, { key: "getImageData", value: function getImageData(a0, a1, a2, a3) { return this._context.getImageData(a0, a1, a2, a3); } }, { key: "lineTo", value: function lineTo(a0, a1) { this._context.lineTo(a0, a1); } }, { key: "moveTo", value: function moveTo(a0, a1) { this._context.moveTo(a0, a1); } }, { key: "rect", value: function rect(a0, a1, a2, a3) { this._context.rect(a0, a1, a2, a3); } }, { key: "putImageData", value: function putImageData(a0, a1, a2) { this._context.putImageData(a0, a1, a2); } }, { key: "quadraticCurveTo", value: function quadraticCurveTo(a0, a1, a2, a3) { this._context.quadraticCurveTo(a0, a1, a2, a3); } }, { key: "restore", value: function restore() { this._context.restore(); } }, { key: "rotate", value: function rotate(a0) { this._context.rotate(a0); } }, { key: "save", value: function save() { this._context.save(); } }, { key: "scale", value: function scale(a0, a1) { this._context.scale(a0, a1); } }, { key: "setLineDash", value: function setLineDash(a0) { if (this._context.setLineDash) { this._context.setLineDash(a0); } else if ('mozDash' in this._context) { this._context['mozDash'] = a0; } else if ('webkitLineDash' in this._context) { this._context['webkitLineDash'] = a0; } } }, { key: "getLineDash", value: function getLineDash() { return this._context.getLineDash(); } }, { key: "setTransform", value: function setTransform(a0, a1, a2, a3, a4, a5) { this._context.setTransform(a0, a1, a2, a3, a4, a5); } }, { key: "stroke", value: function stroke(path2d) { if (path2d) { this._context.stroke(path2d); } else { this._context.stroke(); } } }, { key: "strokeText", value: function strokeText(a0, a1, a2, a3) { this._context.strokeText(a0, a1, a2, a3); } }, { key: "transform", value: function transform(a0, a1, a2, a3, a4, a5) { this._context.transform(a0, a1, a2, a3, a4, a5); } }, { key: "translate", value: function translate(a0, a1) { this._context