(function webpackUniversalModuleDefinition(root, factory) { if(typeof exports === 'object' && typeof module === 'object') module.exports = factory(); else if(typeof define === 'function' && define.amd) define([], factory); else if(typeof exports === 'object') exports["G2_3"] = factory(); else root["G2_3"] = factory(); })(typeof self !== 'undefined' ? self : this, function() { return /******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) { /******/ return installedModules[moduleId].exports; /******/ } /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ i: moduleId, /******/ l: false, /******/ exports: {} /******/ }; /******/ /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ /******/ // Flag the module as loaded /******/ module.l = true; /******/ /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ /******/ /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ /******/ // define getter function for harmony exports /******/ __webpack_require__.d = function(exports, name, getter) { /******/ if(!__webpack_require__.o(exports, name)) { /******/ Object.defineProperty(exports, name, { /******/ configurable: false, /******/ enumerable: true, /******/ get: getter /******/ }); /******/ } /******/ }; /******/ /******/ // getDefaultExport function for compatibility with non-harmony modules /******/ __webpack_require__.n = function(module) { /******/ var getter = module && module.__esModule ? /******/ function getDefault() { return module['default']; } : /******/ function getModuleExports() { return module; }; /******/ __webpack_require__.d(getter, 'a', getter); /******/ return getter; /******/ }; /******/ /******/ // Object.prototype.hasOwnProperty.call /******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); }; /******/ /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ /******/ // Load entry module and return exports /******/ return __webpack_require__(__webpack_require__.s = 562); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview The util method based on the lodash. * @author dxq613@gmail.com * @see https://github.com/lodash/lodash */ var Utils = __webpack_require__(143); var G = __webpack_require__(18); var Util = Utils.mix({}, Utils, { assign: Utils.mix, // simple mix merge: Utils.deepMix, // deep mix cloneDeep: Utils.clone, isFinite: isFinite, isNaN: isNaN, snapEqual: Utils.isNumberEqual, remove: Utils.pull, inArray: Utils.contains, /** * 将用户输入的 padding 转换成 [top, right, bottom, right] 的模式 * @param {Number|Array} padding 输入的padding * @return {Array} 四个padding 值 */ toAllPadding: function toAllPadding(padding) { var top = 0; var left = 0; var right = 0; var bottom = 0; if (Util.isNumber(padding) || Util.isString(padding)) { top = left = right = bottom = padding; } else if (Util.isArray(padding)) { top = padding[0]; right = !Util.isNil(padding[1]) ? padding[1] : padding[0]; bottom = !Util.isNil(padding[2]) ? padding[2] : padding[0]; left = !Util.isNil(padding[3]) ? padding[3] : right; } else if (Util.isObject(padding)) { top = padding.top || 0; right = padding.right || 0; bottom = padding.bottom || 0; left = padding.left || 0; } return [top, right, bottom, left]; }, getClipByRange: function getClipByRange(plotRange) { var tl = plotRange.tl, br = plotRange.br; var clip = new G.Rect({ attrs: { x: tl.x, y: tl.y, width: br.x - tl.x, height: br.y - tl.y } }); return clip; } }); Util.Array = { groupToMap: Utils.groupToMap, group: Utils.group, merge: Utils.merge, values: Utils.valuesOfKey, getRange: Utils.getRange, firstValue: Utils.firstValue, remove: Utils.pull }; module.exports = Util; /***/ }), /* 1 */ /***/ (function(module, exports, __webpack_require__) { var CommonUtil = __webpack_require__(59); var Util = {}; CommonUtil.merge(Util, CommonUtil, { isColorProp: function isColorProp(k) { // 是否是颜色属性 return ['fill', 'stroke', 'fillStyle', 'strokeStyle'].includes(k); }, isGradientColor: function isGradientColor(v) { // 是否是渐变色 return /^[r,R,L,l]{1}[\s]*\(/.test(v); }, mixin: function mixin(c, mixins) { var Param = c.CFG ? 'CFG' : 'ATTRS'; if (c && mixins) { c._mixins = mixins; c[Param] = c[Param] || {}; var temp = {}; Util.each(mixins, function (mixin) { Util.augment(c, mixin); var attrs = mixin[Param]; if (attrs) { Util.merge(temp, attrs); } }); c[Param] = Util.merge(temp, c[Param]); } } }); module.exports = Util; /***/ }), /* 2 */ /***/ (function(module, exports, __webpack_require__) { var CommonUtil = __webpack_require__(169); var Util = {}; CommonUtil.merge(Util, CommonUtil, { mixin: function mixin(c, mixins) { var Param = c.CFG ? 'CFG' : 'ATTRS'; if (c && mixins) { c._mixins = mixins; c[Param] = c[Param] || {}; var temp = {}; Util.each(mixins, function (mixin) { Util.augment(c, mixin); var attrs = mixin[Param]; if (attrs) { Util.merge(temp, attrs); } }); c[Param] = Util.merge(temp, c[Param]); } } }); module.exports = Util; /***/ }), /* 3 */ /***/ (function(module, exports, __webpack_require__) { var isObject = __webpack_require__(22); var isArray = __webpack_require__(5); var each = function each(elements, func) { if (!elements) { return; } var rst = void 0; if (isArray(elements)) { for (var i = 0, len = elements.length; i < len; i++) { rst = func(elements[i], i); if (rst === false) { break; } } } else if (isObject(elements)) { for (var k in elements) { if (elements.hasOwnProperty(k)) { rst = func(elements[k], k); if (rst === false) { break; } } } } }; module.exports = each; /***/ }), /* 4 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview The util method based on the lodash. * @author dxq613@gmail.com */ var G = __webpack_require__(51); var Utils = __webpack_require__(143); var Util = Utils.mix({ assign: Utils.mix, isFinite: isFinite, isNaN: isNaN, Group: G.Group, Event: G.Event }, Utils); module.exports = Util; /***/ }), /* 5 */ /***/ (function(module, exports, __webpack_require__) { var isType = __webpack_require__(14); var isArray = Array.isArray ? Array.isArray : function (value) { return isType(value, 'Array'); }; module.exports = isArray; /***/ }), /* 6 */ /***/ (function(module, exports) { // isFinite, var isNil = function isNil(value) { /** * isNil(null) => true * isNil() => true */ return value === null || value === undefined; }; module.exports = isNil; /***/ }), /* 7 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var isPointInPath = __webpack_require__(227); var Element = __webpack_require__(116); var Inside = __webpack_require__(79); var CLONE_CFGS = ['zIndex', 'capture', 'visible']; var Shape = function Shape(cfg) { Shape.superclass.constructor.call(this, cfg); }; Shape.ATTRS = {}; Util.extend(Shape, Element); var ARRAY_ATTRS = { matrix: 'matrix', path: 'path', points: 'points', lineDash: 'lineDash' }; function _cloneArrayAttr(arr) { var result = []; for (var i = 0; i < arr.length; i++) { if (Util.isArray(arr[i])) { result.push([].concat(arr[i])); } else { result.push(arr[i]); } } return result; } Util.augment(Shape, isPointInPath, { isShape: true, drawInner: function drawInner(context) { var self = this; var attrs = self._attrs; self.createPath(context); var originOpacity = context.globalAlpha; if (self.hasFill()) { var fillOpacity = attrs.fillOpacity; if (!Util.isNil(fillOpacity) && fillOpacity !== 1) { context.globalAlpha = fillOpacity; context.fill(); context.globalAlpha = originOpacity; } else { context.fill(); } } if (self.hasStroke()) { var lineWidth = self._attrs.lineWidth; if (lineWidth > 0) { var strokeOpacity = attrs.strokeOpacity; if (!Util.isNil(strokeOpacity) && strokeOpacity !== 1) { context.globalAlpha = strokeOpacity; } context.stroke(); } } self.afterPath(context); }, afterPath: function afterPath() {}, /** * 击中图形时是否进行包围盒判断 * @return {Boolean} [description] */ isHitBox: function isHitBox() { return true; }, /** * 节点是否能够被击中 * @param {Number} x x坐标 * @param {Number} y y坐标 * @return {Boolean} 是否在图形中 */ isHit: function isHit(x, y) { var self = this; var v = [x, y, 1]; self.invert(v); // canvas if (self.isHitBox()) { var box = self.getBBox(); if (box && !Inside.box(box.minX, box.maxX, box.minY, box.maxY, v[0], v[1])) { return false; } } var clip = self._attrs.clip; if (clip) { clip.invert(v, self.get('canvas')); if (clip.isPointInPath(v[0], v[1])) { return self.isPointInPath(v[0], v[1]); } } else { return self.isPointInPath(v[0], v[1]); } return false; }, /** * @protected * 计算包围盒 * @return {Object} 包围盒 */ calculateBox: function calculateBox() { return null; }, // 获取拾取时线的宽度,需要考虑附加的线的宽度 getHitLineWidth: function getHitLineWidth() { var attrs = this._attrs; // if (!attrs.stroke) { // return 0; // } var lineAppendWidth = attrs.lineAppendWidth || 0; var lineWidth = attrs.lineWidth || 0; return lineWidth + lineAppendWidth; }, // 清除当前的矩阵 clearTotalMatrix: function clearTotalMatrix() { this._cfg.totalMatrix = null; this._cfg.region = null; }, clearBBox: function clearBBox() { this._cfg.box = null; this._cfg.region = null; }, getBBox: function getBBox() { var box = this._cfg.box; // 延迟计算 if (!box) { box = this.calculateBox(); if (box) { box.x = box.minX; box.y = box.minY; box.width = box.maxX - box.minX; box.height = box.maxY - box.minY; } this._cfg.box = box; } return box; }, clone: function clone() { var self = this; var clone = null; var _attrs = self._attrs; var attrs = {}; Util.each(_attrs, function (i, k) { if (ARRAY_ATTRS[k] && Util.isArray(_attrs[k])) { attrs[k] = _cloneArrayAttr(_attrs[k]); } else { attrs[k] = _attrs[k]; } }); clone = new self.constructor({ attrs: attrs }); // 对于一些在 cfg 中的特殊属性做 clone Util.each(CLONE_CFGS, function (cfg) { clone._cfg[cfg] = self._cfg[cfg]; }); return clone; } }); module.exports = Shape; /***/ }), /* 8 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview 全局变量 * @author dxq613 */ var Util = __webpack_require__(0); var Theme = __webpack_require__(167); var Global = { version: '3.5.19', renderer: 'canvas', // trackable: false, trackingInfo: {}, animate: true, widthRatio: { // 宽度所占的分类的比例 column: 1 / 2, // 一般的柱状图占比 1/2 rose: 0.9999999, // 玫瑰图柱状占比 1 multiplePie: 1 / 1.3 // 多层的饼图、环图 }, // 折线图、区域图、path 当只有一个数据时,是否显示成点 showSinglePoint: false, connectNulls: false, scales: {}, registerTheme: function registerTheme(name, theme) { Theme[name] = theme; }, setTheme: function setTheme(theme) { var newTheme = {}; if (Util.isObject(theme)) { newTheme = theme; } else if (Util.indexOf(Object.keys(Theme), theme) !== -1) { newTheme = Theme[theme]; } else { newTheme = Theme.default; } Util.deepMix(Global, newTheme); } }; Global.setTheme('default'); module.exports = Global; /***/ }), /* 9 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var isPointInPath = __webpack_require__(350); var Element = __webpack_require__(172); var Inside = __webpack_require__(93); var Shape = function Shape(cfg) { Shape.superclass.constructor.call(this, cfg); }; Shape.ATTRS = {}; Util.extend(Shape, Element); var ARRAY_ATTRS = { matrix: 'matrix', path: 'path', points: 'points', lineDash: 'lineDash' }; function _cloneArrayAttr(arr) { var result = []; for (var i = 0; i < arr.length; i++) { if (Util.isArray(arr[i])) { result.push([].concat(arr[i])); } else { result.push(arr[i]); } } return result; } Util.augment(Shape, isPointInPath, { isShape: true, drawInner: function drawInner(context) { var self = this; var attrs = self._attrs; self.createPath(context); var originOpacity = context.globalAlpha; if (self.hasFill()) { var fillOpacity = attrs.fillOpacity; if (!Util.isNil(fillOpacity) && fillOpacity !== 1) { context.globalAlpha = fillOpacity; context.fill(); context.globalAlpha = originOpacity; } else { context.fill(); } } if (self.hasStroke()) { var lineWidth = self._attrs.lineWidth; if (lineWidth > 0) { var strokeOpacity = attrs.strokeOpacity; if (!Util.isNil(strokeOpacity) && strokeOpacity !== 1) { context.globalAlpha = strokeOpacity; } context.stroke(); } } self.afterPath(context); }, afterPath: function afterPath() {}, /** * 击中图形时是否进行包围盒判断 * @return {Boolean} [description] */ isHitBox: function isHitBox() { return true; }, /** * 节点是否能够被击中 * @param {Number} x x坐标 * @param {Number} y y坐标 * @return {Boolean} 是否在图形中 */ isHit: function isHit(x, y) { var self = this; var v = [x, y, 1]; self.invert(v); // canvas if (self.isHitBox()) { var box = self.getBBox(); if (box && !Inside.box(box.minX, box.maxX, box.minY, box.maxY, v[0], v[1])) { return false; } } var clip = self._attrs.clip; if (clip) { clip.invert(v, self.get('canvas')); if (clip.isPointInPath(v[0], v[1])) { return self.isPointInPath(v[0], v[1]); } } else { return self.isPointInPath(v[0], v[1]); } return false; }, /** * @protected * 计算包围盒 * @return {Object} 包围盒 */ calculateBox: function calculateBox() { return null; }, // 获取拾取时线的宽度,需要考虑附加的线的宽度 getHitLineWidth: function getHitLineWidth() { var attrs = this._attrs; // if (!attrs.stroke) { // return 0; // } var lineAppendWidth = attrs.lineAppendWidth || 0; var lineWidth = attrs.lineWidth || 0; return lineWidth + lineAppendWidth; }, // 清除当前的矩阵 clearTotalMatrix: function clearTotalMatrix() { this._cfg.totalMatrix = null; this._cfg.region = null; }, clearBBox: function clearBBox() { this._cfg.box = null; this._cfg.region = null; }, getBBox: function getBBox() { var box = this._cfg.box; // 延迟计算 if (!box) { box = this.calculateBox(); if (box) { box.x = box.minX; box.y = box.minY; box.width = box.maxX - box.minX; box.height = box.maxY - box.minY; } this._cfg.box = box; } return box; }, clone: function clone() { var self = this; var clone = null; var _attrs = self._attrs; var attrs = {}; Util.each(_attrs, function (i, k) { if (ARRAY_ATTRS[k] && Util.isArray(_attrs[k])) { attrs[k] = _cloneArrayAttr(_attrs[k]); } else { attrs[k] = _attrs[k]; } }); clone = new self.constructor({ attrs: attrs }); // zIndex也是绘图属性,但是在cfg中,特殊处理 clone._cfg.zIndex = self._cfg.zIndex; return clone; } }); module.exports = Shape; /***/ }), /* 10 */ /***/ (function(module, exports) { function _mix(dist, obj) { for (var key in obj) { if (obj.hasOwnProperty(key) && key !== 'constructor' && obj[key] !== undefined) { dist[key] = obj[key]; } } } var mix = function mix(dist, src1, src2, src3) { if (src1) _mix(dist, src1); if (src2) _mix(dist, src2); if (src3) _mix(dist, src3); return dist; }; module.exports = mix; /***/ }), /* 11 */ /***/ (function(module, exports, __webpack_require__) { /** * 判断是否数字 * @return {Boolean} 是否数字 */ var isType = __webpack_require__(14); var isNumber = function isNumber(value) { return isType(value, 'Number'); }; module.exports = isNumber; /***/ }), /* 12 */ /***/ (function(module, exports, __webpack_require__) { var isType = __webpack_require__(14); var isString = function isString(str) { return isType(str, 'String'); }; module.exports = isString; /***/ }), /* 13 */ /***/ (function(module, exports, __webpack_require__) { /** * 是否为函数 * @param {*} fn 对象 * @return {Boolean} 是否函数 */ var isType = __webpack_require__(14); var isFunction = function isFunction(value) { return isType(value, 'Function'); }; module.exports = isFunction; /***/ }), /* 14 */ /***/ (function(module, exports) { var toString = {}.toString; var isType = function isType(value, type) { return toString.call(value) === '[object ' + type + ']'; }; module.exports = isType; /***/ }), /* 15 */ /***/ (function(module, exports) { var isArrayLike = function isArrayLike(value) { /** * isArrayLike([1, 2, 3]) => true * isArrayLike(document.body.children) => true * isArrayLike('abc') => true * isArrayLike(Function) => false */ return value !== null && typeof value !== 'function' && isFinite(value.length); }; module.exports = isArrayLike; /***/ }), /* 16 */ /***/ (function(module, exports) { module.exports = { FONT_FAMILY: 'BlinkMacSystemFont, "Segoe UI", Roboto,"Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei",SimSun, "sans-serif"' }; /***/ }), /* 17 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var Helper = __webpack_require__(190); var Component = __webpack_require__(36); var KEYWORDS = ['min', 'max', 'median', 'start', 'end']; var Guide = /*#__PURE__*/function (_Component) { _inheritsLoose(Guide, _Component); function Guide() { return _Component.apply(this, arguments) || this; } var _proto = Guide.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Component.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { xScales: null, yScales: null, el: null }); }; _proto.render = function render() {} /** * clear container * @override */ ; _proto.clear = function clear() { var self = this; var el = self.get('el'); el && el.remove(); this.set('el', null); }; _proto.destroy = function destroy() { this.clear(); _Component.prototype.destroy.call(this); } /** * show or hide * @protected * @param {Boolean} visible true means show, false means hide */ ; _proto.changeVisible = function changeVisible(visible) { var self = this; self.set('visible', visible); var el = self.get('el'); if (!el) return; if (el.set) { el.set('visible', visible); } else { el.style.display = visible ? '' : 'none'; } } /** * calculate the canvas coordinate value * @protected * @param {Coordinate} coord the instance of Coordinate class * @param {Object | Array | Function} position the value need to convert * @return {Object} return the result */ ; _proto.parsePoint = function parsePoint(coord, position) { var self = this; var xScales = self.get('xScales'); var yScales = self.get('yScales'); if (Util.isFunction(position)) { position = position(xScales, yScales); } var x; var y; // 如果数据格式是 ['50%', '50%'] 的格式 if (Util.isArray(position) && Util.isString(position[0]) && position[0].indexOf('%') !== -1) { return this._parsePercentPoint(coord, position); } if (Util.isArray(position)) { // Array,suuport for mixing of keyword, percent and value x = self._getNormalizedValue(position[0], Helper.getFirstScale(xScales)); y = self._getNormalizedValue(position[1], Helper.getFirstScale(yScales)); } else { for (var field in position) { var value = position[field]; if (xScales[field]) { x = self._getNormalizedValue(value, xScales[field]); } if (yScales[field]) { y = self._getNormalizedValue(value, yScales[field], 'y'); } } } if (!Util.isNil(x) && !Util.isNil(y) && !isNaN(x) && !isNaN(y)) { return coord.convert({ x: x, y: y }); } return null; } /** * Normalized the value * @param {String | Number} val param * @param {Scale} scale the instance of Scale * @return {Number} return the normalized value */ ; _proto._getNormalizedValue = function _getNormalizedValue(val, scale) { var result; if (Util.indexOf(KEYWORDS, val) !== -1) { // keyword var scaleValue; if (val === 'start') { // the start of coordinate result = 0; } else if (val === 'end') { result = 1; } else if (val === 'median') { scaleValue = scale.isCategory ? (scale.values.length - 1) / 2 : (scale.min + scale.max) / 2; result = scale.scale(scaleValue); } else { if (scale.isCategory) { scaleValue = val === 'min' ? 0 : scale.values.length - 1; } else { scaleValue = scale[val]; } result = scale.scale(scaleValue); } } else { // 数值 result = scale.scale(val); } return result; }; _proto._parsePercentPoint = function _parsePercentPoint(coord, position) { var xPercent = parseFloat(position[0]) / 100; var yPercent = parseFloat(position[1]) / 100; var start = coord.start, end = coord.end; var topLeft = { x: Math.min(start.x, end.x), y: Math.min(start.y, end.y) }; var x = coord.width * xPercent + topLeft.x; var y = coord.height * yPercent + topLeft.y; return { x: x, y: y }; }; return Guide; }(Component); module.exports = Guide; /***/ }), /* 18 */ /***/ (function(module, exports, __webpack_require__) { var G = __webpack_require__(112); module.exports = G; /***/ }), /* 19 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__color_js__ = __webpack_require__(85); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return __WEBPACK_IMPORTED_MODULE_0__color_js__["e"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "f", function() { return __WEBPACK_IMPORTED_MODULE_0__color_js__["g"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return __WEBPACK_IMPORTED_MODULE_0__color_js__["f"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__lab_js__ = __webpack_require__(241); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "e", function() { return __WEBPACK_IMPORTED_MODULE_1__lab_js__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return __WEBPACK_IMPORTED_MODULE_1__lab_js__["b"]; }); /* unused harmony reexport lch */ /* unused harmony reexport gray */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__cubehelix_js__ = __webpack_require__(242); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return __WEBPACK_IMPORTED_MODULE_2__cubehelix_js__["a"]; }); /***/ }), /* 20 */ /***/ (function(module, exports, __webpack_require__) { var mix = __webpack_require__(10); var each = __webpack_require__(3); var isObject = __webpack_require__(22); var isNil = __webpack_require__(6); var Scale = /*#__PURE__*/function () { var _proto = Scale.prototype; _proto._initDefaultCfg = function _initDefaultCfg() { this.type = 'base'; /** * 格式化函数,输出文本或者tick时的格式化函数 * @type {Function} */ this.formatter = null; /** * 输出的值域 * @type {Array} */ this.range = [0, 1]; /** * 度量的标记 * @type {Array} */ this.ticks = null; /** * 参与度量计算的值,可选项 * @type {Array} */ this.values = []; }; function Scale(cfg) { this._initDefaultCfg(); mix(this, cfg); this.init(); } /** * 度量初始化 * @protected */ _proto.init = function init() {} /** * 获取该度量的ticks,返回的是多个对象, * - text: tick 的文本 * - value: 对应的度量转换后的值 * * [ * {text: 0,value:0} * {text: 1,value:0.2} * {text: 2,value:0.4} * {text: 3,value:0.6} * {text: 4,value:0.8} * {text: 5,value:1} * ] * * @param {Number} count 输出tick的个数的近似值,默认是 10 * @return {Array} 返回 ticks 数组 */ ; _proto.getTicks = function getTicks() { var self = this; var ticks = self.ticks; var rst = []; each(ticks, function (tick) { var obj; if (isObject(tick)) { obj = tick; } else { obj = { text: self.getText(tick), tickValue: tick, value: self.scale(tick) }; } rst.push(obj); }); return rst; } /** * 获取格式化后的文本 * @param {*} value 输入的数据 * @param {*} key 字段的 key * @return {String} 格式化的文本 */ ; _proto.getText = function getText(value, key) { var formatter = this.formatter; value = formatter ? formatter(value, key) : value; if (isNil(value) || !value.toString) { value = ''; } return value.toString(); } /** * 输出的值域最小值 * @protected * @return {Number} 返回最小的值 */ ; _proto.rangeMin = function rangeMin() { return this.range[0]; } /** * 输出的值域最大值 * @protected * @return {Number} 返回最大的值 */ ; _proto.rangeMax = function rangeMax() { var range = this.range; return range[range.length - 1]; } /** * 度量转换后的结果,翻转回输入域 * @param {Number} value 需要翻转的数值 * @return {*} 度量的输入值 */ ; _proto.invert = function invert(value) { return value; } /** * 将传入的值从非数值转换成数值格式,如分类字符串、时间字符串等 * @param {*} value 传入的值 * @return {Number} 转换的值 */ ; _proto.translate = function translate(value) { return value; } /** * 进行度量转换 * @param {*} value 输入值 * @return {Number} 输出值,在设定的输出值域之间,默认[0,1] */ ; _proto.scale = function scale(value) { return value; } /** * 克隆一个新的scale,拥有跟当前scale相同的输入域、输出域等 * @return {Scale} 克隆的度量 */ ; _proto.clone = function clone() { var self = this; var constr = self.constructor; var cfg = {}; each(self, function (v, k) { cfg[k] = self[k]; }); return new constr(cfg); } /** * 更改度量的属性信息 * @param {Object} info 属性信息 * @chainable * @return {Scale} 返回自身的引用 */ ; _proto.change = function change(info) { this.ticks = null; mix(this, info); this.init(); return this; }; return Scale; }(); module.exports = Scale; /***/ }), /* 21 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview 工厂类,管理各种类型的 shape * @author dxq613@gmail.com */ var Util = __webpack_require__(0); var PathUtil = __webpack_require__(25); var GPath = Util.PathUtil; var Shape = {}; var ShapeBase = { _coord: null, /** * 绘制图形 * @param {Object} cfg 配置项 * @param {Object} container 容器 * @return {Object} shape 创建的 shape */ draw: function draw(cfg, container) { if (this.drawShape) { return this.drawShape(cfg, container); } return null; }, /** * 获取绘制图形需要的点, 可以不定义,则使用默认的 getPoints(cfg) { if (this.getShapePoints) { return this.getShapePoints(cfg); } return null; },*/ /** * 设置坐标系 * @param {Coord} coord 坐标系 */ setCoord: function setCoord(coord) { this._coord = coord; }, /** * 0~1 path 转 画布 path * @param {path} path 路径 * @param {Boolean} islineToArc 是否转换成圆弧 * @return {path} path 转换到画布坐标的path */ parsePath: function parsePath(path, islineToArc) { var coord = this._coord; path = GPath.parsePathString(path); if (coord.isPolar && islineToArc !== false) { path = PathUtil.convertPolarPath(coord, path); } else { path = PathUtil.convertNormalPath(coord, path); } return path; }, /** * 0~1 point 转 画布 point * @param {point} point 节点 * @return {point} point 转换后的点 */ parsePoint: function parsePoint(point) { var coord = this._coord; return coord.convertPoint(point); }, /** * 0~1 points 转 画布 points * @param {points} points 节点集合 * @return {points} points 转换后的多个节点 */ parsePoints: function parsePoints(points) { var coord = this._coord; var rst = []; Util.each(points, function (point) { rst.push(coord.convertPoint(point)); }); return rst; } }; var ShapeFactoryBase = { defaultShapeType: null, setCoord: function setCoord(coord) { this._coord = coord; }, getShape: function getShape(type) { var self = this; if (Util.isArray(type)) { type = type[0]; } var shape = self[type] || self[self.defaultShapeType]; shape._coord = self._coord; return shape; }, getShapePoints: function getShapePoints(type, cfg) { var shape = this.getShape(type); var fn = shape.getPoints || shape.getShapePoints || this.getDefaultPoints; var points = fn(cfg); return points; }, getDefaultPoints: function getDefaultPoints() { return []; }, getMarkerCfg: function getMarkerCfg(type, cfg) { var shape = this.getShape(type); if (!shape.getMarkerCfg) { var defaultShapeType = this.defaultShapeType; shape = this.getShape(defaultShapeType); } return shape.getMarkerCfg(cfg); }, getSelectedCfg: function getSelectedCfg() { return {}; }, drawShape: function drawShape(type, cfg, container) { var shape = this.getShape(type); var gShape = shape.draw(cfg, container); if (gShape) { gShape.setSilent('origin', cfg.origin); gShape._id = cfg.yIndex ? cfg._id + cfg.yIndex : cfg._id; gShape.name = this.name; } return gShape; } }; // 注册 Geometry 获取图形的入口 Shape.registerFactory = function (factoryName, cfg) { var className = Util.upperFirst(factoryName); var geomObj = Util.assign({}, ShapeFactoryBase, cfg); Shape[className] = geomObj; geomObj.name = factoryName; return geomObj; }; // 注册图形 Shape.registerShape = function (factoryName, shapeType, cfg) { var className = Util.upperFirst(factoryName); var factory = Shape[className]; var shapeObj = Util.assign({}, ShapeBase, cfg); factory[shapeType] = shapeObj; return shapeObj; }; // 获得Geom 对应的 shapeFactory Shape.getShapeFactory = function (factoryName) { var self = this; factoryName = factoryName || 'point'; var className = Util.upperFirst(factoryName); return self[className]; }; module.exports = Shape; /***/ }), /* 22 */ /***/ (function(module, exports) { var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var isObject = function isObject(value) { /** * isObject({}) => true * isObject([1, 2, 3]) => true * isObject(Function) => true * isObject(null) => false */ var type = typeof value === 'undefined' ? 'undefined' : _typeof(value); return value !== null && type === 'object' || type === 'function'; }; module.exports = isObject; /***/ }), /* 23 */ /***/ (function(module, exports, __webpack_require__) { function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @fileOverview 所有 Geometry 的基类 * @author dxq613@gmail.com */ var Attr = __webpack_require__(104); var Adjust = __webpack_require__(335); var Base = __webpack_require__(164); var Util = __webpack_require__(0); var Global = __webpack_require__(8); var Labels = __webpack_require__(343); var Shape = __webpack_require__(21); var TooltipMixin = __webpack_require__(395); var ActiveMixin = __webpack_require__(396); var SelectMixin = __webpack_require__(397); var parseFields = __webpack_require__(398); var GROUP_ATTRS = ['color', 'shape', 'size']; var FIELD_ORIGIN = '_origin'; // 转换成对象的数组 [{type: 'adjust'}] function parseAdjusts(adjusts) { // 如果是字符串或者对象转换成数组 if (Util.isString(adjusts) || Util.isPlainObject(adjusts)) { adjusts = [adjusts]; } Util.each(adjusts, function (adjust, index) { if (!Util.isObject(adjust)) { adjusts[index] = { type: adjust }; } }); return adjusts; } /** * 几何标记 * @class Geom */ var GeomBase = /*#__PURE__*/function (_Base) { _inheritsLoose(GeomBase, _Base); var _proto = GeomBase.prototype; /** * 获取默认的配置属性 * @protected * @return {Object} 默认属性 */ _proto.getDefaultCfg = function getDefaultCfg() { return { /** * 标记 _id 用于区分执行动画 * @type {String} */ _id: null, /** * 类型 * @type {String} */ type: 'base', /** * 坐标系 * @type {Object} */ coord: null, /** * 属性映射集 * @protected * @type {Object} */ attrs: {}, /** * 所属的View * @type {View} */ view: null, /** * 几何标记显示的数据 * @type {Array} */ data: [], /** * 相关的度量 * @type {Object} */ scales: {}, /** * 绘图容器 * @type {Object} */ container: null, /** * 文本容器 * @type {Object} */ labelContainer: null, /** * 图形容器 * @type {Object} */ shapeContainer: null, /** * 几何标记的一些配置项,用于延迟生成图表 * @type {Object} */ attrOptions: {}, // 样式配置项 styleOptions: null, // 选中时的配置项 selectedOptions: null, // active 时的配置项 activedOptions: null, /** * 某些类存在默认的adjust,不能更改 adjust * @type {Boolean} */ hasDefaultAdjust: false, // 数据调整类型 adjusts: null, /** * 使用形状的类型 * @protected * @type {String} */ shapeType: null, /** * 是否生成多个点来绘制图形 * @protected * @type {Boolean} */ generatePoints: false, /** * 数据是否进行排序 * @type {Boolean} */ sortable: false, labelCfg: null, /** * 是否共享 tooltip * @type {Boolean} */ shareTooltip: true, tooltipCfg: null, /** * 是否执行动画,默认执行 * @type {Boolean} */ animate: true, /** * 动画配置 * @type {[type]} */ animateCfg: null, visible: true }; }; function GeomBase(cfg) { var _this; _this = _Base.call(this, cfg) || this; _this.viewTheme = _this.get('viewTheme'); Util.assign(_assertThisInitialized(_this), TooltipMixin, ActiveMixin, SelectMixin); if (_this.get('container')) { _this._initContainer(); } _this._initOptions(); return _this; } // 初始化时对配置项的格式化 _proto._initOptions = function _initOptions() { var adjusts = this.get('adjusts'); if (adjusts) { adjusts = parseAdjusts(adjusts); this.set('adjusts', adjusts); } }; _proto._createScale = function _createScale(field, data) { var scales = this.get('scales'); var scale = scales[field]; if (!scale) { scale = this.get('view').createScale(field, data); scales[field] = scale; } return scale; }; _proto._setAttrOptions = function _setAttrOptions(attrName, attrCfg) { var options = this.get('attrOptions'); options[attrName] = attrCfg; }; _proto._createAttrOption = function _createAttrOption(attrName, field, cfg, defaultValues) { var attrCfg = {}; attrCfg.field = field; if (cfg) { if (Util.isFunction(cfg)) { attrCfg.callback = cfg; } else { attrCfg.values = cfg; } } else if (attrName !== 'color') { attrCfg.values = defaultValues; } this._setAttrOptions(attrName, attrCfg); } /** * 位置属性映射 * @chainable * @param {String} field 字段名 * @return {Geom} geom 当前几何标记 */ ; _proto.position = function position(field) { this._setAttrOptions('position', { field: field }); return this; } /** * 颜色属性映射 * @chainable * @param {String} field 字段名 * @param {Array|Function} values 颜色的数组或者回调函数 * @return {Geom} geom 当前几何标记 */ ; _proto.color = function color(field, values) { var viewTheme = this.viewTheme || Global; this._createAttrOption('color', field, values, viewTheme.colors); return this; } /** * 大小属性映射 * @chainable * @param {String} field 字段名 * @param {Array|Function} values 大小的数组或者回调函数 * @return {Geom} geom 当前几何标记 */ ; _proto.size = function size(field, values) { var viewTheme = this.viewTheme || Global; this._createAttrOption('size', field, values, viewTheme.sizes); return this; } /** * 形状属性映射 * @chainable * @param {String} field 字段名 * @param {Array|Function} values 大小的数组或者回调函数 * @return {Geom} geom 当前几何标记 */ ; _proto.shape = function shape(field, values) { var viewTheme = this.viewTheme || Global; var type = this.get('type'); var shapes = viewTheme.shapes[type] || []; this._createAttrOption('shape', field, values, shapes); return this; } /** * 透明度属性映射 * @chainable * @param {String} field 字段名 * @param {Array|Function} values 透明度的数组或者回调函数 * @return {Geom} geom 当前几何标记 */ ; _proto.opacity = function opacity(field, values) { var viewTheme = this.viewTheme || Global; this._createAttrOption('opacity', field, values, viewTheme.opacities); return this; }; _proto.style = function style(field, cfg) { var styleOptions = this.get('styleOptions'); if (!styleOptions) { styleOptions = {}; this.set('styleOptions', styleOptions); } if (Util.isObject(field)) { cfg = field; field = null; } var fields; if (field) { fields = parseFields(field); } styleOptions.fields = fields; styleOptions.style = cfg; return this; }; _proto.label = function label(field, callback, cfg) { var self = this; var labelCfg = self.get('labelCfg'); // const scales = Util.map(self.get('labelCfg').fields, field => self._createScale(field)); if (!labelCfg) { labelCfg = {}; self.set('labelCfg', labelCfg); } var fields; if (field) { fields = parseFields(field); } labelCfg.fields = fields; // 如果存在回调函数 if (Util.isFunction(callback)) { if (!cfg) { cfg = {}; } labelCfg.callback = callback; } else if (Util.isObject(callback)) { // 如果没有设置回调函数 cfg = callback; } labelCfg.globalCfg = cfg; return this; }; _proto.tooltip = function tooltip(field, cfg) { var tooltipCfg = this.get('tooltipCfg'); if (!tooltipCfg) { tooltipCfg = {}; } if (field === false) { // geom 关闭 tooltip this.set('tooltipCfg', false); } else { var tooltipFields; if (field) { tooltipFields = parseFields(field); } tooltipCfg.fields = tooltipFields; tooltipCfg.cfg = cfg; } this.set('tooltipCfg', tooltipCfg); return this; }; _proto.animate = function animate(cfg) { this.set('animateCfg', cfg); return this; } /** * 是否允许使用默认的图形激活交互 * @param {Boolean} enable 是否允许激活开关 * @param {Object} cfg 激活的配置项 * @return {Geom} 返回 geom 自身 */ ; _proto.active = function active(enable, cfg) { if (enable === false) { this.set('allowActive', false); } else if (Util.isObject(enable)) { this.set('allowActive', true); this.set('activedOptions', enable); } else { this.set('allowActive', true); this.set('activedOptions', cfg); } return this; } /** * 对 geometry 进行数据调整 * @chainable * @param {String|Array|null} adjusts 数据调整的类型 * @return {Object} geometry 对象 */ ; _proto.adjust = function adjust(adjusts) { if (!this.get('hasDefaultAdjust')) { if (adjusts) { adjusts = parseAdjusts(adjusts); } this.set('adjusts', adjusts); } return this; } /** * 设置图形的选中模式 * @param {Boolean|Object} enable 布尔类型用于模式开关,对象类型用于配置 * @param {Object} cfg 选中配置项 * @return {Geom} 返回 geom 自身 */ ; _proto.select = function select(enable, cfg) { if (enable === false) { this.set('allowSelect', false); } else if (Util.isObject(enable)) { this.set('allowSelect', true); this.set('selectedOptions', enable); } else { this.set('allowSelect', true); this.set('selectedOptions', cfg); } return this; }; _proto.hasAdjust = function hasAdjust(adjustType) { var self = this; var adjusts = self.get('adjusts'); if (!adjustType) { return false; } var rst = false; Util.each(adjusts, function (adjust) { if (adjust.type === adjustType) { rst = true; return false; } }); return rst; }; _proto.hasStack = function hasStack() { var isStacked = this.get('isStacked'); if (Util.isNil(isStacked)) { isStacked = this.hasAdjust('stack'); this.set('isStacked', isStacked); } return isStacked; }; _proto.isInCircle = function isInCircle() { var coord = this.get('coord'); return coord && coord.isPolar; }; _proto._initContainer = function _initContainer() { var self = this; var shapeContainer = self.get('shapeContainer'); if (!shapeContainer) { var container = self.get('container'); var view = self.get('view'); var viewId = view && view.get('_id'); shapeContainer = container.addGroup({ viewId: viewId, visible: self.get('visible') }); self.set('shapeContainer', shapeContainer); } }; _proto.init = function init() { var self = this; self._initContainer(); self._initAttrs(); if (self.get('tooltipCfg') && self.get('tooltipCfg').fields) { var tooltipFields = self.get('tooltipCfg').fields; Util.each(tooltipFields, function (field) { self._createScale(field); }); } var dataArray = self._processData(); if (self.get('adjusts')) { self._adjust(dataArray); } self.set('dataArray', dataArray); } // step 1: init attrs ; _proto._initAttrs = function _initAttrs() { var self = this; var attrs = self.get('attrs'); var attrOptions = self.get('attrOptions'); var coord = self.get('coord'); var viewTheme = self.viewTheme || Global; var isPie = false; for (var type in attrOptions) { if (attrOptions.hasOwnProperty(type)) { var option = attrOptions[type]; var className = Util.upperFirst(type); var fields = parseFields(option.field); if (type === 'position') { option.coord = coord; // 饼图坐标系下,填充一维 if (fields.length === 1 && coord.type === 'theta') { fields.unshift('1'); isPie = true; } } var scales = []; for (var i = 0; i < fields.length; i++) { var field = fields[i]; var scale = self._createScale(field); if (type === 'color' && Util.isNil(option.values)) { // 设置 color 的默认色值 if (scale.values.length <= 8) { option.values = isPie ? viewTheme.colors_pie : viewTheme.colors; } else if (scale.values.length <= 16) { option.values = isPie ? viewTheme.colors_pie_16 : viewTheme.colors_16; } else { option.values = viewTheme.colors_24; } if (Util.isNil(option.values)) { option.values = viewTheme.colors; // 防止主题没有声明诸如 colors_pie 的属性 } } scales.push(scale); } // 饼图需要填充满整个空间 if (coord.type === 'theta' && type === 'position' && scales.length > 1) { var yScale = scales[1]; var min = 0; var max = Math.max.apply(null, yScale.values); if (!isFinite(max)) { max = 1; } yScale.change({ nice: false, min: min, max: max }); } option.scales = scales; var attr = new Attr[className](option); attrs[type] = attr; } } } // step 2: 处理数据 ; _proto._processData = function _processData() { var self = this; var data = this.get('data'); var dataArray = []; var groupedArray = this._groupData(data); for (var i = 0; i < groupedArray.length; i++) { var subData = groupedArray[i]; var tempData = self._saveOrigin(subData); dataArray.push(self._numberic(tempData)); } return dataArray; } // step 2.1 数据分组 ; _proto._groupData = function _groupData(data) { var groupScales = this._getGroupScales(); var fields = groupScales.map(function (scale) { return scale.field; }); return Util.Array.group(data, fields); } // step 2.2 数据调整前保存原始数据 ; _proto._saveOrigin = function _saveOrigin(data) { var rst = []; for (var i = 0; i < data.length; i++) { var origin = data[i]; var obj = {}; for (var k in origin) { obj[k] = origin[k]; } // const obj = Util.mix({}, origin); obj[FIELD_ORIGIN] = origin; rst.push(obj); } return rst; } // step 2.3 将分类数据翻译成数据, 仅对位置相关的度量进行数字化处理 ; _proto._numberic = function _numberic(data) { var positionAttr = this.getAttr('position'); var scales = positionAttr.scales; var result = []; for (var j = 0; j < data.length; j++) { var obj = data[j]; var isValidate = true; for (var i = 0; i < Math.min(2, scales.length); i++) { var scale = scales[i]; if (scale.isCategory) { var field = scale.field; obj[field] = scale.translate(obj[field]); if (Number.isNaN(obj[field])) { // 当分类为 NaN 时,说明该条数据不在定义域内,需要过滤掉 isValidate = false; } } } if (isValidate) { result.push(obj); } } return result; }; _proto._getGroupScales = function _getGroupScales() { var self = this; var scales = self.get('groupScales'); if (!scales) { scales = []; var attrs = self.get('attrs'); Util.each(attrs, function (attr) { if (GROUP_ATTRS.includes(attr.type)) { var attrScales = attr.scales; Util.each(attrScales, function (scale) { if (scale.isCategory && Util.indexOf(scales, scale) === -1) { scales.push(scale); } }); } }); self.set('groupScales', scales); } return scales; }; _proto._updateStackRange = function _updateStackRange(field, scale, dataArray) { var mergeArray = Util.Array.merge(dataArray); var min = scale.min; var max = scale.max; for (var i = 0; i < mergeArray.length; i++) { var obj = mergeArray[i]; // 过滤掉非法数据 if (!Util.isArray(obj[field])) { continue; } var tmpMin = Math.min.apply(null, obj[field]); var tmpMax = Math.max.apply(null, obj[field]); if (tmpMin < min) { min = tmpMin; } if (tmpMax > max) { max = tmpMax; } } if (min < scale.min || max > scale.max) { scale.change({ min: min, max: max }); } } // step 2.2 调整数据 ; _proto._adjust = function _adjust(dataArray) { // 当数据为空的时候,就不需要对数据进行调整了 if (!dataArray || !dataArray.length) { return; } var self = this; var adjusts = self.get('adjusts'); var viewTheme = this.viewTheme || Global; var yScale = self.getYScale(); var xScale = self.getXScale(); var xField = xScale.field; var yField = yScale ? yScale.field : null; Util.each(adjusts, function (adjust) { var adjustCfg = Util.mix({ xField: xField, yField: yField }, adjust); var adjustType = Util.upperFirst(adjust.type); if (adjustType === 'Dodge') { var adjustNames = []; if (xScale.isCategory || xScale.isIdentity) { adjustNames.push('x'); } else if (!yScale) { adjustNames.push('y'); } else { throw new Error('dodge is not support linear attribute, please use category attribute!'); } adjustCfg.adjustNames = adjustNames; adjustCfg.dodgeRatio = adjustCfg.dodgeRatio || viewTheme.widthRatio.column; /* if (self.isInCircle()) { adjustCfg.dodgeRatio = 1; adjustCfg.marginRatio = 0; }*/ } else if (adjustType === 'Stack') { var coord = self.get('coord'); if (!yScale) { // 一维的情况下获取高度和默认size adjustCfg.height = coord.getHeight(); var size = self.getDefaultValue('size') || 3; adjustCfg.size = size; } // 不进行 transpose 时,用户又没有设置这个参数时,默认从上向下 if (!coord.isTransposed && Util.isNil(adjustCfg.reverseOrder)) { adjustCfg.reverseOrder = true; } } var adjustElement = new Adjust[adjustType](adjustCfg); adjustElement.processAdjust(dataArray); if (adjustType === 'Stack' && yScale) { self._updateStackRange(yField, yScale, dataArray); } }); } /** * @internal 设置coord,通常外部容器变化时,coord 会发生变化 * @param {Object} coord 坐标系 */ ; _proto.setCoord = function setCoord(coord) { this.set('coord', coord); var position = this.getAttr('position'); var shapeContainer = this.get('shapeContainer'); shapeContainer.setMatrix(coord.matrix); if (position) { position.coord = coord; } } // step 3 绘制 ; _proto.paint = function paint() { var self = this; var dataArray = self.get('dataArray'); var mappedArray = []; var shapeFactory = self.getShapeFactory(); shapeFactory.setCoord(self.get('coord')); self.set('shapeFactory', shapeFactory); var shapeContainer = self.get('shapeContainer'); self._beforeMapping(dataArray); for (var i = 0; i < dataArray.length; i++) { var data = dataArray[i]; var index = i; data = self._mapping(data); mappedArray.push(data); self.draw(data, shapeContainer, shapeFactory, index); } if (self.get('labelCfg')) { self._addLabels(Util.union.apply(null, mappedArray), shapeContainer.get('children')); } if (!self.get('sortable')) { self._sort(mappedArray); // 便于数据的查找,需要对数据进行排序,用于 geom.findPoint() } else { self.set('dataArray', mappedArray); } }; _proto._sort = function _sort(mappedArray) { var self = this; var xScale = self.getXScale(); var xField = xScale.field; Util.each(mappedArray, function (itemArr) { itemArr.sort(function (obj1, obj2) { return xScale.translate(obj1[FIELD_ORIGIN][xField]) - xScale.translate(obj2[FIELD_ORIGIN][xField]); }); }); self.set('dataArray', mappedArray); } // step 3.1 before mapping ; _proto._beforeMapping = function _beforeMapping(dataArray) { var self = this; if (self.get('sortable')) { var xScale = self.getXScale(); var field = xScale.field; Util.each(dataArray, function (data) { data.sort(function (v1, v2) { return xScale.translate(v1[field]) - xScale.translate(v2[field]); }); }); } if (self.get('generatePoints')) { Util.each(dataArray, function (data) { self._generatePoints(data); }); Util.each(dataArray, function (data, index) { var nextData = dataArray[index + 1]; if (nextData) { data[0].nextPoints = nextData[0].points; } }); } } // step 3.2 add labels ; _proto._addLabels = function _addLabels(points, shapes) { var self = this; var type = self.get('type'); var viewTheme = self.get('viewTheme') || Global; var coord = self.get('coord'); var C = Labels.getLabelsClass(coord.type, type); var container = self.get('container'); var scales = Util.map(self.get('labelCfg').fields, function (field) { return self._createScale(field); }); var labelContainer = container.addGroup(C, { _id: this.get('_id'), labelCfg: Util.mix({ scales: scales }, self.get('labelCfg')), coord: coord, geom: self, geomType: type, yScale: self.getYScale(), viewTheme: viewTheme, visible: self.get('visible') }); labelContainer.showLabels(points, shapes); self.set('labelContainer', labelContainer); } /** * @protected * 获取图形的工厂类 * @return {Object} 工厂类对象 */ ; _proto.getShapeFactory = function getShapeFactory() { var shapeFactory = this.get('shapeFactory'); if (!shapeFactory) { var shapeType = this.get('shapeType'); shapeFactory = Shape.getShapeFactory(shapeType); this.set('shapeFactory', shapeFactory); } return shapeFactory; } // step 3.2 generate points ; _proto._generatePoints = function _generatePoints(data) { var self = this; var shapeFactory = self.getShapeFactory(); var shapeAttr = self.getAttr('shape'); for (var i = 0; i < data.length; i++) { var obj = data[i]; var cfg = self.createShapePointsCfg(obj); var shape = shapeAttr ? self._getAttrValues(shapeAttr, obj) : null; var points = shapeFactory.getShapePoints(shape, cfg); obj.points = points; } } /** * 获取图形对应点的配置项 * @protected * @param {Object} obj 数据对象 * @return {Object} cfg 获取图形对应点的配置项 */ ; _proto.createShapePointsCfg = function createShapePointsCfg(obj) { var xScale = this.getXScale(); var yScale = this.getYScale(); var x = this._normalizeValues(obj[xScale.field], xScale); var y; // 存在没有 y 的情况 if (yScale) { y = this._normalizeValues(obj[yScale.field], yScale); } else { y = obj.y ? obj.y : 0.1; } return { x: x, y: y, y0: yScale ? yScale.scale(this.getYMinValue()) : undefined }; } /** * @protected * 如果y轴的最小值小于0则返回0,否则返回最小值 * @return {Number} y轴上的最小值 */ ; _proto.getYMinValue = function getYMinValue() { var yScale = this.getYScale(); var min = yScale.min, max = yScale.max; var value; if (min >= 0) { value = min; } else if (max <= 0) { // 当值全位于负区间时,需要保证 ymin 在区域内,不可为 0 value = max; } else { value = 0; } return value; } // 将数据归一化 ; _proto._normalizeValues = function _normalizeValues(values, scale) { var rst = []; if (Util.isArray(values)) { for (var i = 0; i < values.length; i++) { var v = values[i]; rst.push(scale.scale(v)); } } else { rst = scale.scale(values); } return rst; } // step 3.2 mapping ; _proto._mapping = function _mapping(data) { var self = this; var attrs = self.get('attrs'); var mappedData = []; for (var i = 0; i < data.length; i++) { var record = data[i]; var newRecord = {}; newRecord[FIELD_ORIGIN] = record[FIELD_ORIGIN]; newRecord.points = record.points; newRecord.nextPoints = record.nextPoints; for (var k in attrs) { if (attrs.hasOwnProperty(k)) { var attr = attrs[k]; var names = attr.names; var values = self._getAttrValues(attr, record); if (names.length > 1) { // position 之类的生成多个字段的属性 for (var j = 0; j < values.length; j++) { var val = values[j]; var name = names[j]; newRecord[name] = Util.isArray(val) && val.length === 1 ? val[0] : val; // 只有一个值时返回第一个属性值 } } else { newRecord[names[0]] = values.length === 1 ? values[0] : values; } } } mappedData.push(newRecord); } return mappedData; } // 获取属性映射的值 ; _proto._getAttrValues = function _getAttrValues(attr, record) { var scales = attr.scales; var params = []; for (var i = 0; i < scales.length; i++) { var scale = scales[i]; var field = scale.field; if (scale.type === 'identity') { params.push(scale.value); } else { params.push(record[field]); } } var values = attr.mapping.apply(attr, params); return values; }; _proto.getAttrValue = function getAttrValue(attrName, record) { var attr = this.getAttr(attrName); var rst = null; if (attr) { var values = this._getAttrValues(attr, record); rst = values[0]; } return rst; }; _proto.getDefaultValue = function getDefaultValue(attrName) { var value = this.get(attrName); var attr = this.getAttr(attrName); if (attr) { var scale = attr.getScale(attrName); if (scale.type === 'identity') { value = scale.value; } } return value; } /** * step 3.3 draw * @protected * @param {Array} data 绘制图形 * @param {Object} container 绘图容器 * @param {Object} shapeFactory 绘制图形的工厂类 * @param {Number} index 每个 shape 的索引值 */ ; _proto.draw = function draw(data, container, shapeFactory, index) { var self = this; for (var i = 0; i < data.length; i++) { var obj = data[i]; self.drawPoint(obj, container, shapeFactory, index + i); } }; _proto.getCallbackCfg = function getCallbackCfg(fields, cfg, origin) { if (!fields) { return cfg; } var tmpCfg = {}; var params = fields.map(function (field) { return origin[field]; }); Util.each(cfg, function (v, k) { if (Util.isFunction(v)) { tmpCfg[k] = v.apply(null, params); } else { tmpCfg[k] = v; } }); return tmpCfg; }; _proto._getShapeId = function _getShapeId(dataObj) { var id = this.get('_id'); var keyFields = this.get('keyFields'); if (keyFields && keyFields.length > 0) { Util.each(keyFields, function (key) { id += '-' + dataObj[key]; }); } else { var type = this.get('type'); var xScale = this.getXScale(); var yScale = this.getYScale(); var xField = xScale.field || 'x'; var yField = yScale.field || 'y'; var yVal = dataObj[yField]; var xVal; if (xScale.isIdentity) { xVal = xScale.value; } else { xVal = dataObj[xField]; } if (type === 'interval' || type === 'schema') { id += '-' + xVal; } else if (type === 'line' || type === 'area' || type === 'path') { id += '-' + type; } else { id += '-' + xVal + '-' + yVal; } var groupScales = this._getGroupScales(); if (!Util.isEmpty(groupScales)) { Util.each(groupScales, function (groupScale) { var field = groupScale.field; if (groupScale.type !== 'identity') { id += '-' + dataObj[field]; } }); } } return id; }; _proto.getDrawCfg = function getDrawCfg(obj) { var self = this; var cfg = { origin: obj, x: obj.x, y: obj.y, color: obj.color, size: obj.size, shape: obj.shape, isInCircle: self.isInCircle(), opacity: obj.opacity }; var styleOptions = self.get('styleOptions'); if (styleOptions && styleOptions.style) { cfg.style = self.getCallbackCfg(styleOptions.fields, styleOptions.style, obj[FIELD_ORIGIN]); } if (self.get('generatePoints')) { cfg.points = obj.points; cfg.nextPoints = obj.nextPoints; } if (self.get('animate')) { // _id 字段仅用于动画 cfg._id = self._getShapeId(obj[FIELD_ORIGIN]); } return cfg; }; _proto.appendShapeInfo = function appendShapeInfo(shape, index) { if (shape) { shape.setSilent('index', index); shape.setSilent('coord', this.get('coord')); if (this.get('animate') && this.get('animateCfg')) { shape.setSilent('animateCfg', this.get('animateCfg')); } } }; _proto._applyViewThemeShapeStyle = function _applyViewThemeShapeStyle(cfg, shape, shapeFactory) { // applying view theme var self = this; var viewTheme = self.viewTheme || Global; var shapeName = shapeFactory.name; if (shape) { if (shape && (shape.indexOf('hollow') > -1 || shape.indexOf('liquid') > -1)) { shapeName = "hollow" + Util.upperFirst(shapeName); } } else if (shapeFactory.defaultShapeType.indexOf('hollow') > -1) { shapeName = "hollow" + Util.upperFirst(shapeName); } var defaultStyle = viewTheme.shape[shapeName] || {}; cfg.style = Util.mix({}, defaultStyle, cfg.style); }; _proto.drawPoint = function drawPoint(obj, container, shapeFactory, index) { var self = this; var shape = obj.shape; var cfg = self.getDrawCfg(obj); self._applyViewThemeShapeStyle(cfg, shape, shapeFactory); var geomShape = shapeFactory.drawShape(shape, cfg, container); self.appendShapeInfo(geomShape, index); } /** * 获取属性 * @protected * @param {String} name 属性名 * @return {Scale} 度量 */ ; _proto.getAttr = function getAttr(name) { return this.get('attrs')[name]; } /** * 获取 x 对应的度量 * @return {Scale} x 对应的度量 */ ; _proto.getXScale = function getXScale() { return this.getAttr('position').scales[0]; } /** * 获取 y 对应的度量 * @return {Scale} y 对应的度量 */ ; _proto.getYScale = function getYScale() { return this.getAttr('position').scales[1]; }; _proto.getShapes = function getShapes() { var result = []; var shapeContainer = this.get('shapeContainer'); var children = shapeContainer.get('children'); Util.each(children, function (child) { if (child.get('origin')) { // 过滤 label result.push(child); } }); return result; }; _proto.getAttrsForLegend = function getAttrsForLegend() { var attrs = this.get('attrs'); var rst = []; Util.each(attrs, function (attr) { if (GROUP_ATTRS.includes(attr.type)) { rst.push(attr); } }); return rst; }; _proto.getFieldsForLegend = function getFieldsForLegend() { var fields = []; var attrOptions = this.get('attrOptions'); Util.each(GROUP_ATTRS, function (attrName) { var attrCfg = attrOptions[attrName]; if (attrCfg && attrCfg.field && Util.isString(attrCfg.field)) { fields = fields.concat(attrCfg.field.split('*')); } }); return Util.uniq(fields); }; _proto.changeVisible = function changeVisible(visible, stopDraw) { var me = this; me.set('visible', visible); var shapeContainer = this.get('shapeContainer'); if (shapeContainer) { shapeContainer.set('visible', visible); } var labelContainer = this.get('labelContainer'); if (labelContainer) { labelContainer.set('visible', visible); } if (!stopDraw && shapeContainer) { var canvas = shapeContainer.get('canvas'); canvas.draw(); } }; _proto.reset = function reset() { this.set('attrOptions', {}); this.clearInner(); }; _proto.clearInner = function clearInner() { this.clearActivedShapes(); this.clearSelected(); var shapeContainer = this.get('shapeContainer'); shapeContainer && shapeContainer.clear(); // 由于 Labels 对应的模块需要生成group,所以这个地方需要删除 var labelContainer = this.get('labelContainer'); labelContainer && labelContainer.remove(); this.set('attrs', {}); this.set('groupScales', null); // if (!this.get('hasDefaultAdjust')) { // this.set('adjusts', null); // } this.set('labelContainer', null); this.set('xDistance', null); this.set('isStacked', null); }; _proto.clear = function clear() { this.clearInner(); this.set('scales', {}); }; _proto.destroy = function destroy() { this.clear(); var shapeContainer = this.get('shapeContainer'); shapeContainer && shapeContainer.remove(); this.offEvents(); _Base.prototype.destroy.call(this); }; _proto.bindEvents = function bindEvents() { if (this.get('view')) { this._bindActiveAction(); this._bindSelectedAction(); } }; _proto.offEvents = function offEvents() { if (this.get('view')) { this._offActiveAction(); this._offSelectedAction(); } }; return GeomBase; }(Base); module.exports = GeomBase; /***/ }), /* 24 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { Axis: __webpack_require__(344), Component: __webpack_require__(92), Guide: __webpack_require__(372), Label: __webpack_require__(381), Legend: __webpack_require__(382), Tooltip: __webpack_require__(388) }; /***/ }), /* 25 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview 计算path 使用的工具方法 * @author dxq613@gmail.com */ var Util = __webpack_require__(0); var Spline = __webpack_require__(392); function points2path(points, isInCircle) { if (!points.length) { return []; } var path = []; for (var i = 0, length = points.length; i < length; i++) { var item = points[i]; if (i === 0) { path.push(['M', item.x, item.y]); } else { path.push(['L', item.x, item.y]); } } if (isInCircle) { path.push(['Z']); } return path; } function _getPointRadius(coord, point) { var center = coord.getCenter(); var r = Math.sqrt(Math.pow(point.x - center.x, 2) + Math.pow(point.y - center.y, 2)); return r; } function convertArr(arr, coord) { var len = arr.length; var tmp = [arr[0]]; for (var i = 1; i < len; i = i + 2) { var point = coord.convertPoint({ x: arr[i], y: arr[i + 1] }); tmp.push(point.x, point.y); } return tmp; } function _convertPolarPath(pre, cur, coord) { // const radius = coord.getRadius(); // const inner = coord.innerRadius || 0; // let innerRadius = inner * radius; var transposed = coord.isTransposed; var startAngle = coord.startAngle; var endAngle = coord.endAngle; var prePoint = { x: pre[1], y: pre[2] }; var curPoint = { x: cur[1], y: cur[2] }; var rst = []; // innerRadius = innerRadius || 0; var xDim = transposed ? 'y' : 'x'; var angleRange = Math.abs(curPoint[xDim] - prePoint[xDim]) * (endAngle - startAngle); var direction = curPoint[xDim] >= prePoint[xDim] ? 1 : 0; // 圆弧的方向 var flag = angleRange > Math.PI ? 1 : 0; // 大弧还是小弧标志位 var convertPoint = coord.convertPoint(curPoint); var r = _getPointRadius(coord, convertPoint); if (r >= 0.5) { // 小于1像素的圆在图像上无法识别 if (angleRange === Math.PI * 2) { var middlePoint = { x: (curPoint.x + prePoint.x) / 2, y: (curPoint.y + prePoint.y) / 2 }; var middleConvertPoint = coord.convertPoint(middlePoint); rst.push(['A', r, r, 0, flag, direction, middleConvertPoint.x, middleConvertPoint.y]); rst.push(['A', r, r, 0, flag, direction, convertPoint.x, convertPoint.y]); } else { rst.push(['A', r, r, 0, flag, direction, convertPoint.x, convertPoint.y]); } } return rst; } // 当存在整体的圆时,去除圆前面和后面的线,防止出现直线穿过整个圆的情形 function filterFullCirleLine(path) { Util.each(path, function (subPath, index) { var cur = subPath; if (cur[0].toLowerCase() === 'a') { var pre = path[index - 1]; var next = path[index + 1]; if (next && next[0].toLowerCase() === 'a') { if (pre && pre[0].toLowerCase() === 'l') { pre[0] = 'M'; } } else if (pre && pre[0].toLowerCase() === 'a') { if (next && next[0].toLowerCase() === 'l') { next[0] = 'M'; } } } }); } var PathUtil = { // 线的path getLinePath: function getLinePath(points, isInCircle) { return points2path(points, isInCircle); }, // get spline: 限定了范围的平滑线 getSplinePath: function getSplinePath(points, isInCircle, constaint) { var data = []; var first = points[0]; var prePoint = null; if (points.length <= 2) { return PathUtil.getLinePath(points, isInCircle); } Util.each(points, function (point) { if (!prePoint || !(prePoint.x === point.x && prePoint.y === point.y)) { data.push(point.x); data.push(point.y); prePoint = point; } }); constaint = constaint || [// 范围 [0, 0], [1, 1]]; var splinePath = Spline.catmullRom2bezier(data, isInCircle, constaint); splinePath.unshift(['M', first.x, first.y]); return splinePath; }, getPointRadius: function getPointRadius(coord, point) { var result = _getPointRadius(coord, point); return result; }, getPointAngle: function getPointAngle(coord, point) { var center = coord.getCenter(); var angle = Math.atan2(point.y - center.y, point.x - center.x); return angle; }, convertNormalPath: function convertNormalPath(coord, path) { var tmp = []; Util.each(path, function (subPath) { var action = subPath[0]; switch (action.toLowerCase()) { case 'm': case 'l': case 'c': tmp.push(convertArr(subPath, coord)); break; case 'z': default: tmp.push(subPath); break; } }); return tmp; }, convertPolarPath: function convertPolarPath(coord, path) { var tmp = []; var pre; var cur; var transposed; var equals; Util.each(path, function (subPath, index) { var action = subPath[0]; switch (action.toLowerCase()) { case 'm': case 'c': case 'q': tmp.push(convertArr(subPath, coord)); break; case 'l': pre = path[index - 1]; cur = subPath; transposed = coord.isTransposed; // 是否半径相同,转换成圆弧 equals = transposed ? pre[pre.length - 2] === cur[1] : pre[pre.length - 1] === cur[2]; if (equals) { tmp = tmp.concat(_convertPolarPath(pre, cur, coord)); } else { // y 不相等,所以直接转换 tmp.push(convertArr(subPath, coord)); } break; case 'z': default: tmp.push(subPath); break; } }); filterFullCirleLine(tmp); // 过滤多余的直线 return tmp; } }; module.exports = PathUtil; /***/ }), /* 26 */ /***/ (function(module, exports, __webpack_require__) { var isNil = __webpack_require__(6); function toString(value) { if (isNil(value)) return ''; return value.toString(); } module.exports = toString; /***/ }), /* 27 */ /***/ (function(module, exports, __webpack_require__) { var isPlainObject = __webpack_require__(28); var isArray = __webpack_require__(5); var MAX_MIX_LEVEL = 5; function _deepMix(dist, src, level, maxLevel) { level = level || 0; maxLevel = maxLevel || MAX_MIX_LEVEL; for (var key in src) { if (src.hasOwnProperty(key)) { var value = src[key]; if (value !== null && isPlainObject(value)) { if (!isPlainObject(dist[key])) { dist[key] = {}; } if (level < maxLevel) { _deepMix(dist[key], value, level + 1, maxLevel); } else { dist[key] = src[key]; } } else if (isArray(value)) { dist[key] = []; dist[key] = dist[key].concat(value); } else if (value !== undefined) { dist[key] = value; } } } } var deepMix = function deepMix() { var args = new Array(arguments.length); var length = args.length; for (var i = 0; i < length; i++) { args[i] = arguments[i]; } var rst = args[0]; for (var _i = 1; _i < length; _i++) { _deepMix(rst, args[_i]); } return rst; }; module.exports = deepMix; /***/ }), /* 28 */ /***/ (function(module, exports, __webpack_require__) { var isObjectLike = __webpack_require__(63); var isType = __webpack_require__(14); var isPlainObject = function isPlainObject(value) { /** * isObjectLike(new Foo) => false * isObjectLike([1, 2, 3]) => false * isObjectLike({ x: 0, y: 0 }) => true * isObjectLike(Object.create(null)) => true */ if (!isObjectLike(value) || !isType(value, 'Object')) { return false; } if (Object.getPrototypeOf(value) === null) { return true; } var proto = value; while (Object.getPrototypeOf(proto) !== null) { proto = Object.getPrototypeOf(proto); } return Object.getPrototypeOf(value) === proto; }; module.exports = isPlainObject; /***/ }), /* 29 */ /***/ (function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(15); function toArray(value) { return isArrayLike(value) ? Array.prototype.slice.call(value) : []; } module.exports = toArray; /***/ }), /* 30 */ /***/ (function(module, exports) { var PRECISION = 0.00001; // numbers less than this is considered as 0 module.exports = function isNumberEqual(a, b) { var precision = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : PRECISION; return Math.abs(a - b) < precision; }; /***/ }), /* 31 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var regexTags = /[MLHVQTCSAZ]([^MLHVQTCSAZ]*)/ig; var regexDot = /[^\s\,]+/ig; module.exports = { parseRadius: function parseRadius(radius) { var r1 = 0, r2 = 0, r3 = 0, r4 = 0; if (Util.isArray(radius)) { if (radius.length === 1) { r1 = r2 = r3 = r4 = radius[0]; } else if (radius.length === 2) { r1 = r3 = radius[0]; r2 = r4 = radius[1]; } else if (radius.length === 3) { r1 = radius[0]; r2 = r4 = radius[1]; r3 = radius[2]; } else { r1 = radius[0]; r2 = radius[1]; r3 = radius[2]; r4 = radius[3]; } } else { r1 = r2 = r3 = r4 = radius; } return { r1: r1, r2: r2, r3: r3, r4: r4 }; }, parsePath: function parsePath(path) { path = path || []; if (Util.isArray(path)) { return path; } if (Util.isString(path)) { path = path.match(regexTags); Util.each(path, function (item, index) { item = item.match(regexDot); if (item[0].length > 1) { var tag = item[0].charAt(0); item.splice(1, 0, item[0].substr(1)); item[0] = tag; } Util.each(item, function (sub, i) { if (!isNaN(sub)) { item[i] = +sub; } }); path[index] = item; }); return path; } } }; /***/ }), /* 32 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["c"] = hue; /* harmony export (immutable) */ __webpack_exports__["b"] = gamma; /* harmony export (immutable) */ __webpack_exports__["a"] = nogamma; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__constant__ = __webpack_require__(137); function linear(a, d) { return function (t) { return a + t * d; }; } function exponential(a, b, y) { return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function (t) { return Math.pow(a + t * b, y); }; } function hue(a, b) { var d = b - a; return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : Object(__WEBPACK_IMPORTED_MODULE_0__constant__["a" /* default */])(isNaN(a) ? b : a); } function gamma(y) { return (y = +y) === 1 ? nogamma : function (a, b) { return b - a ? exponential(a, b, y) : Object(__WEBPACK_IMPORTED_MODULE_0__constant__["a" /* default */])(isNaN(a) ? b : a); }; } function nogamma(a, b) { var d = b - a; return d ? linear(a, d) : Object(__WEBPACK_IMPORTED_MODULE_0__constant__["a" /* default */])(isNaN(a) ? b : a); } /***/ }), /* 33 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview the Attribute base class */ var isString = __webpack_require__(12); var isArray = __webpack_require__(5); var isNil = __webpack_require__(6); var mix = __webpack_require__(10); var each = __webpack_require__(3); function toScaleString(scale, value) { if (isString(value)) { return value; } return scale.invert(scale.scale(value)); } /** * 所有视觉通道属性的基类 * @class Attr */ var AttributeBase = /*#__PURE__*/function () { function AttributeBase(cfg) { var _this = this; /** * 属性的类型 * @type {String} */ this.type = 'base'; /** * 属性的名称 * @type {String} */ this.name = null; /** * 回调函数 * @type {Function} */ this.method = null; /** * 备选的值数组 * @type {Array} */ this.values = []; /** * 属性内部的度量 * @type {Array} */ this.scales = []; /** * 是否通过线性取值, 如果未指定,则根据数值的类型判定 * @type {Boolean} */ this.linear = null; /** * 当用户设置的 callback 返回 null 时, 应该返回默认 callback 中的值 */ var mixedCallback = null; var defaultCallback = this.callback; if (cfg.callback) { var userCallback = cfg.callback; mixedCallback = function mixedCallback() { for (var _len = arguments.length, params = new Array(_len), _key = 0; _key < _len; _key++) { params[_key] = arguments[_key]; } var ret = userCallback.apply(void 0, params); if (isNil(ret)) { ret = defaultCallback.apply(_this, params); } return ret; }; } mix(this, cfg); if (mixedCallback) { mix(this, { callback: mixedCallback }); } } // 获取属性值,将值映射到视觉通道 var _proto = AttributeBase.prototype; _proto._getAttrValue = function _getAttrValue(scale, value) { var values = this.values; if (scale.isCategory && !this.linear) { var index = scale.translate(value); return values[index % values.length]; } var percent = scale.scale(value); return this.getLinearValue(percent); }; /** * 如果进行线性映射,返回对应的映射值 * @protected * @param {Number} percent 百分比 * @return {*} 颜色值、形状、大小等 */ _proto.getLinearValue = function getLinearValue(percent) { var values = this.values; var steps = values.length - 1; var step = Math.floor(steps * percent); var leftPercent = steps * percent - step; var start = values[step]; var end = step === steps ? start : values[step + 1]; var rstValue = start + (end - start) * leftPercent; return rstValue; }; /** * 默认的回调函数 * @param {*} value 回调函数的值 * @type {Function} * @return {Array} 返回映射后的值 */ _proto.callback = function callback(value) { var self = this; var scale = self.scales[0]; var rstValue = null; if (scale.type === 'identity') { rstValue = scale.value; } else { rstValue = self._getAttrValue(scale, value); } return rstValue; }; /** * 根据度量获取属性名 * @return {Array} dims of this Attribute */ _proto.getNames = function getNames() { var scales = this.scales; var names = this.names; var length = Math.min(scales.length, names.length); var rst = []; for (var i = 0; i < length; i++) { rst.push(names[i]); } return rst; }; /** * 根据度量获取维度名 * @return {Array} dims of this Attribute */ _proto.getFields = function getFields() { var scales = this.scales; var rst = []; each(scales, function (scale) { rst.push(scale.field); }); return rst; }; /** * 根据名称获取度量 * @param {String} name the name of scale * @return {Scale} scale */ _proto.getScale = function getScale(name) { var scales = this.scales; var names = this.names; var index = names.indexOf(name); return scales[index]; }; /** * 映射数据 * @param {*} param1...paramn 多个数值 * @return {Array} 映射的值组成的数组 */ _proto.mapping = function mapping() { var scales = this.scales; var callback = this.callback; for (var _len2 = arguments.length, params = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { params[_key2] = arguments[_key2]; } var values = params; if (callback) { for (var i = 0, len = params.length; i < len; i++) { params[i] = this._toOriginParam(params[i], scales[i]); } values = callback.apply(this, params); } values = [].concat(values); return values; }; // 原始的参数 _proto._toOriginParam = function _toOriginParam(param, scale) { var rst = param; if (!scale.isLinear) { if (isArray(param)) { rst = []; for (var i = 0, len = param.length; i < len; i++) { rst.push(toScaleString(scale, param[i])); } } else { rst = toScaleString(scale, param); } } return rst; }; return AttributeBase; }(); module.exports = AttributeBase; /***/ }), /* 34 */ /***/ (function(module, exports, __webpack_require__) { var mix = __webpack_require__(10); var Adjust = /*#__PURE__*/function () { var _proto = Adjust.prototype; _proto._initDefaultCfg = function _initDefaultCfg() { this.adjustNames = ['x', 'y']; // 调整的维度,默认,x,y都做调整 }; function Adjust(cfg) { this._initDefaultCfg(); mix(this, cfg); } /** * @override */ _proto.processAdjust = function processAdjust() /* dataArray */ {}; return Adjust; }(); module.exports = Adjust; /***/ }), /* 35 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Component = __webpack_require__(36); var Util = __webpack_require__(4); var Grid = __webpack_require__(187); var Label = __webpack_require__(188); var _require = __webpack_require__(16), FONT_FAMILY = _require.FONT_FAMILY; var Axis = /*#__PURE__*/function (_Component) { _inheritsLoose(Axis, _Component); function Axis() { return _Component.apply(this, arguments) || this; } var _proto = Axis.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Component.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * 用于动画,唯一标识的 id * @type {[type]} */ _id: null, zIndex: 4, /** * 坐标轴上的坐标点 * @type {Array} */ ticks: null, /** * 坐标轴线的配置信息,如果设置成null,则不显示轴线 * @type {Object} */ line: null, /** * 坐标轴刻度线的配置,如果设置成null,则不显示刻度线 * @type {Object} */ tickLine: null, /** * 次刻度线个数配置 * @type {Number} */ subTickCount: 0, /** * 次刻度线样式配置 * @type {Object} */ subTickLine: null, /** * 网格线配置,如果值为 null,则不显示 * @type {Object} */ grid: null, /** * 坐标轴文本配置 * @type {Object} */ label: { offset: 0, offsetX: 0, offsetY: 0, textStyle: {}, // 坐标轴文本样式 autoRotate: true, autoHide: false, formatter: null // 坐标轴文本格式化回调函数 }, labelItems: [], /** * 坐标轴标题配置 * @type {Object} */ title: { autoRotate: true, // 文本是否自动旋转 textStyle: {} // 坐标轴标题样式 }, autoPaint: true }); }; _proto.beforeRender = function beforeRender() { var self = this; var title = self.get('title'); var label = self.get('label'); var grid = self.get('grid'); if (title) { self.set('title', Util.deepMix({ autoRotate: true, textStyle: { fontSize: 12, fill: '#ccc', textBaseline: 'middle', fontFamily: FONT_FAMILY, textAlign: 'center' }, offset: 48 }, title)); } if (label) { self.set('label', Util.deepMix({ autoRotate: true, autoHide: true, textStyle: { fontSize: 12, fill: '#ccc', textBaseline: 'middle', fontFamily: FONT_FAMILY }, offset: 10 }, label)); } if (grid) { self.set('grid', Util.deepMix({ lineStyle: { lineWidth: 1, stroke: '#C0D0E0' } }, grid)); } }; _proto.render = function render() { var self = this; self.beforeRender(); var labelCfg = self.get('label'); if (labelCfg) { self.renderLabels(); } if (self.get('autoPaint')) { self.paint(); } if (!Util.isNil(self.get('title'))) { self.renderTitle(); } self.get('group').sort(); }; _proto.renderLabels = function renderLabels() { var self = this; var group = self.get('group'); var labelCfg = self.get('label'); var labelRenderer = new Label({ name: 'axis-label' }); self.set('labelRenderer', labelRenderer); labelRenderer.set('labelCfg', labelCfg); var cfgs2copy = ['formatter', 'htmlTemplate', 'labelLine', 'textStyle', 'useHtml']; Util.each(cfgs2copy, function (cfg) { if (labelCfg[cfg]) { labelRenderer.set(cfg, labelCfg[cfg]); } }); labelRenderer.set('coord', self.get('coord')); labelRenderer.set('group', group.addGroup()); labelRenderer.set('canvas', self.get('canvas')); }; _proto._parseTicks = function _parseTicks(ticks) { ticks = ticks || []; var ticksLength = ticks.length; for (var i = 0; i < ticksLength; i++) { var item = ticks[i]; if (!Util.isObject(item)) { ticks[i] = this.parseTick(item, i, ticksLength); } } this.set('ticks', ticks); return ticks; }; _proto._addTickItem = function _addTickItem(index, point, length, type) { if (type === void 0) { type = ''; } var tickItems = this.get('tickItems'); var subTickItems = this.get('subTickItems'); var end = this.getTickEnd(point, length, index); var cfg = { x1: point.x, y1: point.y, x2: end.x, y2: end.y }; if (!tickItems) { tickItems = []; } if (!subTickItems) { subTickItems = []; } if (type === 'sub') { subTickItems.push(cfg); } else { tickItems.push(cfg); } this.set('tickItems', tickItems); this.set('subTickItems', subTickItems); }; _proto._renderLine = function _renderLine() { var self = this; var lineCfg = self.get('line'); var path; if (lineCfg) { path = self.getLinePath(); lineCfg = Util.mix({ path: path }, lineCfg); var group = self.get('group'); var lineShape = group.addShape('path', { attrs: lineCfg }); lineShape.name = 'axis-line'; self.get('appendInfo') && lineShape.setSilent('appendInfo', self.get('appendInfo')); self.set('lineShape', lineShape); } }; _proto._processCatTicks = function _processCatTicks() { var self = this; var labelCfg = self.get('label'); var tickLineCfg = self.get('tickLine'); var ticks = self.get('ticks'); ticks = self._parseTicks(ticks); var new_ticks = self._getNormalizedTicks(ticks); for (var i = 0; i < new_ticks.length; i += 3) { var p = self.getTickPoint(new_ticks[i]); var p0 = self.getTickPoint(new_ticks[i + 1]); var p1 = self.getTickPoint(new_ticks[i + 2]); var index = Math.floor(i / 3); var tick = ticks[index]; if (tickLineCfg) { if (index === 0) { self._addTickItem(index, p0, tickLineCfg.length); } self._addTickItem(index, p1, tickLineCfg.length); } if (labelCfg) { self.addLabel(tick, p, index); } } }; _proto._getNormalizedTicks = function _getNormalizedTicks(ticks) { var tickSeg = 0; if (ticks.length > 1) { tickSeg = (ticks[1].value - ticks[0].value) / 2; } var points = []; for (var i = 0; i < ticks.length; i++) { var tick = ticks[i]; var p = tick.value; var p0 = tick.value - tickSeg; var p1 = tick.value + tickSeg; points.push(p, p0, p1); } var range = Util.arrayUtil.getRange(points); return points.map(function (p) { var norm = (p - range.min) / (range.max - range.min); return norm; }); }; _proto.addLabel = function addLabel(tick, point, index) { var self = this; var labelItems = self.get('labelItems'); var labelRenderer = self.get('labelRenderer'); var label = Util.deepMix({}, self.get('label')); var rst; if (labelRenderer) { var offset = self.get('_labelOffset'); if (!Util.isNil(self.get('label').offset)) { offset = self.get('label').offset; } var vector = self.getSideVector(offset, point, index); point = { x: point.x + vector[0] + label.offsetX, y: point.y + vector[1] + label.offsetY }; label.text = tick.text; label.x = point.x; label.y = point.y; label.point = point; label.textAlign = self.getTextAnchor(vector); if (point.rotate) { label.rotate = point.rotate; } labelItems.push(label); } return rst; }; _proto._processTicks = function _processTicks() { var self = this; var labelCfg = self.get('label'); var subTickCount = self.get('subTickCount'); var tickLineCfg = self.get('tickLine'); var ticks = self.get('ticks'); ticks = self._parseTicks(ticks); Util.each(ticks, function (tick, index) { var tickPoint = self.getTickPoint(tick.value, index); if (tickLineCfg) { self._addTickItem(index, tickPoint, tickLineCfg.length); } if (labelCfg) { self.addLabel(tick, tickPoint, index); } }); if (subTickCount) { // 如果有设置次级分点,添加次级tick var subTickLineCfg = self.get('subTickLine'); Util.each(ticks, function (tick, index) { if (index > 0) { var diff = tick.value - ticks[index - 1].value; diff = diff / (self.get('subTickCount') + 1); for (var i = 1; i <= subTickCount; i++) { var subTick = { text: '', value: index ? ticks[index - 1].value + i * diff : i * diff }; var tickPoint = self.getTickPoint(subTick.value); var subTickLength = void 0; if (subTickLineCfg && subTickLineCfg.length) { subTickLength = subTickLineCfg.length; } else { subTickLength = parseInt(tickLineCfg.length * (3 / 5), 10); } self._addTickItem(i - 1, tickPoint, subTickLength, 'sub'); } } }); } }; _proto._addTickLine = function _addTickLine(ticks, lineCfg) { var self = this; var cfg = Util.mix({}, lineCfg); var path = []; Util.each(ticks, function (item) { path.push(['M', item.x1, item.y1]); path.push(['L', item.x2, item.y2]); }); delete cfg.length; cfg.path = path; var group = self.get('group'); var tickShape = group.addShape('path', { attrs: cfg }); tickShape.name = 'axis-ticks'; tickShape._id = self.get('_id') + '-ticks'; tickShape.set('coord', self.get('coord')); self.get('appendInfo') && tickShape.setSilent('appendInfo', self.get('appendInfo')); }; _proto._renderTicks = function _renderTicks() { var self = this; var tickItems = self.get('tickItems'); var subTickItems = self.get('subTickItems'); if (!Util.isEmpty(tickItems)) { var tickLineCfg = self.get('tickLine'); self._addTickLine(tickItems, tickLineCfg); } if (!Util.isEmpty(subTickItems)) { var subTickLineCfg = self.get('subTickLine') || self.get('tickLine'); self._addTickLine(subTickItems, subTickLineCfg); } }; _proto._renderGrid = function _renderGrid() { var grid = this.get('grid'); if (!grid) { return; } grid.coord = this.get('coord'); grid.appendInfo = this.get('appendInfo'); var group = this.get('group'); this.set('gridGroup', group.addGroup(Grid, grid)); }; _proto._renderLabels = function _renderLabels() { var self = this; var labelRenderer = self.get('labelRenderer'); var labelItems = self.get('labelItems'); if (labelRenderer) { labelRenderer.set('items', labelItems); labelRenderer._dryDraw(); } }; _proto.paint = function paint() { var self = this; var tickLineCfg = self.get('tickLine'); var alignWithLabel = true; if (tickLineCfg && tickLineCfg.hasOwnProperty('alignWithLabel')) { alignWithLabel = tickLineCfg.alignWithLabel; } self._renderLine(); var type = self.get('type'); var isCat = type === 'cat' || type === 'timeCat'; if (isCat && alignWithLabel === false) { self._processCatTicks(); } else { self._processTicks(); } self._renderTicks(); self._renderGrid(); self._renderLabels(); var labelCfg = this.get('label'); if (labelCfg && labelCfg.autoRotate) { self.autoRotateLabels(); } if (labelCfg && labelCfg.autoHide) { self.autoHideLabels(); } }; _proto.parseTick = function parseTick(tick, index, length) { return { text: tick, value: index / (length - 1) }; }; _proto.getTextAnchor = function getTextAnchor(vector) { var ratio = Math.abs(vector[1] / vector[0]); var align; if (ratio >= 1) { // 上面或者下面 align = 'center'; } else { if (vector[0] > 0) { // 右侧 align = 'start'; } else { // 左侧 align = 'end'; } } return align; }; _proto.getMaxLabelWidth = function getMaxLabelWidth(labelRenderer) { var labels = labelRenderer.getLabels(); var max = 0; Util.each(labels, function (label) { var bbox = label.getBBox(); var width = bbox.width; if (max < width) { max = width; } }); return max; }; _proto.getMaxLabelHeight = function getMaxLabelHeight(labelRenderer) { var labels = labelRenderer.getLabels(); var max = 0; Util.each(labels, function (label) { var bbox = label.getBBox(); var height = bbox.height; if (max < height) { max = height; } }); return max; }; _proto.destroy = function destroy() { var self = this; if (!self.destroyed) { var gridGroup = self.get('gridGroup'); gridGroup && gridGroup.remove(); var labelRenderer = this.get('labelRenderer'); labelRenderer && labelRenderer.destroy(); var group = self.get('group'); group.destroy(); _Component.prototype.destroy.call(this); // 要最后调用 super.destroy 否则 get 属性会无效 } }; _proto.clear = function clear() { var self = this; var group = self.get('group'); if (!group.get('destroyed') && group.get('children').length) { var gridGroup = self.get('gridGroup'); gridGroup && gridGroup.clear(); var labelRenderer = this.get('labelRenderer'); labelRenderer && labelRenderer.clear(); var _group = self.get('group'); _group.clear(); } } /** * 旋转文本 * @abstract * @return {[type]} [description] */ ; _proto.autoRotateLabels = function autoRotateLabels() {} /** * 文本自动防遮罩 * @abstract * @return {[type]} [description] */ ; _proto.autoHideLabels = function autoHideLabels() {} /** * 渲染标题 * @abstract * @return {[type]} [description] */ ; _proto.renderTitle = function renderTitle() {} /** * 获取坐标轴线的 path * @abstract * @return {[type]} [description] */ ; _proto.getLinePath = function getLinePath() {} /** * 获取 tick 在画布上的位置 * @abstract * @return {[type]} [description] */ ; _proto.getTickPoint = function getTickPoint() {} /** * 获取标示坐标点的线的终点 * @abstract * @return {[type]} [description] */ ; _proto.getTickEnd = function getTickEnd() {} /** * 获取距离坐标轴的向量 * @abstract * @return {[type]} [description] */ ; _proto.getSideVector = function getSideVector() {}; return Axis; }(Component); module.exports = Axis; /***/ }), /* 36 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Base = __webpack_require__(92); var Component = /*#__PURE__*/function (_Base) { _inheritsLoose(Component, _Base); function Component() { return _Base.apply(this, arguments) || this; } var _proto = Component.prototype; // 配置 _proto.getDefaultCfg = function getDefaultCfg() { return { // 顶层标志位 _id: null, // 用于动画 // 容器 canvas: null, container: null, // html,可选 group: null, // G Group,可选 // 交互属性 capture: false, // props coord: null, offset: [0, 0], plotRange: null, // BBox position: [0, 0], visible: true, zIndex: 1 }; } // 基础生命周期 ; _proto._init = function _init() {}; _proto.clear = function clear() {}; _proto.destroy = function destroy() { // 之前未指定销毁 _Base.prototype.destroy.call(this); } // 绘图 ; _proto.beforeRender = function beforeRender() {}; _proto.render = function render() {} // 初始化、绑事件和绘图 ; _proto.afterRender = function afterRender() {}; _proto.beforeDraw = function beforeDraw() {}; _proto.draw = function draw() {} // 单纯更新视图 ; _proto.afterDraw = function afterDraw() {} // visibility ; _proto.show = function show() {}; _proto.hide = function hide() {} // props operating syntactic sugar ; _proto.setOffset = function setOffset() {}; _proto.setPosition = function setPosition() {}; _proto.setVisible = function setVisible() {}; _proto.setZIndex = function setZIndex() {}; return Component; }(Base); module.exports = Component; /***/ }), /* 37 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var regexTags = /[MLHVQTCSAZ]([^MLHVQTCSAZ]*)/ig; var regexDot = /[^\s\,]+/ig; var numColorCache = {}; module.exports = { parseRadius: function parseRadius(radius) { var r1 = 0, r2 = 0, r3 = 0, r4 = 0; if (Util.isArray(radius)) { if (radius.length === 1) { r1 = r2 = r3 = r4 = radius[0]; } else if (radius.length === 2) { r1 = r3 = radius[0]; r2 = r4 = radius[1]; } else if (radius.length === 3) { r1 = radius[0]; r2 = r4 = radius[1]; r3 = radius[2]; } else { r1 = radius[0]; r2 = radius[1]; r3 = radius[2]; r4 = radius[3]; } } else { r1 = r2 = r3 = r4 = radius; } return { r1: r1, r2: r2, r3: r3, r4: r4 }; }, parsePath: function parsePath(path) { path = path || []; if (Util.isArray(path)) { return path; } if (Util.isString(path)) { path = path.match(regexTags); Util.each(path, function (item, index) { item = item.match(regexDot); if (item[0].length > 1) { var tag = item[0].charAt(0); item.splice(1, 0, item[0].substr(1)); item[0] = tag; } Util.each(item, function (sub, i) { if (!isNaN(sub)) { item[i] = +sub; } }); path[index] = item; }); return path; } }, numberToColor: function numberToColor(num) { // 增加缓存 var color = numColorCache[num]; if (!color) { var str = num.toString(16); for (var i = str.length; i < 6; i++) { str = '0' + str; } color = '#' + str; numColorCache[num] = color; } return color; } }; /***/ }), /* 38 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * @fileOverview The measurement of linear data scale function * @author dxq613@gmail.com */ var isNil = __webpack_require__(6); var each = __webpack_require__(3); var Base = __webpack_require__(20); var numberAuto = __webpack_require__(208); /** * 线性度量 * @class Scale.Linear */ var Linear = /*#__PURE__*/function (_Base) { _inheritsLoose(Linear, _Base); function Linear() { return _Base.apply(this, arguments) || this; } var _proto = Linear.prototype; _proto._initDefaultCfg = function _initDefaultCfg() { _Base.prototype._initDefaultCfg.call(this); var self = this; self.type = 'linear'; self.isLinear = true; /** * 是否为了用户习惯,优化min,max和ticks,如果进行优化,则会根据生成的ticks调整min,max,否则舍弃(min,max)范围之外的ticks * @type {Boolean} * @default false */ self.nice = false; /** * min value of the scale * @type {Number} * @default null */ self.min = null; /** * min value limitted of the scale * @type {Number} * @default null */ self.minLimit = null; /** * max value of the scale * @type {Number} * @default null */ self.max = null; /** * max value limitted of the scale * @type {Number} * @default null */ self.maxLimit = null; /** * 自动生成标记时的个数 * @type {Number} * @default null */ self.tickCount = null; /** * 坐标轴点之间的间距,指的是真实数据的差值 * @type {Number} * @default null */ self.tickInterval = null; /** * 坐标轴点之间的最小间距,指的是真实数据的差值 * @type {Number} * @default null */ self.minTickInterval = null; /** * 用于计算坐标点时逼近的数组 * @type {Array} */ self.snapArray = null; } /** * @protected * @override */ ; _proto.init = function init() { var self = this; if (!self.ticks) { self.min = self.translate(self.min); self.max = self.translate(self.max); self.initTicks(); } else { var ticks = self.ticks; var firstValue = self.translate(ticks[0]); var lastValue = self.translate(ticks[ticks.length - 1]); if (isNil(self.min) || self.min > firstValue) { self.min = firstValue; } if (isNil(self.max) || self.max < lastValue) { self.max = lastValue; } } } /** * 计算坐标点 * @protected * @return {Array} 计算完成的坐标点 */ ; _proto.calculateTicks = function calculateTicks() { var min = this.min, max = this.max, minLimit = this.minLimit, maxLimit = this.maxLimit, tickCount = this.tickCount, tickInterval = this.tickInterval, minTickInterval = this.minTickInterval, snapArray = this.snapArray; if (tickCount === 1) { throw new Error('linear scale\'tickCount should not be 1'); } if (max < min) { throw new Error("max: " + max + " should not be less than min: " + min); } var tmp = numberAuto({ min: min, max: max, minLimit: minLimit, maxLimit: maxLimit, minCount: tickCount, maxCount: tickCount, interval: tickInterval, minTickInterval: minTickInterval, snapArray: snapArray }); return tmp.ticks; } // 初始化ticks ; _proto.initTicks = function initTicks() { var self = this; var calTicks = self.calculateTicks(); if (self.nice) { // 如果需要优化显示的tick self.ticks = calTicks; self.min = calTicks[0]; self.max = calTicks[calTicks.length - 1]; } else { var ticks = []; each(calTicks, function (tick) { if (tick >= self.min && tick <= self.max) { ticks.push(tick); } }); // 如果 ticks 为空,直接输入最小值、最大值 if (!ticks.length) { ticks.push(self.min); ticks.push(self.max); } self.ticks = ticks; } } /** * @override */ ; _proto.scale = function scale(value) { if (isNil(value)) { return NaN; } var max = this.max; var min = this.min; if (max === min) { return 0; } var percent = (value - min) / (max - min); var rangeMin = this.rangeMin(); var rangeMax = this.rangeMax(); return rangeMin + percent * (rangeMax - rangeMin); } /** * @override */ ; _proto.invert = function invert(value) { var percent = (value - this.rangeMin()) / (this.rangeMax() - this.rangeMin()); return this.min + percent * (this.max - this.min); }; return Linear; }(Base); Base.Linear = Linear; module.exports = Linear; /***/ }), /* 39 */ /***/ (function(module, exports, __webpack_require__) { var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var isArray = __webpack_require__(5); var clone = function clone(obj) { if ((typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) !== 'object' || obj === null) { return obj; } var rst = void 0; if (isArray(obj)) { rst = []; for (var i = 0, l = obj.length; i < l; i++) { if (_typeof(obj[i]) === 'object' && obj[i] != null) { rst[i] = clone(obj[i]); } else { rst[i] = obj[i]; } } } else { rst = {}; for (var k in obj) { if (_typeof(obj[k]) === 'object' && obj[k] != null) { rst[k] = clone(obj[k]); } else { rst[k] = obj[k]; } } } return rst; }; module.exports = clone; /***/ }), /* 40 */ /***/ (function(module, exports, __webpack_require__) { var isObjectLike = __webpack_require__(63); var isArrayLike = __webpack_require__(15); var isString = __webpack_require__(12); var isEqual = function isEqual(value, other) { if (value === other) { return true; } if (!value || !other) { return false; } if (isString(value) || isString(other)) { return false; } if (isArrayLike(value) || isArrayLike(other)) { if (value.length !== other.length) { return false; } var rst = true; for (var i = 0; i < value.length; i++) { rst = isEqual(value[i], other[i]); if (!rst) { break; } } return rst; } if (isObjectLike(value) || isObjectLike(other)) { var valueKeys = Object.keys(value); var otherKeys = Object.keys(other); if (valueKeys.length !== otherKeys.length) { return false; } var _rst = true; for (var _i = 0; _i < valueKeys.length; _i++) { _rst = isEqual(value[valueKeys[_i]], other[valueKeys[_i]]); if (!_rst) { break; } } return _rst; } return false; }; module.exports = isEqual; /***/ }), /* 41 */ /***/ (function(module, exports) { var clamp = function clamp(a, min, max) { if (a < min) { return min; } else if (a > max) { return max; } return a; }; module.exports = clamp; /***/ }), /* 42 */ /***/ (function(module, exports, __webpack_require__) { var mat3 = __webpack_require__(218); mat3.translate = function (out, a, v) { var transMat = new Array(9); mat3.fromTranslation(transMat, v); return mat3.multiply(out, transMat, a); }; mat3.rotate = function (out, a, rad) { var rotateMat = new Array(9); mat3.fromRotation(rotateMat, rad); return mat3.multiply(out, rotateMat, a); }; mat3.scale = function (out, a, v) { var scaleMat = new Array(9); mat3.fromScaling(scaleMat, v); return mat3.multiply(out, scaleMat, a); }; module.exports = mat3; /***/ }), /* 43 */ /***/ (function(module, exports, __webpack_require__) { var vec2 = __webpack_require__(1).vec2; module.exports = { at: function at(p1, p2, t) { return (p2 - p1) * t + p1; }, pointDistance: function pointDistance(x1, y1, x2, y2, x, y) { var d = [x2 - x1, y2 - y1]; if (vec2.exactEquals(d, [0, 0])) { return NaN; } var u = [-d[1], d[0]]; vec2.normalize(u, u); var a = [x - x1, y - y1]; return Math.abs(vec2.dot(a, u)); }, box: function box(x1, y1, x2, y2, lineWidth) { var halfWidth = lineWidth / 2; var minX = Math.min(x1, x2); var maxX = Math.max(x1, x2); var minY = Math.min(y1, y2); var maxY = Math.max(y1, y2); return { minX: minX - halfWidth, minY: minY - halfWidth, maxX: maxX + halfWidth, maxY: maxY + halfWidth }; }, len: function len(x1, y1, x2, y2) { return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); } }; /***/ }), /* 44 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); function circlePoint(cx, cy, r, angle) { return { x: Math.cos(angle) * r + cx, y: Math.sin(angle) * r + cy }; } function angleNearTo(angle, min, max, out) { var v1; var v2; if (out) { if (angle < min) { v1 = min - angle; v2 = Math.PI * 2 - max + angle; } else if (angle > max) { v1 = Math.PI * 2 - angle + min; v2 = angle - max; } } else { v1 = angle - min; v2 = max - angle; } return v1 > v2 ? max : min; } function nearAngle(angle, startAngle, endAngle, clockwise) { var plus = 0; if (endAngle - startAngle >= Math.PI * 2) { plus = Math.PI * 2; } startAngle = Util.mod(startAngle, Math.PI * 2); endAngle = Util.mod(endAngle, Math.PI * 2) + plus; angle = Util.mod(angle, Math.PI * 2); if (clockwise) { if (startAngle >= endAngle) { if (angle > endAngle && angle < startAngle) { return angle; } return angleNearTo(angle, endAngle, startAngle, true); } if (angle < startAngle || angle > endAngle) { return angle; } return angleNearTo(angle, startAngle, endAngle); } if (startAngle <= endAngle) { if (startAngle < angle && angle < endAngle) { return angle; } return angleNearTo(angle, startAngle, endAngle, true); } if (angle > startAngle || angle < endAngle) { return angle; } return angleNearTo(angle, endAngle, startAngle); } function arcProjectPoint(cx, cy, r, startAngle, endAngle, clockwise, x, y, out) { var v = [x, y]; var v0 = [cx, cy]; var v1 = [1, 0]; var subv = Util.vec2.subtract([], v, v0); var angle = Util.vec2.angleTo(v1, subv); angle = nearAngle(angle, startAngle, endAngle, clockwise); var vpoint = [r * Math.cos(angle) + cx, r * Math.sin(angle) + cy]; if (out) { out.x = vpoint[0]; out.y = vpoint[1]; } var d = Util.vec2.distance(vpoint, v); return d; } function arcBox(cx, cy, r, startAngle, endAngle, clockwise) { var angleRight = 0; var angleBottom = Math.PI / 2; var angleLeft = Math.PI; var angleTop = Math.PI * 3 / 2; var points = []; var angle = nearAngle(angleRight, startAngle, endAngle, clockwise); if (angle === angleRight) { points.push(circlePoint(cx, cy, r, angleRight)); } angle = nearAngle(angleBottom, startAngle, endAngle, clockwise); if (angle === angleBottom) { points.push(circlePoint(cx, cy, r, angleBottom)); } angle = nearAngle(angleLeft, startAngle, endAngle, clockwise); if (angle === angleLeft) { points.push(circlePoint(cx, cy, r, angleLeft)); } angle = nearAngle(angleTop, startAngle, endAngle, clockwise); if (angle === angleTop) { points.push(circlePoint(cx, cy, r, angleTop)); } points.push(circlePoint(cx, cy, r, startAngle)); points.push(circlePoint(cx, cy, r, endAngle)); var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; Util.each(points, function (point) { if (minX > point.x) { minX = point.x; } if (maxX < point.x) { maxX = point.x; } if (minY > point.y) { minY = point.y; } if (maxY < point.y) { maxY = point.y; } }); return { minX: minX, minY: minY, maxX: maxX, maxY: maxY }; } module.exports = { nearAngle: nearAngle, projectPoint: function projectPoint(cx, cy, r, startAngle, endAngle, clockwise, x, y) { var rst = {}; arcProjectPoint(cx, cy, r, startAngle, endAngle, clockwise, x, y, rst); return rst; }, pointDistance: arcProjectPoint, box: arcBox }; /***/ }), /* 45 */ /***/ (function(module, exports, __webpack_require__) { var Format = __webpack_require__(31); var PathSegment = __webpack_require__(46); var PI = Math.PI; var sin = Math.sin; var cos = Math.cos; var atan2 = Math.atan2; var DEFAULT_LENGTH = 10; var DEFAULT_ANGLE = PI / 3; function _addArrow(ctx, attrs, x1, y1, x2, y2, isStart) { var leftX; var leftY; var rightX; var rightY; var offsetX; var offsetY; var angle; if (!attrs.fill) { // 闭合的不绘制箭头 var arrowLength = attrs.arrowLength || DEFAULT_LENGTH; var arrowAngle = attrs.arrowAngle ? attrs.arrowAngle * PI / 180 : DEFAULT_ANGLE; // 转换为弧 // Calculate angle angle = atan2(y1 - y2, x1 - x2); /* // Adjust angle correctly angle -= PI;*/ // Calculate offset to place arrow at edge of path offsetX = Math.abs(attrs.lineWidth * cos(angle)) / 2; offsetY = Math.abs(attrs.lineWidth * sin(angle)) / 2; if (isStart) { offsetX = -offsetX; offsetY = -offsetY; } // Calculate coordinates for left half of arrow leftX = x2 + arrowLength * cos(angle + arrowAngle / 2); leftY = y2 + arrowLength * sin(angle + arrowAngle / 2); // Calculate coordinates for right half of arrow rightX = x2 + arrowLength * cos(angle - arrowAngle / 2); rightY = y2 + arrowLength * sin(angle - arrowAngle / 2); ctx.beginPath(); // Draw left half of arrow ctx.moveTo(leftX - offsetX, leftY - offsetY); ctx.lineTo(x2 - offsetX, y2 - offsetY); // Draw right half of arrow ctx.lineTo(rightX - offsetX, rightY - offsetY); // Visually connect arrow to path ctx.moveTo(x2 - offsetX, y2 - offsetY); ctx.lineTo(x2 + offsetX, y2 + offsetY); // Move back to end of path ctx.moveTo(x2, y2); ctx.stroke(); } } function parsePath(attrs) { var segments = []; var pathArray = Format.parsePath(attrs.path); var preSegment; if (!Array.isArray(pathArray) || pathArray.length === 0 || pathArray[0][0] !== 'M' && pathArray[0][0] !== 'm') { return false; } var count = pathArray.length; for (var i = 0; i < pathArray.length; i++) { var item = pathArray[i]; preSegment = new PathSegment(item, preSegment, i === count - 1); segments.push(preSegment); } return segments; } /** * 如果自定义箭头并且有 d 需要做偏移,如果直接画,线条会超出箭头尖端,因此需要根据箭头偏移 d, 返回线需要缩短的距离 * |---------------- * |<|-------------- * | * @param {Number} x1 起始点 x * @param {number} y1 起始点 y * @param {number} x2 箭头作用点 x * @param {number} y2 箭头作用点 y * @param {number} d 箭头沿线条方向的偏移距离 * @return {{dx: number, dy: number}} 返回线条偏移距离 */ function getShortenOffset(x1, y1, x2, y2, d) { var rad = Math.atan2(y2 - y1, x2 - x1); return { dx: cos(rad) * d, dy: sin(rad) * d }; } function _addCustomizedArrow(ctx, attrs, x1, y1, x2, y2, isStart) { var shape = isStart ? attrs.startArrow : attrs.endArrow; var d = shape.d; var x = x2 - x1; var y = y2 - y1; var rad = Math.atan2(y, x); var path = parsePath(shape); if (!path) { return; } if (d) { x2 = x2 - cos(rad) * d; y2 = y2 - sin(rad) * d; } ctx.save(); ctx.beginPath(); ctx.translate(x2, y2); ctx.rotate(rad); for (var i = 0; i < path.length; i++) { path[i].draw(ctx); } ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.fillStyle = ctx.strokeStyle; ctx.fill(); ctx.restore(); } module.exports = { addStartArrow: function addStartArrow(ctx, attrs, x1, y1, x2, y2) { if (typeof attrs.startArrow === 'object') { _addCustomizedArrow(ctx, attrs, x1, y1, x2, y2, true); } else if (attrs.startArrow) { _addArrow(ctx, attrs, x1, y1, x2, y2, true); } }, addEndArrow: function addEndArrow(ctx, attrs, x1, y1, x2, y2) { if (typeof attrs.endArrow === 'object') { _addCustomizedArrow(ctx, attrs, x1, y1, x2, y2, false); } else if (attrs.endArrow) { _addArrow(ctx, attrs, x1, y1, x2, y2, false); } }, getShortenOffset: getShortenOffset }; /***/ }), /* 46 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Inside = __webpack_require__(79); var Cubic = __webpack_require__(80); var Quadratic = __webpack_require__(118); var Ellipse = __webpack_require__(119); var vec3 = Util.vec3; var mat3 = Util.mat3; var ARR_CMD = ['m', 'l', 'c', 'a', 'q', 'h', 'v', 't', 's', 'z']; function toAbsolute(x, y, curPoint) { // 获取绝对坐标 return { x: curPoint.x + x, y: curPoint.y + y }; } function toSymmetry(point, center) { // 点对称 return { x: center.x + (center.x - point.x), y: center.y + (center.y - point.y) }; } function vMag(v) { return Math.sqrt(v[0] * v[0] + v[1] * v[1]); } function vRatio(u, v) { return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v)); } function vAngle(u, v) { return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v)); } function getArcParams(point1, point2, fa, fs, rx, ry, psiDeg) { var psi = Util.mod(Util.toRadian(psiDeg), Math.PI * 2); var x1 = point1.x; var y1 = point1.y; var x2 = point2.x; var y2 = point2.y; 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 diff = rx * rx * (yp * yp) + ry * ry * (xp * xp); var f = Math.sqrt((rx * rx * (ry * ry) - diff) / diff); 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 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 [point1, cx, cy, rx, ry, theta, dTheta, psi, fs]; } var PathSegment = function PathSegment(item, preSegment, isLast) { this.preSegment = preSegment; this.isLast = isLast; this.init(item, preSegment); }; Util.augment(PathSegment, { init: function init(item, preSegment) { var command = item[0]; preSegment = preSegment || { endPoint: { x: 0, y: 0 } }; var relative = ARR_CMD.indexOf(command) >= 0; // /[a-z]/.test(command); var cmd = relative ? command.toUpperCase() : command; var p = item; var point1; var point2; var point3; var point; var preEndPoint = preSegment.endPoint; var p1 = p[1]; var p2 = p[2]; switch (cmd) { default: break; case 'M': if (relative) { point = toAbsolute(p1, p2, preEndPoint); } else { point = { x: p1, y: p2 }; } this.command = 'M'; this.params = [preEndPoint, point]; this.subStart = point; this.endPoint = point; break; case 'L': if (relative) { point = toAbsolute(p1, p2, preEndPoint); } else { point = { x: p1, y: p2 }; } this.command = 'L'; this.params = [preEndPoint, point]; this.subStart = preSegment.subStart; this.endPoint = point; this.endTangent = function () { return [point.x - preEndPoint.x, point.y - preEndPoint.y]; }; this.startTangent = function () { return [preEndPoint.x - point.x, preEndPoint.y - point.y]; }; break; case 'H': if (relative) { point = toAbsolute(p1, 0, preEndPoint); } else { point = { x: p1, y: preEndPoint.y }; } this.command = 'L'; this.params = [preEndPoint, point]; this.subStart = preSegment.subStart; this.endPoint = point; this.endTangent = function () { return [point.x - preEndPoint.x, point.y - preEndPoint.y]; }; this.startTangent = function () { return [preEndPoint.x - point.x, preEndPoint.y - point.y]; }; break; case 'V': if (relative) { point = toAbsolute(0, p1, preEndPoint); } else { point = { x: preEndPoint.x, y: p1 }; } this.command = 'L'; this.params = [preEndPoint, point]; this.subStart = preSegment.subStart; this.endPoint = point; this.endTangent = function () { return [point.x - preEndPoint.x, point.y - preEndPoint.y]; }; this.startTangent = function () { return [preEndPoint.x - point.x, preEndPoint.y - point.y]; }; break; case 'Q': if (relative) { point1 = toAbsolute(p1, p2, preEndPoint); point2 = toAbsolute(p[3], p[4], preEndPoint); } else { point1 = { x: p1, y: p2 }; point2 = { x: p[3], y: p[4] }; } this.command = 'Q'; this.params = [preEndPoint, point1, point2]; this.subStart = preSegment.subStart; this.endPoint = point2; this.endTangent = function () { return [point2.x - point1.x, point2.y - point1.y]; }; this.startTangent = function () { return [preEndPoint.x - point1.x, preEndPoint.y - point1.y]; }; break; case 'T': if (relative) { point2 = toAbsolute(p1, p2, preEndPoint); } else { point2 = { x: p1, y: p2 }; } if (preSegment.command === 'Q') { point1 = toSymmetry(preSegment.params[1], preEndPoint); this.command = 'Q'; this.params = [preEndPoint, point1, point2]; this.subStart = preSegment.subStart; this.endPoint = point2; this.endTangent = function () { return [point2.x - point1.x, point2.y - point1.y]; }; this.startTangent = function () { return [preEndPoint.x - point1.x, preEndPoint.y - point1.y]; }; } else { this.command = 'TL'; this.params = [preEndPoint, point2]; this.subStart = preSegment.subStart; this.endPoint = point2; this.endTangent = function () { return [point2.x - preEndPoint.x, point2.y - preEndPoint.y]; }; this.startTangent = function () { return [preEndPoint.x - point2.x, preEndPoint.y - point2.y]; }; } break; case 'C': if (relative) { point1 = toAbsolute(p1, p2, preEndPoint); point2 = toAbsolute(p[3], p[4], preEndPoint); point3 = toAbsolute(p[5], p[6], preEndPoint); } else { point1 = { x: p1, y: p2 }; point2 = { x: p[3], y: p[4] }; point3 = { x: p[5], y: p[6] }; } this.command = 'C'; this.params = [preEndPoint, point1, point2, point3]; this.subStart = preSegment.subStart; this.endPoint = point3; this.endTangent = function () { return [point3.x - point2.x, point3.y - point2.y]; }; this.startTangent = function () { return [preEndPoint.x - point1.x, preEndPoint.y - point1.y]; }; break; case 'S': if (relative) { point2 = toAbsolute(p1, p2, preEndPoint); point3 = toAbsolute(p[3], p[4], preEndPoint); } else { point2 = { x: p1, y: p2 }; point3 = { x: p[3], y: p[4] }; } if (preSegment.command === 'C') { point1 = toSymmetry(preSegment.params[2], preEndPoint); this.command = 'C'; this.params = [preEndPoint, point1, point2, point3]; this.subStart = preSegment.subStart; this.endPoint = point3; this.endTangent = function () { return [point3.x - point2.x, point3.y - point2.y]; }; this.startTangent = function () { return [preEndPoint.x - point1.x, preEndPoint.y - point1.y]; }; } else { this.command = 'SQ'; this.params = [preEndPoint, point2, point3]; this.subStart = preSegment.subStart; this.endPoint = point3; this.endTangent = function () { return [point3.x - point2.x, point3.y - point2.y]; }; this.startTangent = function () { return [preEndPoint.x - point2.x, preEndPoint.y - point2.y]; }; } break; case 'A': { var rx = p1; var ry = p2; var psi = p[3]; var fa = p[4]; var fs = p[5]; if (relative) { point = toAbsolute(p[6], p[7], preEndPoint); } else { point = { x: p[6], y: p[7] }; } this.command = 'A'; var params = getArcParams(preEndPoint, point, fa, fs, rx, ry, psi); this.params = params; var start = preSegment.subStart; this.subStart = start; this.endPoint = point; var startAngle = params[5] % (Math.PI * 2); if (Util.isNumberEqual(startAngle, Math.PI * 2)) { startAngle = 0; } var endAngle = params[6] % (Math.PI * 2); if (Util.isNumberEqual(endAngle, Math.PI * 2)) { endAngle = 0; } var d = 0.001; this.startTangent = function () { if (fs === 0) { d *= -1; } var dx = params[3] * Math.cos(startAngle - d) + params[1]; var dy = params[4] * Math.sin(startAngle - d) + params[2]; return [dx - start.x, dy - start.y]; }; this.endTangent = function () { var endAngle = params[6]; if (endAngle - Math.PI * 2 < 0.0001) { endAngle = 0; } var dx = params[3] * Math.cos(startAngle + endAngle + d) + params[1]; var dy = params[4] * Math.sin(startAngle + endAngle - d) + params[2]; return [preEndPoint.x - dx, preEndPoint.y - dy]; }; break; } case 'Z': { this.command = 'Z'; this.params = [preEndPoint, preSegment.subStart]; this.subStart = preSegment.subStart; this.endPoint = preSegment.subStart; } } }, isInside: function isInside(x, y, lineWidth) { var self = this; var command = self.command; var params = self.params; var box = self.box; if (box) { if (!Inside.box(box.minX, box.maxX, box.minY, box.maxY, x, y)) { return false; } } switch (command) { default: break; case 'M': return false; case 'TL': case 'L': case 'Z': return Inside.line(params[0].x, params[0].y, params[1].x, params[1].y, lineWidth, x, y); case 'SQ': case 'Q': return Inside.quadraticline(params[0].x, params[0].y, params[1].x, params[1].y, params[2].x, params[2].y, lineWidth, x, y); case 'C': { return Inside.cubicline(params[0].x, params[0].y, params[1].x, params[1].y, params[2].x, params[2].y, params[3].x, params[3].y, lineWidth, x, y); } case 'A': { var p = params; var cx = p[1]; var cy = p[2]; var rx = p[3]; var ry = p[4]; var theta = p[5]; var dTheta = p[6]; var psi = p[7]; var fs = p[8]; var r = rx > ry ? rx : ry; var scaleX = rx > ry ? 1 : rx / ry; var scaleY = rx > ry ? ry / rx : 1; p = [x, y, 1]; var m = [1, 0, 0, 0, 1, 0, 0, 0, 1]; mat3.translate(m, m, [-cx, -cy]); mat3.rotate(m, m, -psi); mat3.scale(m, m, [1 / scaleX, 1 / scaleY]); vec3.transformMat3(p, p, m); return Inside.arcline(0, 0, r, theta, theta + dTheta, 1 - fs, lineWidth, p[0], p[1]); } } return false; }, draw: function draw(context) { var command = this.command; var params = this.params; var point1; var point2; var point3; switch (command) { default: break; case 'M': context.moveTo(params[1].x, params[1].y); break; case 'TL': case 'L': context.lineTo(params[1].x, params[1].y); break; case 'SQ': case 'Q': point1 = params[1]; point2 = params[2]; context.quadraticCurveTo(point1.x, point1.y, point2.x, point2.y); break; case 'C': point1 = params[1]; point2 = params[2]; point3 = params[3]; context.bezierCurveTo(point1.x, point1.y, point2.x, point2.y, point3.x, point3.y); break; case 'A': { var p = params; var p1 = p[1]; var p2 = p[2]; var cx = p1; var cy = p2; var rx = p[3]; var ry = p[4]; var theta = p[5]; var dTheta = p[6]; var psi = p[7]; var fs = p[8]; 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': context.closePath(); break; } }, shortenDraw: function shortenDraw(context, dx, dy) { var command = this.command; var params = this.params; var point1; var point2; var point3; switch (command) { default: break; case 'M': context.moveTo(params[1].x - dx, params[1].y - dy); break; case 'TL': case 'L': context.lineTo(params[1].x - dx, params[1].y - dy); break; case 'SQ': case 'Q': point1 = params[1]; point2 = params[2]; context.quadraticCurveTo(point1.x, point1.y, point2.x - dx, point2.y - dy); break; case 'C': point1 = params[1]; point2 = params[2]; point3 = params[3]; context.bezierCurveTo(point1.x, point1.y, point2.x, point2.y, point3.x - dx, point3.y - dy); break; case 'A': { var p = params; var p1 = p[1]; var p2 = p[2]; var cx = p1; var cy = p2; var rx = p[3]; var ry = p[4]; var theta = p[5]; var dTheta = p[6]; var psi = p[7]; var fs = p[8]; 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': context.closePath(); break; } }, getBBox: function getBBox(lineWidth) { var halfWidth = lineWidth / 2; var params = this.params; var yDims; var xDims; var i; var l; switch (this.command) { default: case 'M': case 'Z': break; case 'TL': case 'L': this.box = { minX: Math.min(params[0].x, params[1].x) - halfWidth, maxX: Math.max(params[0].x, params[1].x) + halfWidth, minY: Math.min(params[0].y, params[1].y) - halfWidth, maxY: Math.max(params[0].y, params[1].y) + halfWidth }; break; case 'SQ': case 'Q': xDims = Quadratic.extrema(params[0].x, params[1].x, params[2].x); for (i = 0, l = xDims.length; i < l; i++) { xDims[i] = Quadratic.at(params[0].x, params[1].x, params[2].x, xDims[i]); } xDims.push(params[0].x, params[2].x); yDims = Quadratic.extrema(params[0].y, params[1].y, params[2].y); for (i = 0, l = yDims.length; i < l; i++) { yDims[i] = Quadratic.at(params[0].y, params[1].y, params[2].y, yDims); } yDims.push(params[0].y, params[2].y); this.box = { minX: Math.min.apply(Math, xDims) - halfWidth, maxX: Math.max.apply(Math, xDims) + halfWidth, minY: Math.min.apply(Math, yDims) - halfWidth, maxY: Math.max.apply(Math, yDims) + halfWidth }; break; case 'C': xDims = Cubic.extrema(params[0].x, params[1].x, params[2].x, params[3].x); for (i = 0, l = xDims.length; i < l; i++) { xDims[i] = Cubic.at(params[0].x, params[1].x, params[2].x, params[3].x, xDims[i]); } yDims = Cubic.extrema(params[0].y, params[1].y, params[2].y, params[3].y); for (i = 0, l = yDims.length; i < l; i++) { yDims[i] = Cubic.at(params[0].y, params[1].y, params[2].y, params[3].y, yDims[i]); } xDims.push(params[0].x, params[3].x); yDims.push(params[0].y, params[3].y); this.box = { minX: Math.min.apply(Math, xDims) - halfWidth, maxX: Math.max.apply(Math, xDims) + halfWidth, minY: Math.min.apply(Math, yDims) - halfWidth, maxY: Math.max.apply(Math, yDims) + halfWidth }; break; case 'A': { // todo 待优化 var p = params; var cx = p[1]; var cy = p[2]; var rx = p[3]; var ry = p[4]; var theta = p[5]; var dTheta = p[6]; var psi = p[7]; var fs = p[8]; var start = theta; var end = theta + dTheta; var xDim = Ellipse.xExtrema(psi, rx, ry); var minX = Infinity; var maxX = -Infinity; var xs = [start, end]; for (i = -Math.PI * 2; i <= Math.PI * 2; i += Math.PI) { var xAngle = xDim + i; if (fs === 1) { if (start < xAngle && xAngle < end) { xs.push(xAngle); } } else { if (end < xAngle && xAngle < start) { xs.push(xAngle); } } } for (i = 0, l = xs.length; i < l; i++) { var x = Ellipse.xAt(psi, rx, ry, cx, xs[i]); if (x < minX) { minX = x; } if (x > maxX) { maxX = x; } } var yDim = Ellipse.yExtrema(psi, rx, ry); var minY = Infinity; var maxY = -Infinity; var ys = [start, end]; for (i = -Math.PI * 2; i <= Math.PI * 2; i += Math.PI) { var yAngle = yDim + i; if (fs === 1) { if (start < yAngle && yAngle < end) { ys.push(yAngle); } } else { if (end < yAngle && yAngle < start) { ys.push(yAngle); } } } for (i = 0, l = ys.length; i < l; i++) { var y = Ellipse.yAt(psi, rx, ry, cy, ys[i]); if (y < minY) { minY = y; } if (y > maxY) { maxY = y; } } this.box = { minX: minX - halfWidth, maxX: maxX + halfWidth, minY: minY - halfWidth, maxY: maxY + halfWidth }; break; } } } }); module.exports = PathSegment; /***/ }), /* 47 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony default export */ __webpack_exports__["a"] = (function (a, b) { return a = +a, b -= a, function (t) { return a + b * t; }; }); /***/ }), /* 48 */ /***/ (function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(15); var indexOf = Array.prototype.indexOf; var contains = function contains(arr, value) { if (!isArrayLike(arr)) { return false; } return indexOf.call(arr, value) > -1; }; module.exports = contains; /***/ }), /* 49 */ /***/ (function(module, exports) { var merge = function merge(dataArray) { var rst = []; for (var i = 0; i < dataArray.length; i++) { rst = rst.concat(dataArray[i]); } return rst; }; module.exports = merge; /***/ }), /* 50 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { mat3: __webpack_require__(42), vec2: __webpack_require__(75), vec3: __webpack_require__(76), transform: __webpack_require__(77) }; /***/ }), /* 51 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { Canvas: __webpack_require__(345), Group: __webpack_require__(171), Shape: __webpack_require__(9), Arc: __webpack_require__(175), Circle: __webpack_require__(176), Dom: __webpack_require__(177), Ellipse: __webpack_require__(178), Fan: __webpack_require__(179), Image: __webpack_require__(180), Line: __webpack_require__(181), Marker: __webpack_require__(95), Path: __webpack_require__(182), Polygon: __webpack_require__(183), Polyline: __webpack_require__(184), Rect: __webpack_require__(185), Text: __webpack_require__(186), PathSegment: __webpack_require__(55), PathUtil: __webpack_require__(96), Event: __webpack_require__(170), // version, etc. version: '3.3.6' }; /***/ }), /* 52 */ /***/ (function(module, exports, __webpack_require__) { var vec2 = __webpack_require__(2).vec2; module.exports = { at: function at(p1, p2, t) { return (p2 - p1) * t + p1; }, pointDistance: function pointDistance(x1, y1, x2, y2, x, y) { var d = [x2 - x1, y2 - y1]; if (vec2.exactEquals(d, [0, 0])) { return NaN; } var u = [-d[1], d[0]]; vec2.normalize(u, u); var a = [x - x1, y - y1]; return Math.abs(vec2.dot(a, u)); }, box: function box(x1, y1, x2, y2, lineWidth) { var halfWidth = lineWidth / 2; var minX = Math.min(x1, x2); var maxX = Math.max(x1, x2); var minY = Math.min(y1, y2); var maxY = Math.max(y1, y2); return { minX: minX - halfWidth, minY: minY - halfWidth, maxX: maxX + halfWidth, maxY: maxY + halfWidth }; }, len: function len(x1, y1, x2, y2) { return Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)); } }; /***/ }), /* 53 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); function circlePoint(cx, cy, r, angle) { return { x: Math.cos(angle) * r + cx, y: Math.sin(angle) * r + cy }; } function angleNearTo(angle, min, max, out) { var v1; var v2; if (out) { if (angle < min) { v1 = min - angle; v2 = Math.PI * 2 - max + angle; } else if (angle > max) { v1 = Math.PI * 2 - angle + min; v2 = angle - max; } } else { v1 = angle - min; v2 = max - angle; } return v1 > v2 ? max : min; } function nearAngle(angle, startAngle, endAngle, clockwise) { var plus = 0; if (endAngle - startAngle >= Math.PI * 2) { plus = Math.PI * 2; } startAngle = Util.mod(startAngle, Math.PI * 2); endAngle = Util.mod(endAngle, Math.PI * 2) + plus; angle = Util.mod(angle, Math.PI * 2); if (clockwise) { if (startAngle >= endAngle) { if (angle > endAngle && angle < startAngle) { return angle; } return angleNearTo(angle, endAngle, startAngle, true); } if (angle < startAngle || angle > endAngle) { return angle; } return angleNearTo(angle, startAngle, endAngle); } if (startAngle <= endAngle) { if (startAngle < angle && angle < endAngle) { return angle; } return angleNearTo(angle, startAngle, endAngle, true); } if (angle > startAngle || angle < endAngle) { return angle; } return angleNearTo(angle, endAngle, startAngle); } function arcProjectPoint(cx, cy, r, startAngle, endAngle, clockwise, x, y, out) { var v = [x, y]; var v0 = [cx, cy]; var v1 = [1, 0]; var subv = Util.vec2.subtract([], v, v0); var angle = Util.vec2.angleTo(v1, subv); angle = nearAngle(angle, startAngle, endAngle, clockwise); var vpoint = [r * Math.cos(angle) + cx, r * Math.sin(angle) + cy]; if (out) { out.x = vpoint[0]; out.y = vpoint[1]; } var d = Util.vec2.distance(vpoint, v); return d; } function arcBox(cx, cy, r, startAngle, endAngle, clockwise) { var angleRight = 0; var angleBottom = Math.PI / 2; var angleLeft = Math.PI; var angleTop = Math.PI * 3 / 2; var points = []; var angle = nearAngle(angleRight, startAngle, endAngle, clockwise); if (angle === angleRight) { points.push(circlePoint(cx, cy, r, angleRight)); } angle = nearAngle(angleBottom, startAngle, endAngle, clockwise); if (angle === angleBottom) { points.push(circlePoint(cx, cy, r, angleBottom)); } angle = nearAngle(angleLeft, startAngle, endAngle, clockwise); if (angle === angleLeft) { points.push(circlePoint(cx, cy, r, angleLeft)); } angle = nearAngle(angleTop, startAngle, endAngle, clockwise); if (angle === angleTop) { points.push(circlePoint(cx, cy, r, angleTop)); } points.push(circlePoint(cx, cy, r, startAngle)); points.push(circlePoint(cx, cy, r, endAngle)); var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; Util.each(points, function (point) { if (minX > point.x) { minX = point.x; } if (maxX < point.x) { maxX = point.x; } if (minY > point.y) { minY = point.y; } if (maxY < point.y) { maxY = point.y; } }); return { minX: minX, minY: minY, maxX: maxX, maxY: maxY }; } module.exports = { nearAngle: nearAngle, projectPoint: function projectPoint(cx, cy, r, startAngle, endAngle, clockwise, x, y) { var rst = {}; arcProjectPoint(cx, cy, r, startAngle, endAngle, clockwise, x, y, rst); return rst; }, pointDistance: arcProjectPoint, box: arcBox }; /***/ }), /* 54 */ /***/ (function(module, exports, __webpack_require__) { var Format = __webpack_require__(37); var PathSegment = __webpack_require__(55); var PI = Math.PI; var sin = Math.sin; var cos = Math.cos; var atan2 = Math.atan2; var DEFAULT_LENGTH = 10; var DEFAULT_ANGLE = PI / 3; function _addArrow(ctx, attrs, x1, y1, x2, y2, isStart) { var leftX; var leftY; var rightX; var rightY; var offsetX; var offsetY; var angle; if (!attrs.fill) { // 闭合的不绘制箭头 var arrowLength = attrs.arrowLength || DEFAULT_LENGTH; var arrowAngle = attrs.arrowAngle ? attrs.arrowAngle * PI / 180 : DEFAULT_ANGLE; // 转换为弧 // Calculate angle angle = atan2(y1 - y2, x1 - x2); /* // Adjust angle correctly angle -= PI;*/ // Calculate offset to place arrow at edge of path offsetX = Math.abs(attrs.lineWidth * cos(angle)) / 2; offsetY = Math.abs(attrs.lineWidth * sin(angle)) / 2; if (isStart) { offsetX = -offsetX; offsetY = -offsetY; } // Calculate coordinates for left half of arrow leftX = x2 + arrowLength * cos(angle + arrowAngle / 2); leftY = y2 + arrowLength * sin(angle + arrowAngle / 2); // Calculate coordinates for right half of arrow rightX = x2 + arrowLength * cos(angle - arrowAngle / 2); rightY = y2 + arrowLength * sin(angle - arrowAngle / 2); ctx.beginPath(); // Draw left half of arrow ctx.moveTo(leftX - offsetX, leftY - offsetY); ctx.lineTo(x2 - offsetX, y2 - offsetY); // Draw right half of arrow ctx.lineTo(rightX - offsetX, rightY - offsetY); // Visually connect arrow to path ctx.moveTo(x2 - offsetX, y2 - offsetY); ctx.lineTo(x2 + offsetX, y2 + offsetY); // Move back to end of path ctx.moveTo(x2, y2); ctx.stroke(); } } function parsePath(attrs) { var segments = []; var pathArray = Format.parsePath(attrs.path); var preSegment; if (!Array.isArray(pathArray) || pathArray.length === 0 || pathArray[0][0] !== 'M' && pathArray[0][0] !== 'm') { return false; } var count = pathArray.length; for (var i = 0; i < pathArray.length; i++) { var item = pathArray[i]; preSegment = new PathSegment(item, preSegment, i === count - 1); segments.push(preSegment); } return segments; } function _addCustomizedArrow(ctx, attrs, x1, y1, x2, y2, isStart) { var shape = isStart ? attrs.startArrow : attrs.endArrow; var d = shape.d; var deg = 0; var x = x2 - x1; var y = y2 - y1; var tan = Math.atan(x / y); if (y === 0 && x < 0) { deg = Math.PI; } else if (x > 0 && y > 0) { deg = Math.PI / 2 - tan; } else if (x < 0 && y < 0) { deg = -Math.PI / 2 - tan; } else if (x >= 0 && y < 0) { deg = -tan - Math.PI / 2; } else if (x <= 0 && y > 0) { deg = Math.PI / 2 - tan; } var path = parsePath(shape); if (!path) { return; } if (d) { if (isStart) { x2 = x2 + Math.sin(Math.abs(tan)) * d; y2 = y2 + Math.cos(Math.abs(tan)) * d - 0.5 * ctx.lineWidth; } else { x2 = x2 - Math.sin(Math.abs(tan)) * d; y2 = y2 - Math.cos(Math.abs(tan)) * d + 0.5 * ctx.lineWidth; } } ctx.save(); ctx.beginPath(); ctx.translate(x2, y2); ctx.rotate(deg); for (var i = 0; i < path.length; i++) { path[i].draw(ctx); } ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.fillStyle = ctx.strokeStyle; ctx.fill(); ctx.restore(); } module.exports = { addStartArrow: function addStartArrow(ctx, attrs, x1, y1, x2, y2) { if (typeof attrs.startArrow === 'object') { _addCustomizedArrow(ctx, attrs, x1, y1, x2, y2, true); } else if (attrs.startArrow) { _addArrow(ctx, attrs, x1, y1, x2, y2, true); } }, addEndArrow: function addEndArrow(ctx, attrs, x1, y1, x2, y2) { if (typeof attrs.endArrow === 'object') { _addCustomizedArrow(ctx, attrs, x1, y1, x2, y2, false); } else if (attrs.endArrow) { _addArrow(ctx, attrs, x1, y1, x2, y2, false); } } }; /***/ }), /* 55 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Inside = __webpack_require__(93); var Cubic = __webpack_require__(94); var Quadratic = __webpack_require__(173); var Ellipse = __webpack_require__(174); var vec3 = Util.vec3; var mat3 = Util.mat3; var ARR_CMD = ['m', 'l', 'c', 'a', 'q', 'h', 'v', 't', 's', 'z']; function toAbsolute(x, y, curPoint) { // 获取绝对坐标 return { x: curPoint.x + x, y: curPoint.y + y }; } function toSymmetry(point, center) { // 点对称 return { x: center.x + (center.x - point.x), y: center.y + (center.y - point.y) }; } function vMag(v) { return Math.sqrt(v[0] * v[0] + v[1] * v[1]); } function vRatio(u, v) { return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v)); } function vAngle(u, v) { return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v)); } function getArcParams(point1, point2, fa, fs, rx, ry, psiDeg) { var psi = Util.mod(Util.toRadian(psiDeg), Math.PI * 2); var x1 = point1.x; var y1 = point1.y; var x2 = point2.x; var y2 = point2.y; 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 diff = rx * rx * (yp * yp) + ry * ry * (xp * xp); var f = Math.sqrt((rx * rx * (ry * ry) - diff) / diff); 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 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 [point1, cx, cy, rx, ry, theta, dTheta, psi, fs]; } var PathSegment = function PathSegment(item, preSegment, isLast) { this.preSegment = preSegment; this.isLast = isLast; this.init(item, preSegment); }; Util.augment(PathSegment, { init: function init(item, preSegment) { var command = item[0]; preSegment = preSegment || { endPoint: { x: 0, y: 0 } }; var relative = ARR_CMD.indexOf(command) >= 0; // /[a-z]/.test(command); var cmd = relative ? command.toUpperCase() : command; var p = item; var point1; var point2; var point3; var point; var preEndPoint = preSegment.endPoint; var p1 = p[1]; var p2 = p[2]; switch (cmd) { default: break; case 'M': if (relative) { point = toAbsolute(p1, p2, preEndPoint); } else { point = { x: p1, y: p2 }; } this.command = 'M'; this.params = [preEndPoint, point]; this.subStart = point; this.endPoint = point; break; case 'L': if (relative) { point = toAbsolute(p1, p2, preEndPoint); } else { point = { x: p1, y: p2 }; } this.command = 'L'; this.params = [preEndPoint, point]; this.subStart = preSegment.subStart; this.endPoint = point; this.endTangent = function () { return [point.x - preEndPoint.x, point.y - preEndPoint.y]; }; this.startTangent = function () { return [preEndPoint.x - point.x, preEndPoint.y - point.y]; }; break; case 'H': if (relative) { point = toAbsolute(p1, 0, preEndPoint); } else { point = { x: p1, y: preEndPoint.y }; } this.command = 'L'; this.params = [preEndPoint, point]; this.subStart = preSegment.subStart; this.endPoint = point; this.endTangent = function () { return [point.x - preEndPoint.x, point.y - preEndPoint.y]; }; this.startTangent = function () { return [preEndPoint.x - point.x, preEndPoint.y - point.y]; }; break; case 'V': if (relative) { point = toAbsolute(0, p1, preEndPoint); } else { point = { x: preEndPoint.x, y: p1 }; } this.command = 'L'; this.params = [preEndPoint, point]; this.subStart = preSegment.subStart; this.endPoint = point; this.endTangent = function () { return [point.x - preEndPoint.x, point.y - preEndPoint.y]; }; this.startTangent = function () { return [preEndPoint.x - point.x, preEndPoint.y - point.y]; }; break; case 'Q': if (relative) { point1 = toAbsolute(p1, p2, preEndPoint); point2 = toAbsolute(p[3], p[4], preEndPoint); } else { point1 = { x: p1, y: p2 }; point2 = { x: p[3], y: p[4] }; } this.command = 'Q'; this.params = [preEndPoint, point1, point2]; this.subStart = preSegment.subStart; this.endPoint = point2; this.endTangent = function () { return [point2.x - point1.x, point2.y - point1.y]; }; this.startTangent = function () { return [preEndPoint.x - point1.x, preEndPoint.y - point1.y]; }; break; case 'T': if (relative) { point2 = toAbsolute(p1, p2, preEndPoint); } else { point2 = { x: p1, y: p2 }; } if (preSegment.command === 'Q') { point1 = toSymmetry(preSegment.params[1], preEndPoint); this.command = 'Q'; this.params = [preEndPoint, point1, point2]; this.subStart = preSegment.subStart; this.endPoint = point2; this.endTangent = function () { return [point2.x - point1.x, point2.y - point1.y]; }; this.startTangent = function () { return [preEndPoint.x - point1.x, preEndPoint.y - point1.y]; }; } else { this.command = 'TL'; this.params = [preEndPoint, point2]; this.subStart = preSegment.subStart; this.endPoint = point2; this.endTangent = function () { return [point2.x - preEndPoint.x, point2.y - preEndPoint.y]; }; this.startTangent = function () { return [preEndPoint.x - point2.x, preEndPoint.y - point2.y]; }; } break; case 'C': if (relative) { point1 = toAbsolute(p1, p2, preEndPoint); point2 = toAbsolute(p[3], p[4], preEndPoint); point3 = toAbsolute(p[5], p[6], preEndPoint); } else { point1 = { x: p1, y: p2 }; point2 = { x: p[3], y: p[4] }; point3 = { x: p[5], y: p[6] }; } this.command = 'C'; this.params = [preEndPoint, point1, point2, point3]; this.subStart = preSegment.subStart; this.endPoint = point3; this.endTangent = function () { return [point3.x - point2.x, point3.y - point2.y]; }; this.startTangent = function () { return [preEndPoint.x - point1.x, preEndPoint.y - point1.y]; }; break; case 'S': if (relative) { point2 = toAbsolute(p1, p2, preEndPoint); point3 = toAbsolute(p[3], p[4], preEndPoint); } else { point2 = { x: p1, y: p2 }; point3 = { x: p[3], y: p[4] }; } if (preSegment.command === 'C') { point1 = toSymmetry(preSegment.params[2], preEndPoint); this.command = 'C'; this.params = [preEndPoint, point1, point2, point3]; this.subStart = preSegment.subStart; this.endPoint = point3; this.endTangent = function () { return [point3.x - point2.x, point3.y - point2.y]; }; this.startTangent = function () { return [preEndPoint.x - point1.x, preEndPoint.y - point1.y]; }; } else { this.command = 'SQ'; this.params = [preEndPoint, point2, point3]; this.subStart = preSegment.subStart; this.endPoint = point3; this.endTangent = function () { return [point3.x - point2.x, point3.y - point2.y]; }; this.startTangent = function () { return [preEndPoint.x - point2.x, preEndPoint.y - point2.y]; }; } break; case 'A': { var rx = p1; var ry = p2; var psi = p[3]; var fa = p[4]; var fs = p[5]; if (relative) { point = toAbsolute(p[6], p[7], preEndPoint); } else { point = { x: p[6], y: p[7] }; } this.command = 'A'; var params = getArcParams(preEndPoint, point, fa, fs, rx, ry, psi); this.params = params; var start = preSegment.subStart; this.subStart = start; this.endPoint = point; var startAngle = params[5] % (Math.PI * 2); if (Util.isNumberEqual(startAngle, Math.PI * 2)) { startAngle = 0; } var endAngle = params[6] % (Math.PI * 2); if (Util.isNumberEqual(endAngle, Math.PI * 2)) { endAngle = 0; } var d = 0.001; this.startTangent = function () { if (fs === 0) { d *= -1; } var dx = params[3] * Math.cos(startAngle - d) + params[1]; var dy = params[4] * Math.sin(startAngle - d) + params[2]; return [dx - start.x, dy - start.y]; }; this.endTangent = function () { var endAngle = params[6]; if (endAngle - Math.PI * 2 < 0.0001) { endAngle = 0; } var dx = params[3] * Math.cos(startAngle + endAngle + d) + params[1]; var dy = params[4] * Math.sin(startAngle + endAngle - d) + params[2]; return [preEndPoint.x - dx, preEndPoint.y - dy]; }; break; } case 'Z': { this.command = 'Z'; this.params = [preEndPoint, preSegment.subStart]; this.subStart = preSegment.subStart; this.endPoint = preSegment.subStart; } } }, isInside: function isInside(x, y, lineWidth) { var self = this; var command = self.command; var params = self.params; var box = self.box; if (box) { if (!Inside.box(box.minX, box.maxX, box.minY, box.maxY, x, y)) { return false; } } switch (command) { default: break; case 'M': return false; case 'TL': case 'L': case 'Z': return Inside.line(params[0].x, params[0].y, params[1].x, params[1].y, lineWidth, x, y); case 'SQ': case 'Q': return Inside.quadraticline(params[0].x, params[0].y, params[1].x, params[1].y, params[2].x, params[2].y, lineWidth, x, y); case 'C': { return Inside.cubicline(params[0].x, params[0].y, params[1].x, params[1].y, params[2].x, params[2].y, params[3].x, params[3].y, lineWidth, x, y); } case 'A': { var p = params; var cx = p[1]; var cy = p[2]; var rx = p[3]; var ry = p[4]; var theta = p[5]; var dTheta = p[6]; var psi = p[7]; var fs = p[8]; var r = rx > ry ? rx : ry; var scaleX = rx > ry ? 1 : rx / ry; var scaleY = rx > ry ? ry / rx : 1; p = [x, y, 1]; var m = [1, 0, 0, 0, 1, 0, 0, 0, 1]; mat3.translate(m, m, [-cx, -cy]); mat3.rotate(m, m, -psi); mat3.scale(m, m, [1 / scaleX, 1 / scaleY]); vec3.transformMat3(p, p, m); return Inside.arcline(0, 0, r, theta, theta + dTheta, 1 - fs, lineWidth, p[0], p[1]); } } return false; }, draw: function draw(context) { var command = this.command; var params = this.params; var point1; var point2; var point3; switch (command) { default: break; case 'M': context.moveTo(params[1].x, params[1].y); break; case 'TL': case 'L': context.lineTo(params[1].x, params[1].y); break; case 'SQ': case 'Q': point1 = params[1]; point2 = params[2]; context.quadraticCurveTo(point1.x, point1.y, point2.x, point2.y); break; case 'C': point1 = params[1]; point2 = params[2]; point3 = params[3]; context.bezierCurveTo(point1.x, point1.y, point2.x, point2.y, point3.x, point3.y); break; case 'A': { var p = params; var p1 = p[1]; var p2 = p[2]; var cx = p1; var cy = p2; var rx = p[3]; var ry = p[4]; var theta = p[5]; var dTheta = p[6]; var psi = p[7]; var fs = p[8]; 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': context.closePath(); break; } }, getBBox: function getBBox(lineWidth) { var halfWidth = lineWidth / 2; var params = this.params; var yDims; var xDims; var i; var l; switch (this.command) { default: case 'M': case 'Z': break; case 'TL': case 'L': this.box = { minX: Math.min(params[0].x, params[1].x) - halfWidth, maxX: Math.max(params[0].x, params[1].x) + halfWidth, minY: Math.min(params[0].y, params[1].y) - halfWidth, maxY: Math.max(params[0].y, params[1].y) + halfWidth }; break; case 'SQ': case 'Q': xDims = Quadratic.extrema(params[0].x, params[1].x, params[2].x); for (i = 0, l = xDims.length; i < l; i++) { xDims[i] = Quadratic.at(params[0].x, params[1].x, params[2].x, xDims[i]); } xDims.push(params[0].x, params[2].x); yDims = Quadratic.extrema(params[0].y, params[1].y, params[2].y); for (i = 0, l = yDims.length; i < l; i++) { yDims[i] = Quadratic.at(params[0].y, params[1].y, params[2].y, yDims); } yDims.push(params[0].y, params[2].y); this.box = { minX: Math.min.apply(Math, xDims) - halfWidth, maxX: Math.max.apply(Math, xDims) + halfWidth, minY: Math.min.apply(Math, yDims) - halfWidth, maxY: Math.max.apply(Math, yDims) + halfWidth }; break; case 'C': xDims = Cubic.extrema(params[0].x, params[1].x, params[2].x, params[3].x); for (i = 0, l = xDims.length; i < l; i++) { xDims[i] = Cubic.at(params[0].x, params[1].x, params[2].x, params[3].x, xDims[i]); } yDims = Cubic.extrema(params[0].y, params[1].y, params[2].y, params[3].y); for (i = 0, l = yDims.length; i < l; i++) { yDims[i] = Cubic.at(params[0].y, params[1].y, params[2].y, params[3].y, yDims[i]); } xDims.push(params[0].x, params[3].x); yDims.push(params[0].y, params[3].y); this.box = { minX: Math.min.apply(Math, xDims) - halfWidth, maxX: Math.max.apply(Math, xDims) + halfWidth, minY: Math.min.apply(Math, yDims) - halfWidth, maxY: Math.max.apply(Math, yDims) + halfWidth }; break; case 'A': { // todo 待优化 var p = params; var cx = p[1]; var cy = p[2]; var rx = p[3]; var ry = p[4]; var theta = p[5]; var dTheta = p[6]; var psi = p[7]; var fs = p[8]; var start = theta; var end = theta + dTheta; var xDim = Ellipse.xExtrema(psi, rx, ry); var minX = Infinity; var maxX = -Infinity; var xs = [start, end]; for (i = -Math.PI * 2; i <= Math.PI * 2; i += Math.PI) { var xAngle = xDim + i; if (fs === 1) { if (start < xAngle && xAngle < end) { xs.push(xAngle); } } else { if (end < xAngle && xAngle < start) { xs.push(xAngle); } } } for (i = 0, l = xs.length; i < l; i++) { var x = Ellipse.xAt(psi, rx, ry, cx, xs[i]); if (x < minX) { minX = x; } if (x > maxX) { maxX = x; } } var yDim = Ellipse.yExtrema(psi, rx, ry); var minY = Infinity; var maxY = -Infinity; var ys = [start, end]; for (i = -Math.PI * 2; i <= Math.PI * 2; i += Math.PI) { var yAngle = yDim + i; if (fs === 1) { if (start < yAngle && yAngle < end) { ys.push(yAngle); } } else { if (end < yAngle && yAngle < start) { ys.push(yAngle); } } } for (i = 0, l = ys.length; i < l; i++) { var y = Ellipse.yAt(psi, rx, ry, cy, ys[i]); if (y < minY) { minY = y; } if (y > maxY) { maxY = y; } } this.box = { minX: minX - halfWidth, maxX: maxX + halfWidth, minY: minY - halfWidth, maxY: maxY + halfWidth }; break; } } } }); module.exports = PathSegment; /***/ }), /* 56 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; 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; } /** * @fileOverview the base class of Coordinate * @author sima.zhang */ var MatrixUtil = __webpack_require__(50); var mix = __webpack_require__(10); var mat3 = MatrixUtil.mat3; var vec3 = MatrixUtil.vec3; var Coord = /*#__PURE__*/function () { _createClass(Coord, [{ key: "getDefaultCfg", /** * 获取默认的配置属性 * @protected * @return {Object} 默认属性 */ value: function getDefaultCfg() { return { /** * Mark x y is transposed. * @type {Boolean} */ isTransposed: false, /** * The matrix of coordinate * @type {Array} */ matrix: [1, 0, 0, 0, 1, 0, 0, 0, 1] }; } }]); function Coord(cfg) { _classCallCheck(this, Coord); var defaultCfg = this.getDefaultCfg(); mix(this, defaultCfg, cfg); this.init(); } _createClass(Coord, [{ key: "init", value: function init() { var start = this.start; var end = this.end; var center = { x: (start.x + end.x) / 2, y: (start.y + end.y) / 2 }; this.center = center; this.width = Math.abs(end.x - start.x); this.height = Math.abs(end.y - start.y); } }, { key: "_swapDim", value: function _swapDim(dim) { var dimRange = this[dim]; if (dimRange) { var tmp = dimRange.start; dimRange.start = dimRange.end; dimRange.end = tmp; } } }, { key: "getCenter", value: function getCenter() { return this.center; } }, { key: "getWidth", value: function getWidth() { return this.width; } }, { key: "getHeight", value: function getHeight() { return this.height; } }, { key: "convertDim", value: function convertDim(percent, dim) { var _this$dim = this[dim], start = _this$dim.start, end = _this$dim.end; return start + percent * (end - start); } }, { key: "invertDim", value: function invertDim(value, dim) { var _this$dim2 = this[dim], start = _this$dim2.start, end = _this$dim2.end; return (value - start) / (end - start); } /** * 将归一化的坐标点数据转换为画布坐标 * @override * @param {Object} point 归一化的坐标点 * @return {Object} 返回画布坐标 */ }, { key: "convertPoint", value: function convertPoint(point) { return point; } /** * 将画布坐标转换为归一化的坐标点数据 * @override * @param {Object} point 画布坐标点数据 * @return {Object} 归一化后的数据点 */ }, { key: "invertPoint", value: function invertPoint(point) { return point; } /** * 将坐标点进行矩阵变换 * @param {Number} x 对应 x 轴画布坐标 * @param {Number} y 对应 y 轴画布坐标 * @param {Number} tag 默认为 0,可取值 0, 1 * @return {Array} 返回变换后的三阶向量 [x, y, z] */ }, { key: "applyMatrix", value: function applyMatrix(x, y) { var tag = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var matrix = this.matrix; var vector = [x, y, tag]; vec3.transformMat3(vector, vector, matrix); return vector; } /** * 将坐标点进行矩阵逆变换 * @param {Number} x 对应 x 轴画布坐标 * @param {Number} y 对应 y 轴画布坐标 * @param {Number} tag 默认为 0,可取值 0, 1 * @return {Array} 返回矩阵逆变换后的三阶向量 [x, y, z] */ }, { key: "invertMatrix", value: function invertMatrix(x, y) { var tag = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 0; var matrix = this.matrix; var inversedMatrix = mat3.invert([], matrix); var vector = [x, y, tag]; vec3.transformMat3(vector, vector, inversedMatrix); return vector; } /** * 将归一化的坐标点数据转换为画布坐标,并根据坐标系当前矩阵进行变换 * @param {Object} point 归一化的坐标点 * @return {Object} 返回进行矩阵变换后的画布坐标 */ }, { key: "convert", value: function convert(point) { var _this$convertPoint = this.convertPoint(point), x = _this$convertPoint.x, y = _this$convertPoint.y; var vector = this.applyMatrix(x, y, 1); return { x: vector[0], y: vector[1] }; } /** * 将进行过矩阵变换画布坐标转换为归一化坐标 * @param {Object} point 画布坐标 * @return {Object} 返回归一化的坐标点 */ }, { key: "invert", value: function invert(point) { var vector = this.invertMatrix(point.x, point.y, 1); return this.invertPoint({ x: vector[0], y: vector[1] }); } /** * 坐标系旋转变换 * @param {Number} radian 旋转弧度 * @return {Object} 返回坐标系对象 */ }, { key: "rotate", value: function rotate(radian) { var matrix = this.matrix; var center = this.center; mat3.translate(matrix, matrix, [-center.x, -center.y]); mat3.rotate(matrix, matrix, radian); mat3.translate(matrix, matrix, [center.x, center.y]); return this; } /** * 坐标系反射变换 * @param {String} dim 反射维度 * @return {Object} 返回坐标系对象 */ }, { key: "reflect", value: function reflect(dim) { switch (dim) { case 'x': this._swapDim('x'); break; case 'y': this._swapDim('y'); break; default: this._swapDim('y'); } return this; } /** * 坐标系比例变换 * @param {Number} s1 x 方向缩放比例 * @param {Number} s2 y 方向缩放比例 * @return {Object} 返回坐标系对象 */ }, { key: "scale", value: function scale(s1, s2) { var matrix = this.matrix; var center = this.center; mat3.translate(matrix, matrix, [-center.x, -center.y]); mat3.scale(matrix, matrix, [s1, s2]); mat3.translate(matrix, matrix, [center.x, center.y]); return this; } /** * 坐标系平移变换 * @param {Number} x x 方向平移像素 * @param {Number} y y 方向平移像素 * @return {Object} 返回坐标系对象 */ }, { key: "translate", value: function translate(x, y) { var matrix = this.matrix; mat3.translate(matrix, matrix, [x, y]); return this; } /** * 将坐标系 x y 两个轴进行转置 * @return {Object} 返回坐标系对象 */ }, { key: "transpose", value: function transpose() { this.isTransposed = !this.isTransposed; return this; } }]); return Coord; }(); module.exports = Coord; /***/ }), /* 57 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview shape 的辅助方法 * @author dxq613@gmail.com */ var Util = __webpack_require__(0); var ShapeUtil = { splitPoints: function splitPoints(obj) { var points = []; var x = obj.x; var y = obj.y; y = Util.isArray(y) ? y : [y]; Util.each(y, function (yItem, index) { var point = { x: Util.isArray(x) ? x[index] : x, y: yItem }; points.push(point); }); return points; }, addFillAttrs: function addFillAttrs(attrs, cfg) { if (cfg.color) { attrs.fill = cfg.color; } if (Util.isNumber(cfg.opacity)) { attrs.opacity = attrs.fillOpacity = cfg.opacity; } }, addStrokeAttrs: function addStrokeAttrs(attrs, cfg) { if (cfg.color) { attrs.stroke = cfg.color; } if (Util.isNumber(cfg.opacity)) { attrs.opacity = attrs.strokeOpacity = cfg.opacity; } } }; module.exports = ShapeUtil; /***/ }), /* 58 */, /* 59 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { isFunction: __webpack_require__(13), isObject: __webpack_require__(22), isBoolean: __webpack_require__(60), isNil: __webpack_require__(6), isString: __webpack_require__(12), isArray: __webpack_require__(5), isNumber: __webpack_require__(11), isEmpty: __webpack_require__(61), // isBlank uniqueId: __webpack_require__(62), clone: __webpack_require__(39), deepMix: __webpack_require__(27), assign: __webpack_require__(10), // simpleMix merge: __webpack_require__(27), // mix upperFirst: __webpack_require__(64), // ucfirst each: __webpack_require__(3), isEqual: __webpack_require__(40), toArray: __webpack_require__(29), extend: __webpack_require__(65), augment: __webpack_require__(66), remove: __webpack_require__(67), isNumberEqual: __webpack_require__(30), toRadian: __webpack_require__(68), toDegree: __webpack_require__(69), mod: __webpack_require__(70), clamp: __webpack_require__(41), createDom: __webpack_require__(71), modifyCSS: __webpack_require__(72), requestAnimationFrame: __webpack_require__(73), getRatio: function getRatio() { return window.devicePixelRatio ? window.devicePixelRatio : 2; }, mat3: __webpack_require__(42), vec2: __webpack_require__(75), vec3: __webpack_require__(76), transform: __webpack_require__(77) }; /***/ }), /* 60 */ /***/ (function(module, exports, __webpack_require__) { /** * 是否是布尔类型 * * @param {Object} value 测试的值 * @return {Boolean} */ var isType = __webpack_require__(14); var isBoolean = function isBoolean(value) { return isType(value, 'Boolean'); }; module.exports = isBoolean; /***/ }), /* 61 */ /***/ (function(module, exports, __webpack_require__) { var isNil = __webpack_require__(6); var isArrayLike = __webpack_require__(15); var getType = __webpack_require__(113); var isPrototype = __webpack_require__(114); var hasOwnProperty = Object.prototype.hasOwnProperty; function isEmpty(value) { /** * isEmpty(null) => true * isEmpty() => true * isEmpty(true) => true * isEmpty(1) => true * isEmpty([1, 2, 3]) => false * isEmpty('abc') => false * isEmpty({ a: 1 }) => false */ if (isNil(value)) { return true; } if (isArrayLike(value)) { return !value.length; } var type = getType(value); if (type === 'Map' || type === 'Set') { return !value.size; } if (isPrototype(value)) { return !Object.keys(value).length; } for (var key in value) { if (hasOwnProperty.call(value, key)) { return false; } } return true; } module.exports = isEmpty; /***/ }), /* 62 */ /***/ (function(module, exports) { var uniqueId = function () { var map = {}; return function (prefix) { prefix = prefix || 'g'; if (!map[prefix]) { map[prefix] = 1; } else { map[prefix] += 1; } return prefix + map[prefix]; }; }(); module.exports = uniqueId; /***/ }), /* 63 */ /***/ (function(module, exports) { var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var isObjectLike = function isObjectLike(value) { /** * isObjectLike({}) => true * isObjectLike([1, 2, 3]) => true * isObjectLike(Function) => false * isObjectLike(null) => false */ return (typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value !== null; }; module.exports = isObjectLike; /***/ }), /* 64 */ /***/ (function(module, exports, __webpack_require__) { var toString = __webpack_require__(26); var upperFirst = function upperFirst(value) { var str = toString(value); return str.charAt(0).toUpperCase() + str.substring(1); }; module.exports = upperFirst; /***/ }), /* 65 */ /***/ (function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(13); var mix = __webpack_require__(10); var extend = function extend(subclass, superclass, overrides, staticOverrides) { // 如果只提供父类构造函数,则自动生成子类构造函数 if (!isFunction(superclass)) { overrides = superclass; superclass = subclass; subclass = function subclass() {}; } var create = Object.create ? function (proto, c) { return Object.create(proto, { constructor: { value: c } }); } : function (proto, c) { function Tmp() {} Tmp.prototype = proto; var o = new Tmp(); o.constructor = c; return o; }; var superObj = create(superclass.prototype, subclass); // new superclass(),//实例化父类作为子类的prototype subclass.prototype = mix(superObj, subclass.prototype); // 指定子类的prototype subclass.superclass = create(superclass.prototype, superclass); mix(superObj, overrides); mix(subclass, staticOverrides); return subclass; }; module.exports = extend; /***/ }), /* 66 */ /***/ (function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(13); var toArray = __webpack_require__(29); var mix = __webpack_require__(10); var augment = function augment(c) { var args = toArray(arguments); for (var i = 1; i < args.length; i++) { var obj = args[i]; if (isFunction(obj)) { obj = obj.prototype; } mix(c.prototype, obj); } }; module.exports = augment; /***/ }), /* 67 */ /***/ (function(module, exports) { var arrPrototype = Array.prototype; var splice = arrPrototype.splice; var indexOf = arrPrototype.indexOf; var slice = arrPrototype.slice; var pull = function pull(arr) { var values = slice.call(arguments, 1); for (var i = 0; i < values.length; i++) { var value = values[i]; var fromIndex = -1; while ((fromIndex = indexOf.call(arr, value)) > -1) { splice.call(arr, fromIndex, 1); } } return arr; }; module.exports = pull; /***/ }), /* 68 */ /***/ (function(module, exports) { var RADIAN = Math.PI / 180; var toRadian = function toRadian(degree) { return RADIAN * degree; }; module.exports = toRadian; /***/ }), /* 69 */ /***/ (function(module, exports) { var DEGREE = 180 / Math.PI; var toDegree = function toDegree(radian) { return DEGREE * radian; }; module.exports = toDegree; /***/ }), /* 70 */ /***/ (function(module, exports) { var mod = function mod(n, m) { return (n % m + m) % m; }; module.exports = mod; /***/ }), /* 71 */ /***/ (function(module, exports) { /** * 创建DOM 节点 * @param {String} str Dom 字符串 * @return {HTMLElement} DOM 节点 */ var TABLE = document.createElement('table'); var TABLE_TR = document.createElement('tr'); var FRAGMENT_REG = /^\s*<(\w+|!)[^>]*>/; var CONTAINERS = { tr: document.createElement('tbody'), tbody: TABLE, thead: TABLE, tfoot: TABLE, td: TABLE_TR, th: TABLE_TR, '*': document.createElement('div') }; module.exports = function createDom(str) { var name = FRAGMENT_REG.test(str) && RegExp.$1; if (!(name in CONTAINERS)) { name = '*'; } var container = CONTAINERS[name]; str = str.replace(/(^\s*)|(\s*$)/g, ''); container.innerHTML = '' + str; var dom = container.childNodes[0]; container.removeChild(dom); return dom; }; /***/ }), /* 72 */ /***/ (function(module, exports) { module.exports = function modifyCSS(dom, css) { if (dom) { for (var key in css) { if (css.hasOwnProperty(key)) { dom.style[key] = css[key]; } } } return dom; }; /***/ }), /* 73 */ /***/ (function(module, exports) { module.exports = function requestAnimationFrame(fn) { var method = window.requestAnimationFrame || window.webkitRequestAnimationFrame || function (fn) { return setTimeout(fn, 16); }; return method(fn); }; /***/ }), /* 74 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.setMatrixArrayType = setMatrixArrayType; exports.toRadian = toRadian; exports.equals = equals; /** * Common utilities * @module glMatrix */ // Configuration Constants var EPSILON = exports.EPSILON = 0.000001; var ARRAY_TYPE = exports.ARRAY_TYPE = typeof Float32Array !== 'undefined' ? Float32Array : Array; var RANDOM = exports.RANDOM = Math.random; /** * Sets the type of array used when creating new vectors and matrices * * @param {Type} type Array type, such as Float32Array or Array */ function setMatrixArrayType(type) { exports.ARRAY_TYPE = ARRAY_TYPE = type; } var degree = Math.PI / 180; /** * Convert Degree To Radian * * @param {Number} a Angle in Degrees */ function toRadian(a) { return a * degree; } /** * Tests whether or not the arguments have approximately the same value, within an absolute * or relative tolerance of glMatrix.EPSILON (an absolute tolerance is used for values less * than or equal to 1.0, and a relative tolerance is used for larger values) * * @param {Number} a The first number to test. * @param {Number} b The second number to test. * @returns {Boolean} True if the numbers are approximately equal, false otherwise. */ function equals(a, b) { return Math.abs(a - b) <= EPSILON * Math.max(1.0, Math.abs(a), Math.abs(b)); } /***/ }), /* 75 */ /***/ (function(module, exports, __webpack_require__) { var vec2 = __webpack_require__(219); var clamp = __webpack_require__(41); vec2.angle = function (v1, v2) { var theta = vec2.dot(v1, v2) / (vec2.length(v1) * vec2.length(v2)); return Math.acos(clamp(theta, -1, 1)); }; /** * 向量 v1 到 向量 v2 夹角的方向 * @param {Array} v1 向量 * @param {Array} v2 向量 * @return {Boolean} >= 0 顺时针 < 0 逆时针 */ vec2.direction = function (v1, v2) { return v1[0] * v2[1] - v2[0] * v1[1]; }; vec2.angleTo = function (v1, v2, direct) { var angle = vec2.angle(v1, v2); var angleLargeThanPI = vec2.direction(v1, v2) >= 0; if (direct) { if (angleLargeThanPI) { return Math.PI * 2 - angle; } return angle; } if (angleLargeThanPI) { return angle; } return Math.PI * 2 - angle; }; vec2.vertical = function (out, v, flag) { if (flag) { out[0] = v[1]; out[1] = -1 * v[0]; } else { out[0] = -1 * v[1]; out[1] = v[0]; } return out; }; module.exports = vec2; /***/ }), /* 76 */ /***/ (function(module, exports, __webpack_require__) { var vec3 = __webpack_require__(220); module.exports = vec3; /***/ }), /* 77 */ /***/ (function(module, exports, __webpack_require__) { var clone = __webpack_require__(39); var each = __webpack_require__(3); var mat3 = __webpack_require__(42); module.exports = function transform(m, ts) { m = clone(m); each(ts, function (t) { switch (t[0]) { case 't': mat3.translate(m, m, [t[1], t[2]]); break; case 's': mat3.scale(m, m, [t[1], t[2]]); break; case 'r': mat3.rotate(m, m, t[1]); break; case 'm': mat3.multiply(m, m, t[1]); break; default: return false; } }); return m; }; /***/ }), /* 78 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Event = function Event(type, event, bubbles, cancelable) { this.type = type; // 事件类型 this.target = null; // 目标 this.currentTarget = null; // 当前目标 this.bubbles = bubbles; // 冒泡 this.cancelable = cancelable; // 是否能够阻止 this.timeStamp = new Date().getTime(); // 时间戳 this.defaultPrevented = false; // 阻止默认 this.propagationStopped = false; // 阻止冒泡 this.removed = false; // 是否被移除 this.event = event; // 触发的原生事件 }; Util.augment(Event, { preventDefault: function preventDefault() { this.defaultPrevented = this.cancelable && true; }, stopPropagation: function stopPropagation() { this.propagationStopped = true; }, remove: function remove() { this.remove = true; }, clone: function clone() { return Util.clone(this); }, toString: function toString() { return '[Event (type=' + this.type + ')]'; } }); module.exports = Event; /***/ }), /* 79 */ /***/ (function(module, exports, __webpack_require__) { var Line = __webpack_require__(43); var Quadratic = __webpack_require__(118); var Cubic = __webpack_require__(80); var Arc = __webpack_require__(44); module.exports = { line: function line(x1, y1, x2, y2, lineWidth, x, y) { var box = Line.box(x1, y1, x2, y2, lineWidth); if (!this.box(box.minX, box.maxX, box.minY, box.maxY, x, y)) { return false; } var d = Line.pointDistance(x1, y1, x2, y2, x, y); if (isNaN(d)) { return false; } return d <= lineWidth / 2; }, polyline: function polyline(points, lineWidth, x, y) { var l = points.length - 1; if (l < 1) { return false; } for (var i = 0; i < l; i++) { var x1 = points[i][0]; var y1 = points[i][1]; var x2 = points[i + 1][0]; var y2 = points[i + 1][1]; if (this.line(x1, y1, x2, y2, lineWidth, x, y)) { return true; } } return false; }, cubicline: function cubicline(x1, y1, x2, y2, x3, y3, x4, y4, lineWidth, x, y) { return Cubic.pointDistance(x1, y1, x2, y2, x3, y3, x4, y4, x, y) <= lineWidth / 2; }, quadraticline: function quadraticline(x1, y1, x2, y2, x3, y3, lineWidth, x, y) { return Quadratic.pointDistance(x1, y1, x2, y2, x3, y3, x, y) <= lineWidth / 2; }, arcline: function arcline(cx, cy, r, startAngle, endAngle, clockwise, lineWidth, x, y) { return Arc.pointDistance(cx, cy, r, startAngle, endAngle, clockwise, x, y) <= lineWidth / 2; }, rect: function rect(rx, ry, width, height, x, y) { return rx <= x && x <= rx + width && ry <= y && y <= ry + height; }, circle: function circle(cx, cy, r, x, y) { return Math.pow(x - cx, 2) + Math.pow(y - cy, 2) <= Math.pow(r, 2); }, box: function box(minX, maxX, minY, maxY, x, y) { return minX <= x && x <= maxX && minY <= y && y <= maxY; } }; /***/ }), /* 80 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var vec2 = Util.vec2; function cubicAt(p0, p1, p2, p3, t) { var onet = 1 - t; return onet * onet * (onet * p3 + 3 * t * p2) + t * t * (t * p0 + 3 * onet * p1); } function cubicDerivativeAt(p0, p1, p2, p3, t) { var onet = 1 - t; return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet + (p3 - p2) * t * t); } function cubicProjectPoint(x1, y1, x2, y2, x3, y3, x4, y4, x, y, out) { var t; var interval = 0.005; var d = Infinity; var _t; var v1; var d1; var d2; var v2; var prev; var next; var EPSILON = 0.0001; var v0 = [x, y]; for (_t = 0; _t < 1; _t += 0.05) { v1 = [cubicAt(x1, x2, x3, x4, _t), cubicAt(y1, y2, y3, y4, _t)]; d1 = vec2.squaredDistance(v0, v1); if (d1 < d) { t = _t; d = d1; } } d = Infinity; for (var i = 0; i < 32; i++) { if (interval < EPSILON) { break; } prev = t - interval; next = t + interval; v1 = [cubicAt(x1, x2, x3, x4, prev), cubicAt(y1, y2, y3, y4, prev)]; d1 = vec2.squaredDistance(v0, v1); if (prev >= 0 && d1 < d) { t = prev; d = d1; } else { v2 = [cubicAt(x1, x2, x3, x4, next), cubicAt(y1, y2, y3, y4, next)]; d2 = vec2.squaredDistance(v0, v2); if (next <= 1 && d2 < d) { t = next; d = d2; } else { interval *= 0.5; } } } if (out) { out.x = cubicAt(x1, x2, x3, x4, t); out.y = cubicAt(y1, y2, y3, y4, t); } return Math.sqrt(d); } function cubicExtrema(p0, p1, p2, p3) { var a = 3 * p0 - 9 * p1 + 9 * p2 - 3 * p3; var b = 6 * p1 - 12 * p2 + 6 * p3; var c = 3 * p2 - 3 * p3; var extrema = []; var t1; var t2; var discSqrt; if (Util.isNumberEqual(a, 0)) { if (!Util.isNumberEqual(b, 0)) { t1 = -c / b; if (t1 >= 0 && t1 <= 1) { extrema.push(t1); } } } else { var disc = b * b - 4 * a * c; if (Util.isNumberEqual(disc, 0)) { extrema.push(-b / (2 * a)); } else if (disc > 0) { discSqrt = Math.sqrt(disc); t1 = (-b + discSqrt) / (2 * a); t2 = (-b - discSqrt) / (2 * a); if (t1 >= 0 && t1 <= 1) { extrema.push(t1); } if (t2 >= 0 && t2 <= 1) { extrema.push(t2); } } } return extrema; } function base3(t, p1, p2, p3, p4) { var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4; var t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; return t * t2 - 3 * p1 + 3 * p2; } function cubiclLen(x1, y1, x2, y2, x3, y3, x4, y4, z) { if (Util.isNil(z)) { z = 1; } z = z > 1 ? 1 : z < 0 ? 0 : z; var z2 = z / 2; var n = 12; var Tvalues = [-0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699, -0.9041, 0.9041, -0.9816, 0.9816]; var Cvalues = [0.2491, 0.2491, 0.2335, 0.2335, 0.2032, 0.2032, 0.1601, 0.1601, 0.1069, 0.1069, 0.0472, 0.0472]; var sum = 0; for (var i = 0; i < n; i++) { var ct = z2 * Tvalues[i] + z2; var xbase = base3(ct, x1, x2, x3, x4); var ybase = base3(ct, y1, y2, y3, y4); var comb = xbase * xbase + ybase * ybase; sum += Cvalues[i] * Math.sqrt(comb); } return z2 * sum; } module.exports = { at: cubicAt, derivativeAt: cubicDerivativeAt, projectPoint: function projectPoint(x1, y1, x2, y2, x3, y3, x4, y4, x, y) { var rst = {}; cubicProjectPoint(x1, y1, x2, y2, x3, y3, x4, y4, x, y, rst); return rst; }, pointDistance: cubicProjectPoint, extrema: cubicExtrema, len: cubiclLen }; /***/ }), /* 81 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Shape = __webpack_require__(7); var Format = __webpack_require__(31); var PathSegment = __webpack_require__(46); var Marker = function Marker(cfg) { Marker.superclass.constructor.call(this, cfg); }; Marker.Symbols = { // 圆 circle: function circle(x, y, r) { return [['M', x, y], ['m', -r, 0], ['a', r, r, 0, 1, 0, r * 2, 0], ['a', r, r, 0, 1, 0, -r * 2, 0]]; }, // 正方形 square: function square(x, y, r) { return [['M', x - r, y - r], ['L', x + r, y - r], ['L', x + r, y + r], ['L', x - r, y + r], ['Z']]; }, // 菱形 diamond: function diamond(x, y, r) { return [['M', x - r, y], ['L', x, y - r], ['L', x + r, y], ['L', x, y + r], ['Z']]; }, // 三角形 triangle: function triangle(x, y, r) { var diffY = r * Math.sin(1 / 3 * Math.PI); return [['M', x - r, y + diffY], ['L', x, y - diffY], ['L', x + r, y + diffY], ['z']]; }, // 倒三角形 'triangle-down': function triangleDown(x, y, r) { var diffY = r * Math.sin(1 / 3 * Math.PI); return [['M', x - r, y - diffY], ['L', x + r, y - diffY], ['L', x, y + diffY], ['Z']]; } }; Marker.ATTRS = { path: null, lineWidth: 1 }; Util.extend(Marker, Shape); Util.augment(Marker, { type: 'marker', canFill: true, canStroke: true, getDefaultAttrs: function getDefaultAttrs() { return { x: 0, y: 0, lineWidth: 1 }; }, calculateBox: function calculateBox() { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var r = attrs.radius || attrs.r; var lineWidth = this.getHitLineWidth(); var halfWidth = lineWidth / 2 + r; return { minX: cx - halfWidth, minY: cy - halfWidth, maxX: cx + halfWidth, maxY: cy + halfWidth }; }, _getPath: function _getPath() { var attrs = this._attrs; var x = attrs.x; var y = attrs.y; var r = attrs.radius || attrs.r; var symbol = attrs.symbol || 'circle'; var method; if (Util.isFunction(symbol)) { method = symbol; } else { method = Marker.Symbols[symbol]; } if (!method) { console.warn(symbol + " marker is not supported."); return null; } return method(x, y, r); }, createPath: function createPath(context) { var segments = this._cfg.segments; if (segments && !this._cfg.hasUpdate) { context.beginPath(); for (var i = 0; i < segments.length; i++) { segments[i].draw(context); } return; } var path = Format.parsePath(this._getPath()); context.beginPath(); var preSegment; segments = []; for (var _i = 0; _i < path.length; _i++) { var item = path[_i]; preSegment = new PathSegment(item, preSegment, _i === path.length - 1); segments.push(preSegment); preSegment.draw(context); } this._cfg.segments = segments; this._cfg.hasUpdate = false; } }); module.exports = Marker; /***/ }), /* 82 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(59); var SPACES = "\t\n\x0B\f\r \xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029"; var PATH_COMMAND = new RegExp('([a-z])[' + SPACES + ',]*((-?\\d*\\.?\\d*(?:e[\\-+]?\\d+)?[' + SPACES + ']*,?[' + SPACES + ']*)+)', 'ig'); var PATH_VALUES = new RegExp('(-?\\d*\\.?\\d*(?:e[\\-+]?\\d+)?)[' + SPACES + ']*,?[' + SPACES + ']*', 'ig'); // Parses given path string into an array of arrays of path segments var parsePathString = function parsePathString(pathString) { if (!pathString) { return null; } if (typeof pathString === typeof []) { return pathString; } var paramCounts = { a: 7, c: 6, o: 2, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, u: 3, z: 0 }; var data = []; String(pathString).replace(PATH_COMMAND, function (a, b, c) { var params = []; var name = b.toLowerCase(); c.replace(PATH_VALUES, function (a, b) { b && params.push(+b); }); if (name === 'm' && params.length > 2) { data.push([b].concat(params.splice(0, 2))); name = 'l'; b = b === 'm' ? 'l' : 'L'; } if (name === 'o' && params.length === 1) { data.push([b, params[0]]); } if (name === 'r') { data.push([b].concat(params)); } else { while (params.length >= paramCounts[name]) { data.push([b].concat(params.splice(0, paramCounts[name]))); if (!paramCounts[name]) { break; } } } }); return data; }; // http://schepers.cc/getting-to-the-point var catmullRom2bezier = function catmullRom2bezier(crp, z) { var d = []; for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { var p = [{ x: +crp[i - 2], y: +crp[i - 1] }, { x: +crp[i], y: +crp[i + 1] }, { x: +crp[i + 2], y: +crp[i + 3] }, { x: +crp[i + 4], y: +crp[i + 5] }]; if (z) { if (!i) { p[0] = { x: +crp[iLen - 2], y: +crp[iLen - 1] }; } else if (iLen - 4 === i) { p[3] = { x: +crp[0], y: +crp[1] }; } else if (iLen - 2 === i) { p[2] = { x: +crp[0], y: +crp[1] }; p[3] = { x: +crp[2], y: +crp[3] }; } } else { if (iLen - 4 === i) { p[3] = p[2]; } else if (!i) { p[0] = { x: +crp[i], y: +crp[i + 1] }; } } d.push(['C', (-p[0].x + 6 * p[1].x + p[2].x) / 6, (-p[0].y + 6 * p[1].y + p[2].y) / 6, (p[1].x + 6 * p[2].x - p[3].x) / 6, (p[1].y + 6 * p[2].y - p[3].y) / 6, p[2].x, p[2].y]); } return d; }; var ellipsePath = function ellipsePath(x, y, rx, ry, a) { var res = []; if (a === null && ry === null) { ry = rx; } x = +x; y = +y; rx = +rx; ry = +ry; if (a !== null) { var rad = Math.PI / 180; var x1 = x + rx * Math.cos(-ry * rad); var x2 = x + rx * Math.cos(-a * rad); var y1 = y + rx * Math.sin(-ry * rad); var y2 = y + rx * Math.sin(-a * rad); res = [['M', x1, y1], ['A', rx, rx, 0, +(a - ry > 180), 0, x2, y2]]; } else { res = [['M', x, y], ['m', 0, -ry], ['a', rx, ry, 0, 1, 1, 0, 2 * ry], ['a', rx, ry, 0, 1, 1, 0, -2 * ry], ['z']]; } return res; }; var pathToAbsolute = function pathToAbsolute(pathArray) { pathArray = parsePathString(pathArray); if (!pathArray || !pathArray.length) { return [['M', 0, 0]]; } var res = []; var x = 0; var y = 0; var mx = 0; var my = 0; var start = 0; var pa0; var dots; if (pathArray[0][0] === 'M') { x = +pathArray[0][1]; y = +pathArray[0][2]; mx = x; my = y; start++; res[0] = ['M', x, y]; } var crz = pathArray.length === 3 && pathArray[0][0] === 'M' && pathArray[1][0].toUpperCase() === 'R' && pathArray[2][0].toUpperCase() === 'Z'; for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) { res.push(r = []); pa = pathArray[i]; pa0 = pa[0]; if (pa0 !== pa0.toUpperCase()) { r[0] = pa0.toUpperCase(); switch (r[0]) { case 'A': r[1] = pa[1]; r[2] = pa[2]; r[3] = pa[3]; r[4] = pa[4]; r[5] = pa[5]; r[6] = +pa[6] + x; r[7] = +pa[7] + y; break; case 'V': r[1] = +pa[1] + y; break; case 'H': r[1] = +pa[1] + x; break; case 'R': dots = [x, y].concat(pa.slice(1)); for (var j = 2, jj = dots.length; j < jj; j++) { dots[j] = +dots[j] + x; dots[++j] = +dots[j] + y; } res.pop(); res = res.concat(catmullRom2bezier(dots, crz)); break; case 'O': res.pop(); dots = ellipsePath(x, y, pa[1], pa[2]); dots.push(dots[0]); res = res.concat(dots); break; case 'U': res.pop(); res = res.concat(ellipsePath(x, y, pa[1], pa[2], pa[3])); r = ['U'].concat(res[res.length - 1].slice(-2)); break; case 'M': mx = +pa[1] + x; my = +pa[2] + y; break; // for lint default: for (var _j = 1, _jj = pa.length; _j < _jj; _j++) { r[_j] = +pa[_j] + (_j % 2 ? x : y); } } } else if (pa0 === 'R') { dots = [x, y].concat(pa.slice(1)); res.pop(); res = res.concat(catmullRom2bezier(dots, crz)); r = ['R'].concat(pa.slice(-2)); } else if (pa0 === 'O') { res.pop(); dots = ellipsePath(x, y, pa[1], pa[2]); dots.push(dots[0]); res = res.concat(dots); } else if (pa0 === 'U') { res.pop(); res = res.concat(ellipsePath(x, y, pa[1], pa[2], pa[3])); r = ['U'].concat(res[res.length - 1].slice(-2)); } else { for (var k = 0, kk = pa.length; k < kk; k++) { r[k] = pa[k]; } } pa0 = pa0.toUpperCase(); if (pa0 !== 'O') { switch (r[0]) { case 'Z': x = +mx; y = +my; break; case 'H': x = r[1]; break; case 'V': y = r[1]; break; case 'M': mx = r[r.length - 2]; my = r[r.length - 1]; break; // for lint default: x = r[r.length - 2]; y = r[r.length - 1]; } } } return res; }; var l2c = function l2c(x1, y1, x2, y2) { return [x1, y1, x2, y2, x2, y2]; }; var q2c = function q2c(x1, y1, ax, ay, x2, y2) { var _13 = 1 / 3; var _23 = 2 / 3; return [_13 * x1 + _23 * ax, _13 * y1 + _23 * ay, _13 * x2 + _23 * ax, _13 * y2 + _23 * ay, x2, y2]; }; var a2c = function a2c(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { // for more information of where this math came from visit: // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes if (rx === ry) { rx += 1; } var _120 = Math.PI * 120 / 180; var rad = Math.PI / 180 * (+angle || 0); var res = []; var xy; var f1; var f2; var cx; var cy; var rotate = function rotate(x, y, rad) { var X = x * Math.cos(rad) - y * Math.sin(rad); var Y = x * Math.sin(rad) + y * Math.cos(rad); return { x: X, y: Y }; }; if (!recursive) { xy = rotate(x1, y1, -rad); x1 = xy.x; y1 = xy.y; xy = rotate(x2, y2, -rad); x2 = xy.x; y2 = xy.y; if (x1 === x2 && y1 === y2) { // 若弧的起始点和终点重叠则错开一点 x2 += 1; y2 += 1; } // const cos = Math.cos(Math.PI / 180 * angle); // const sin = Math.sin(Math.PI / 180 * angle); var x = (x1 - x2) / 2; var y = (y1 - y2) / 2; var h = x * x / (rx * rx) + y * y / (ry * ry); if (h > 1) { h = Math.sqrt(h); rx = h * rx; ry = h * ry; } var rx2 = rx * rx; var ry2 = ry * ry; var k = (large_arc_flag === sweep_flag ? -1 : 1) * Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))); cx = k * rx * y / ry + (x1 + x2) / 2; cy = k * -ry * x / rx + (y1 + y2) / 2; f1 = Math.asin(((y1 - cy) / ry).toFixed(9)); f2 = Math.asin(((y2 - cy) / ry).toFixed(9)); f1 = x1 < cx ? Math.PI - f1 : f1; f2 = x2 < cx ? Math.PI - f2 : f2; f1 < 0 && (f1 = Math.PI * 2 + f1); f2 < 0 && (f2 = Math.PI * 2 + f2); if (sweep_flag && f1 > f2) { f1 = f1 - Math.PI * 2; } if (!sweep_flag && f2 > f1) { f2 = f2 - Math.PI * 2; } } else { f1 = recursive[0]; f2 = recursive[1]; cx = recursive[2]; cy = recursive[3]; } var df = f2 - f1; if (Math.abs(df) > _120) { var f2old = f2; var x2old = x2; var y2old = y2; f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1); x2 = cx + rx * Math.cos(f2); y2 = cy + ry * Math.sin(f2); res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]); } df = f2 - f1; var c1 = Math.cos(f1); var s1 = Math.sin(f1); var c2 = Math.cos(f2); var s2 = Math.sin(f2); var t = Math.tan(df / 4); var hx = 4 / 3 * rx * t; var hy = 4 / 3 * ry * t; var m1 = [x1, y1]; var m2 = [x1 + hx * s1, y1 - hy * c1]; var m3 = [x2 + hx * s2, y2 - hy * c2]; var m4 = [x2, y2]; m2[0] = 2 * m1[0] - m2[0]; m2[1] = 2 * m1[1] - m2[1]; if (recursive) { return [m2, m3, m4].concat(res); } res = [m2, m3, m4].concat(res).join().split(','); var newres = []; for (var i = 0, ii = res.length; i < ii; i++) { newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; } return newres; }; var pathTocurve = function pathTocurve(path, path2) { var p = pathToAbsolute(path); var p2 = path2 && pathToAbsolute(path2); var attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }; var attrs2 = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }; var pcoms1 = []; // path commands of original path p var pcoms2 = []; // path commands of original path p2 var pfirst = ''; // temporary holder for original path command var pcom = ''; // holder for previous path command of original path var ii; var processPath = function processPath(path, d, pcom) { var nx, ny; if (!path) { return ['C', d.x, d.y, d.x, d.y, d.x, d.y]; } !(path[0] in { T: 1, Q: 1 }) && (d.qx = d.qy = null); switch (path[0]) { case 'M': d.X = path[1]; d.Y = path[2]; break; case 'A': path = ['C'].concat(a2c.apply(0, [d.x, d.y].concat(path.slice(1)))); break; case 'S': if (pcom === 'C' || pcom === 'S') { // In "S" case we have to take into account, if the previous command is C/S. nx = d.x * 2 - d.bx; // And reflect the previous ny = d.y * 2 - d.by; // command's control point relative to the current point. } else { // or some else or nothing nx = d.x; ny = d.y; } path = ['C', nx, ny].concat(path.slice(1)); break; case 'T': if (pcom === 'Q' || pcom === 'T') { // In "T" case we have to take into account, if the previous command is Q/T. d.qx = d.x * 2 - d.qx; // And make a reflection similar d.qy = d.y * 2 - d.qy; // to case "S". } else { // or something else or nothing d.qx = d.x; d.qy = d.y; } path = ['C'].concat(q2c(d.x, d.y, d.qx, d.qy, path[1], path[2])); break; case 'Q': d.qx = path[1]; d.qy = path[2]; path = ['C'].concat(q2c(d.x, d.y, path[1], path[2], path[3], path[4])); break; case 'L': path = ['C'].concat(l2c(d.x, d.y, path[1], path[2])); break; case 'H': path = ['C'].concat(l2c(d.x, d.y, path[1], d.y)); break; case 'V': path = ['C'].concat(l2c(d.x, d.y, d.x, path[1])); break; case 'Z': path = ['C'].concat(l2c(d.x, d.y, d.X, d.Y)); break; default: break; } return path; }; var fixArc = function fixArc(pp, i) { if (pp[i].length > 7) { pp[i].shift(); var pi = pp[i]; while (pi.length) { pcoms1[i] = 'A'; // if created multiple C:s, their original seg is saved p2 && (pcoms2[i] = 'A'); // the same as above pp.splice(i++, 0, ['C'].concat(pi.splice(0, 6))); } pp.splice(i, 1); ii = Math.max(p.length, p2 && p2.length || 0); } }; var fixM = function fixM(path1, path2, a1, a2, i) { if (path1 && path2 && path1[i][0] === 'M' && path2[i][0] !== 'M') { path2.splice(i, 0, ['M', a2.x, a2.y]); a1.bx = 0; a1.by = 0; a1.x = path1[i][1]; a1.y = path1[i][2]; ii = Math.max(p.length, p2 && p2.length || 0); } }; ii = Math.max(p.length, p2 && p2.length || 0); for (var i = 0; i < ii; i++) { p[i] && (pfirst = p[i][0]); // save current path command if (pfirst !== 'C') { // C is not saved yet, because it may be result of conversion pcoms1[i] = pfirst; // Save current path command i && (pcom = pcoms1[i - 1]); // Get previous path command pcom } p[i] = processPath(p[i], attrs, pcom); // Previous path command is inputted to processPath if (pcoms1[i] !== 'A' && pfirst === 'C') pcoms1[i] = 'C'; // A is the only command // which may produce multiple C:s // so we have to make sure that C is also C in original path fixArc(p, i); // fixArc adds also the right amount of A:s to pcoms1 if (p2) { // the same procedures is done to p2 p2[i] && (pfirst = p2[i][0]); if (pfirst !== 'C') { pcoms2[i] = pfirst; i && (pcom = pcoms2[i - 1]); } p2[i] = processPath(p2[i], attrs2, pcom); if (pcoms2[i] !== 'A' && pfirst === 'C') { pcoms2[i] = 'C'; } fixArc(p2, i); } fixM(p, p2, attrs, attrs2, i); fixM(p2, p, attrs2, attrs, i); var seg = p[i]; var seg2 = p2 && p2[i]; var seglen = seg.length; var seg2len = p2 && seg2.length; attrs.x = seg[seglen - 2]; attrs.y = seg[seglen - 1]; attrs.bx = parseFloat(seg[seglen - 4]) || attrs.x; attrs.by = parseFloat(seg[seglen - 3]) || attrs.y; attrs2.bx = p2 && (parseFloat(seg2[seg2len - 4]) || attrs2.x); attrs2.by = p2 && (parseFloat(seg2[seg2len - 3]) || attrs2.y); attrs2.x = p2 && seg2[seg2len - 2]; attrs2.y = p2 && seg2[seg2len - 1]; } return p2 ? [p, p2] : p; }; var p2s = /,?([a-z]),?/gi; var parsePathArray = function parsePathArray(path) { return path.join(',').replace(p2s, '$1'); }; var base3 = function base3(t, p1, p2, p3, p4) { var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4; var t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; return t * t2 - 3 * p1 + 3 * p2; }; var bezlen = function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { if (z === null) { z = 1; } z = z > 1 ? 1 : z < 0 ? 0 : z; var z2 = z / 2; var n = 12; var Tvalues = [-0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699, -0.9041, 0.9041, -0.9816, 0.9816]; var Cvalues = [0.2491, 0.2491, 0.2335, 0.2335, 0.2032, 0.2032, 0.1601, 0.1601, 0.1069, 0.1069, 0.0472, 0.0472]; var sum = 0; for (var i = 0; i < n; i++) { var ct = z2 * Tvalues[i] + z2; var xbase = base3(ct, x1, x2, x3, x4); var ybase = base3(ct, y1, y2, y3, y4); var comb = xbase * xbase + ybase * ybase; sum += Cvalues[i] * Math.sqrt(comb); } return z2 * sum; }; var curveDim = function curveDim(x0, y0, x1, y1, x2, y2, x3, y3) { var tvalues = []; var bounds = [[], []]; var a; var b; var c; var t; for (var i = 0; i < 2; ++i) { if (i === 0) { b = 6 * x0 - 12 * x1 + 6 * x2; a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3; c = 3 * x1 - 3 * x0; } else { b = 6 * y0 - 12 * y1 + 6 * y2; a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3; c = 3 * y1 - 3 * y0; } if (Math.abs(a) < 1e-12) { if (Math.abs(b) < 1e-12) { continue; } t = -c / b; if (t > 0 && t < 1) { tvalues.push(t); } continue; } var b2ac = b * b - 4 * c * a; var sqrtb2ac = Math.sqrt(b2ac); if (b2ac < 0) { continue; } var t1 = (-b + sqrtb2ac) / (2 * a); if (t1 > 0 && t1 < 1) { tvalues.push(t1); } var t2 = (-b - sqrtb2ac) / (2 * a); if (t2 > 0 && t2 < 1) { tvalues.push(t2); } } var j = tvalues.length; var jlen = j; var mt; while (j--) { t = tvalues[j]; mt = 1 - t; bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3; bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3; } bounds[0][jlen] = x0; bounds[1][jlen] = y0; bounds[0][jlen + 1] = x3; bounds[1][jlen + 1] = y3; bounds[0].length = bounds[1].length = jlen + 2; return { min: { x: Math.min.apply(0, bounds[0]), y: Math.min.apply(0, bounds[1]) }, max: { x: Math.max.apply(0, bounds[0]), y: Math.max.apply(0, bounds[1]) } }; }; var intersect = function intersect(x1, y1, x2, y2, x3, y3, x4, y4) { if (Math.max(x1, x2) < Math.min(x3, x4) || Math.min(x1, x2) > Math.max(x3, x4) || Math.max(y1, y2) < Math.min(y3, y4) || Math.min(y1, y2) > Math.max(y3, y4)) { return; } var nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4); var ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4); var denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); if (!denominator) { return; } var px = nx / denominator; var py = ny / denominator; var px2 = +px.toFixed(2); var py2 = +py.toFixed(2); if (px2 < +Math.min(x1, x2).toFixed(2) || px2 > +Math.max(x1, x2).toFixed(2) || px2 < +Math.min(x3, x4).toFixed(2) || px2 > +Math.max(x3, x4).toFixed(2) || py2 < +Math.min(y1, y2).toFixed(2) || py2 > +Math.max(y1, y2).toFixed(2) || py2 < +Math.min(y3, y4).toFixed(2) || py2 > +Math.max(y3, y4).toFixed(2)) { return; } return { x: px, y: py }; }; var isPointInsideBBox = function isPointInsideBBox(bbox, x, y) { return x >= bbox.x && x <= bbox.x + bbox.width && y >= bbox.y && y <= bbox.y + bbox.height; }; var rectPath = function rectPath(x, y, w, h, r) { if (r) { return [['M', +x + +r, y], ['l', w - r * 2, 0], ['a', r, r, 0, 0, 1, r, r], ['l', 0, h - r * 2], ['a', r, r, 0, 0, 1, -r, r], ['l', r * 2 - w, 0], ['a', r, r, 0, 0, 1, -r, -r], ['l', 0, r * 2 - h], ['a', r, r, 0, 0, 1, r, -r], ['z']]; } var res = [['M', x, y], ['l', w, 0], ['l', 0, h], ['l', -w, 0], ['z']]; res.parsePathArray = parsePathArray; return res; }; var box = function box(x, y, width, height) { if (x === null) { x = y = width = height = 0; } if (y === null) { y = x.y; width = x.width; height = x.height; x = x.x; } return { x: x, y: y, width: width, w: width, height: height, h: height, x2: x + width, y2: y + height, cx: x + width / 2, cy: y + height / 2, r1: Math.min(width, height) / 2, r2: Math.max(width, height) / 2, r0: Math.sqrt(width * width + height * height) / 2, path: rectPath(x, y, width, height), vb: [x, y, width, height].join(' ') }; }; var isBBoxIntersect = function isBBoxIntersect(bbox1, bbox2) { bbox1 = box(bbox1); bbox2 = box(bbox2); return isPointInsideBBox(bbox2, bbox1.x, bbox1.y) || isPointInsideBBox(bbox2, bbox1.x2, bbox1.y) || isPointInsideBBox(bbox2, bbox1.x, bbox1.y2) || isPointInsideBBox(bbox2, bbox1.x2, bbox1.y2) || isPointInsideBBox(bbox1, bbox2.x, bbox2.y) || isPointInsideBBox(bbox1, bbox2.x2, bbox2.y) || isPointInsideBBox(bbox1, bbox2.x, bbox2.y2) || isPointInsideBBox(bbox1, bbox2.x2, bbox2.y2) || (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x) && (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y); }; var bezierBBox = function bezierBBox(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) { if (!Util.isArray(p1x)) { p1x = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y]; } var bbox = curveDim.apply(null, p1x); return box(bbox.min.x, bbox.min.y, bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y); }; var findDotsAtSegment = function findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { var t1 = 1 - t; var t13 = Math.pow(t1, 3); var t12 = Math.pow(t1, 2); var t2 = t * t; var t3 = t2 * t; var x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x; var y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y; var mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x); var my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y); var nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x); var ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y); var ax = t1 * p1x + t * c1x; var ay = t1 * p1y + t * c1y; var cx = t1 * c2x + t * p2x; var cy = t1 * c2y + t * p2y; var alpha = 90 - Math.atan2(mx - nx, my - ny) * 180 / Math.PI; // (mx > nx || my < ny) && (alpha += 180); return { x: x, y: y, m: { x: mx, y: my }, n: { x: nx, y: ny }, start: { x: ax, y: ay }, end: { x: cx, y: cy }, alpha: alpha }; }; var interHelper = function interHelper(bez1, bez2, justCount) { var bbox1 = bezierBBox(bez1); var bbox2 = bezierBBox(bez2); if (!isBBoxIntersect(bbox1, bbox2)) { return justCount ? 0 : []; } var l1 = bezlen.apply(0, bez1); var l2 = bezlen.apply(0, bez2); var n1 = ~~(l1 / 8); var n2 = ~~(l2 / 8); var dots1 = []; var dots2 = []; var xy = {}; var res = justCount ? 0 : []; for (var i = 0; i < n1 + 1; i++) { var d = findDotsAtSegment.apply(0, bez1.concat(i / n1)); dots1.push({ x: d.x, y: d.y, t: i / n1 }); } for (var _i = 0; _i < n2 + 1; _i++) { var _d = findDotsAtSegment.apply(0, bez2.concat(_i / n2)); dots2.push({ x: _d.x, y: _d.y, t: _i / n2 }); } for (var _i2 = 0; _i2 < n1; _i2++) { for (var j = 0; j < n2; j++) { var di = dots1[_i2]; var di1 = dots1[_i2 + 1]; var dj = dots2[j]; var dj1 = dots2[j + 1]; var ci = Math.abs(di1.x - di.x) < 0.001 ? 'y' : 'x'; var cj = Math.abs(dj1.x - dj.x) < 0.001 ? 'y' : 'x'; var is = intersect(di.x, di.y, di1.x, di1.y, dj.x, dj.y, dj1.x, dj1.y); if (is) { if (xy[is.x.toFixed(4)] === is.y.toFixed(4)) { continue; } xy[is.x.toFixed(4)] = is.y.toFixed(4); var t1 = di.t + Math.abs((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t); var t2 = dj.t + Math.abs((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t); if (t1 >= 0 && t1 <= 1 && t2 >= 0 && t2 <= 1) { if (justCount) { res++; } else { res.push({ x: is.x, y: is.y, t1: t1, t2: t2 }); } } } } } return res; }; var interPathHelper = function interPathHelper(path1, path2, justCount) { path1 = pathTocurve(path1); path2 = pathTocurve(path2); var x1; var y1; var x2; var y2; var x1m; var y1m; var x2m; var y2m; var bez1; var bez2; var res = justCount ? 0 : []; for (var i = 0, ii = path1.length; i < ii; i++) { var pi = path1[i]; if (pi[0] === 'M') { x1 = x1m = pi[1]; y1 = y1m = pi[2]; } else { if (pi[0] === 'C') { bez1 = [x1, y1].concat(pi.slice(1)); x1 = bez1[6]; y1 = bez1[7]; } else { bez1 = [x1, y1, x1, y1, x1m, y1m, x1m, y1m]; x1 = x1m; y1 = y1m; } for (var j = 0, jj = path2.length; j < jj; j++) { var pj = path2[j]; if (pj[0] === 'M') { x2 = x2m = pj[1]; y2 = y2m = pj[2]; } else { if (pj[0] === 'C') { bez2 = [x2, y2].concat(pj.slice(1)); x2 = bez2[6]; y2 = bez2[7]; } else { bez2 = [x2, y2, x2, y2, x2m, y2m, x2m, y2m]; x2 = x2m; y2 = y2m; } var intr = interHelper(bez1, bez2, justCount); if (justCount) { res += intr; } else { for (var k = 0, kk = intr.length; k < kk; k++) { intr[k].segment1 = i; intr[k].segment2 = j; intr[k].bez1 = bez1; intr[k].bez2 = bez2; } res = res.concat(intr); } } } } } return res; }; var pathIntersection = function pathIntersection(path1, path2) { return interPathHelper(path1, path2); }; function decasteljau(points, t) { var left = []; var right = []; function recurse(points, t) { if (points.length === 1) { left.push(points[0]); right.push(points[0]); } else { var middlePoints = []; for (var i = 0; i < points.length - 1; i++) { if (i === 0) { left.push(points[0]); } if (i === points.length - 2) { right.push(points[i + 1]); } middlePoints[i] = [(1 - t) * points[i][0] + t * points[i + 1][0], (1 - t) * points[i][1] + t * points[i + 1][1]]; } recurse(middlePoints, t); } } if (points.length) { recurse(points, t); } return { left: left, right: right.reverse() }; } function splitCurve(start, end, count) { var points = [[start[1], start[2]]]; count = count || 2; var segments = []; if (end[0] === 'A') { points.push(end[6]); points.push(end[7]); } else if (end[0] === 'C') { points.push([end[1], end[2]]); points.push([end[3], end[4]]); points.push([end[5], end[6]]); } else if (end[0] === 'S' || end[0] === 'Q') { points.push([end[1], end[2]]); points.push([end[3], end[4]]); } else { points.push([end[1], end[2]]); } var leftSegments = points; var t = 1 / count; for (var i = 0; i < count - 1; i++) { var rt = t / (1 - t * i); var split = decasteljau(leftSegments, rt); segments.push(split.left); leftSegments = split.right; } segments.push(leftSegments); var result = segments.map(function (segment) { var cmd = []; if (segment.length === 4) { cmd.push('C'); cmd = cmd.concat(segment[2]); } if (segment.length >= 3) { if (segment.length === 3) { cmd.push('Q'); } cmd = cmd.concat(segment[1]); } if (segment.length === 2) { cmd.push('L'); } cmd = cmd.concat(segment[segment.length - 1]); return cmd; }); return result; } var splitSegment = function splitSegment(start, end, count) { if (count === 1) { return [[].concat(start)]; } var segments = []; if (end[0] === 'L' || end[0] === 'C' || end[0] === 'Q') { segments = segments.concat(splitCurve(start, end, count)); } else { var temp = [].concat(start); if (temp[0] === 'M') { temp[0] = 'L'; } for (var i = 0; i <= count - 1; i++) { segments.push(temp); } } return segments; }; var fillPath = function fillPath(source, target) { if (source.length === 1) { return source; } var sourceLen = source.length - 1; var targetLen = target.length - 1; var ratio = sourceLen / targetLen; var segmentsToFill = []; if (source.length === 1 && source[0][0] === 'M') { for (var i = 0; i < targetLen - sourceLen; i++) { source.push(source[0]); } return source; } for (var _i3 = 0; _i3 < targetLen; _i3++) { var index = Math.floor(ratio * _i3); segmentsToFill[index] = (segmentsToFill[index] || 0) + 1; } var filled = segmentsToFill.reduce(function (filled, count, i) { if (i === sourceLen) { return filled.concat(source[sourceLen]); } return filled.concat(splitSegment(source[i], source[i + 1], count)); }, []); filled.unshift(source[0]); if (target[targetLen] === 'Z' || target[targetLen] === 'z') { filled.push('Z'); } return filled; }; var isEqual = function isEqual(obj1, obj2) { if (obj1.length !== obj2.length) { return false; } var result = true; Util.each(obj1, function (item, i) { if (item !== obj2[i]) { result = false; return false; } }); return result; }; function getMinDiff(del, add, modify) { var type = null; var min = modify; if (add < min) { min = add; type = 'add'; } if (del < min) { min = del; type = 'del'; } return { type: type, min: min }; } /* * https://en.wikipedia.org/wiki/Levenshtein_distance * 计算两条path的编辑距离 */ var levenshteinDistance = function levenshteinDistance(source, target) { var sourceLen = source.length; var targetLen = target.length; var sourceSegment, targetSegment; var temp = 0; if (sourceLen === 0 || targetLen === 0) { return null; } var dist = []; for (var i = 0; i <= sourceLen; i++) { dist[i] = []; dist[i][0] = { min: i }; } for (var j = 0; j <= targetLen; j++) { dist[0][j] = { min: j }; } for (var _i4 = 1; _i4 <= sourceLen; _i4++) { sourceSegment = source[_i4 - 1]; for (var _j2 = 1; _j2 <= targetLen; _j2++) { targetSegment = target[_j2 - 1]; if (isEqual(sourceSegment, targetSegment)) { temp = 0; } else { temp = 1; } var del = dist[_i4 - 1][_j2].min + 1; var add = dist[_i4][_j2 - 1].min + 1; var modify = dist[_i4 - 1][_j2 - 1].min + temp; dist[_i4][_j2] = getMinDiff(del, add, modify); } } return dist; }; var fillPathByDiff = function fillPathByDiff(source, target) { var diffMatrix = levenshteinDistance(source, target); var sourceLen = source.length; var targetLen = target.length; var changes = []; var index = 1; var minPos = 1; // 如果source和target不是完全不相等 if (diffMatrix[sourceLen][targetLen] !== sourceLen) { // 获取从source到target所需改动 for (var i = 1; i <= sourceLen; i++) { var min = diffMatrix[i][i].min; minPos = i; for (var j = index; j <= targetLen; j++) { if (diffMatrix[i][j].min < min) { min = diffMatrix[i][j].min; minPos = j; } } index = minPos; if (diffMatrix[i][index].type) { changes.push({ index: i - 1, type: diffMatrix[i][index].type }); } } // 对source进行增删path for (var _i5 = changes.length - 1; _i5 >= 0; _i5--) { index = changes[_i5].index; if (changes[_i5].type === 'add') { source.splice(index, 0, [].concat(source[index])); } else { source.splice(index, 1); } } } // source尾部补齐 sourceLen = source.length; var diff = targetLen - sourceLen; if (sourceLen < targetLen) { for (var _i6 = 0; _i6 < diff; _i6++) { if (source[sourceLen - 1][0] === 'z' || source[sourceLen - 1][0] === 'Z') { source.splice(sourceLen - 2, 0, source[sourceLen - 2]); } else { source.push(source[sourceLen - 1]); } sourceLen += 1; } } return source; }; // 将两个点均分成count个点 function _splitPoints(points, former, count) { var result = [].concat(points); var index; var t = 1 / (count + 1); var formerEnd = _getSegmentPoints(former)[0]; for (var i = 1; i <= count; i++) { t *= i; index = Math.floor(points.length * t); if (index === 0) { result.unshift([formerEnd[0] * t + points[index][0] * (1 - t), formerEnd[1] * t + points[index][1] * (1 - t)]); } else { result.splice(index, 0, [formerEnd[0] * t + points[index][0] * (1 - t), formerEnd[1] * t + points[index][1] * (1 - t)]); } } return result; } /* * 抽取pathSegment中的关键点 * M,L,A,Q,H,V一个端点 * Q, S抽取一个端点,一个控制点 * C抽取一个端点,两个控制点 */ function _getSegmentPoints(segment) { var points = []; switch (segment[0]) { case 'M': points.push([segment[1], segment[2]]); break; case 'L': points.push([segment[1], segment[2]]); break; case 'A': points.push([segment[6], segment[7]]); break; case 'Q': points.push([segment[3], segment[4]]); points.push([segment[1], segment[2]]); break; case 'T': points.push([segment[1], segment[2]]); break; case 'C': points.push([segment[5], segment[6]]); points.push([segment[1], segment[2]]); points.push([segment[3], segment[4]]); break; case 'S': points.push([segment[3], segment[4]]); points.push([segment[1], segment[2]]); break; case 'H': points.push([segment[1], segment[1]]); break; case 'V': points.push([segment[1], segment[1]]); break; default: } return points; } var formatPath = function formatPath(fromPath, toPath) { if (fromPath.length <= 1) { return fromPath; } var points; for (var i = 0; i < toPath.length; i++) { if (fromPath[i][0] !== toPath[i][0]) { // 获取fromPath的pathSegment的端点,根据toPath的指令对其改造 points = _getSegmentPoints(fromPath[i]); switch (toPath[i][0]) { case 'M': fromPath[i] = ['M'].concat(points[0]); break; case 'L': fromPath[i] = ['L'].concat(points[0]); break; case 'A': fromPath[i] = [].concat(toPath[i]); fromPath[i][6] = points[0][0]; fromPath[i][7] = points[0][1]; break; case 'Q': if (points.length < 2) { if (i > 0) { points = _splitPoints(points, fromPath[i - 1], 1); } else { fromPath[i] = toPath[i]; break; } } fromPath[i] = ['Q'].concat(points.reduce(function (arr, i) { return arr.concat(i); }, [])); break; case 'T': fromPath[i] = ['T'].concat(points[0]); break; case 'C': if (points.length < 3) { if (i > 0) { points = _splitPoints(points, fromPath[i - 1], 2); } else { fromPath[i] = toPath[i]; break; } } fromPath[i] = ['C'].concat(points.reduce(function (arr, i) { return arr.concat(i); }, [])); break; case 'S': if (points.length < 2) { if (i > 0) { points = _splitPoints(points, fromPath[i - 1], 1); } else { fromPath[i] = toPath[i]; break; } } fromPath[i] = ['S'].concat(points.reduce(function (arr, i) { return arr.concat(i); }, [])); break; default: fromPath[i] = toPath[i]; } } } return fromPath; }; module.exports = { parsePathString: parsePathString, parsePathArray: parsePathArray, pathTocurve: pathTocurve, pathToAbsolute: pathToAbsolute, catmullRomToBezier: catmullRom2bezier, rectPath: rectPath, fillPath: fillPath, fillPathByDiff: fillPathByDiff, formatPath: formatPath, intersection: pathIntersection }; /***/ }), /* 83 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["b"] = now; /* harmony export (immutable) */ __webpack_exports__["a"] = Timer; /* harmony export (immutable) */ __webpack_exports__["c"] = timer; /* harmony export (immutable) */ __webpack_exports__["d"] = timerFlush; var frame = 0, // is an animation frame pending? timeout = 0, // is a timeout pending? interval = 0, // are any timers active? pokeDelay = 1000, // how frequently we check for clock skew taskHead, taskTail, clockLast = 0, clockNow = 0, clockSkew = 0, clock = typeof performance === "object" && performance.now ? performance : Date, setFrame = typeof window === "object" && window.requestAnimationFrame ? window.requestAnimationFrame.bind(window) : function (f) { setTimeout(f, 17); }; function now() { return clockNow || (setFrame(clearNow), clockNow = clock.now() + clockSkew); } function clearNow() { clockNow = 0; } function Timer() { this._call = this._time = this._next = null; } Timer.prototype = timer.prototype = { constructor: Timer, restart: function (callback, delay, time) { if (typeof callback !== "function") throw new TypeError("callback is not a function"); time = (time == null ? now() : +time) + (delay == null ? 0 : +delay); if (!this._next && taskTail !== this) { if (taskTail) taskTail._next = this;else taskHead = this; taskTail = this; } this._call = callback; this._time = time; sleep(); }, stop: function () { if (this._call) { this._call = null; this._time = Infinity; sleep(); } } }; function timer(callback, delay, time) { var t = new Timer(); t.restart(callback, delay, time); return t; } function timerFlush() { now(); // Get the current time, if not already set. ++frame; // Pretend we’ve set an alarm, if we haven’t already. var t = taskHead, e; while (t) { if ((e = clockNow - t._time) >= 0) t._call.call(null, e); t = t._next; } --frame; } function wake() { clockNow = (clockLast = clock.now()) + clockSkew; frame = timeout = 0; try { timerFlush(); } finally { frame = 0; nap(); clockNow = 0; } } function poke() { var now = clock.now(), delay = now - clockLast; if (delay > pokeDelay) clockSkew -= delay, clockLast = now; } function nap() { var t0, t1 = taskHead, t2, time = Infinity; while (t1) { if (t1._call) { if (time > t1._time) time = t1._time; t0 = t1, t1 = t1._next; } else { t2 = t1._next, t1._next = null; t1 = t0 ? t0._next = t2 : taskHead = t2; } } taskTail = t0; sleep(time); } function sleep(time) { if (frame) return; // Soonest alarm already set, or will be. if (timeout) timeout = clearTimeout(timeout); var delay = time - clockNow; // Strictly less than if we recomputed clockNow. if (delay > 24) { if (time < Infinity) timeout = setTimeout(wake, time - clock.now() - clockSkew); if (interval) interval = clearInterval(interval); } else { if (!interval) clockLast = clock.now(), interval = setInterval(poke, pokeDelay); frame = 1, setFrame(wake); } } /***/ }), /* 84 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_d3_color__ = __webpack_require__(19); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__rgb__ = __webpack_require__(135); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__array__ = __webpack_require__(138); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__date__ = __webpack_require__(139); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__number__ = __webpack_require__(47); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__object__ = __webpack_require__(140); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__string__ = __webpack_require__(141); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__constant__ = __webpack_require__(137); /* harmony default export */ __webpack_exports__["a"] = (function (a, b) { var t = typeof b, c; return b == null || t === "boolean" ? Object(__WEBPACK_IMPORTED_MODULE_7__constant__["a" /* default */])(b) : (t === "number" ? __WEBPACK_IMPORTED_MODULE_4__number__["a" /* default */] : t === "string" ? (c = Object(__WEBPACK_IMPORTED_MODULE_0_d3_color__["a" /* color */])(b)) ? (b = c, __WEBPACK_IMPORTED_MODULE_1__rgb__["a" /* default */]) : __WEBPACK_IMPORTED_MODULE_6__string__["a" /* default */] : b instanceof __WEBPACK_IMPORTED_MODULE_0_d3_color__["a" /* color */] ? __WEBPACK_IMPORTED_MODULE_1__rgb__["a" /* default */] : b instanceof Date ? __WEBPACK_IMPORTED_MODULE_3__date__["a" /* default */] : Array.isArray(b) ? __WEBPACK_IMPORTED_MODULE_2__array__["a" /* default */] : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? __WEBPACK_IMPORTED_MODULE_5__object__["a" /* default */] : __WEBPACK_IMPORTED_MODULE_4__number__["a" /* default */])(a, b); }); /***/ }), /* 85 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = Color; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "d", function() { return darker; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return brighter; }); /* harmony export (immutable) */ __webpack_exports__["e"] = color; /* harmony export (immutable) */ __webpack_exports__["h"] = rgbConvert; /* harmony export (immutable) */ __webpack_exports__["g"] = rgb; /* harmony export (immutable) */ __webpack_exports__["b"] = Rgb; /* unused harmony export hslConvert */ /* harmony export (immutable) */ __webpack_exports__["f"] = hsl; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__define_js__ = __webpack_require__(86); function Color() {} var darker = 0.7; var brighter = 1 / darker; var reI = "\\s*([+-]?\\d+)\\s*", reN = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)\\s*", reP = "\\s*([+-]?\\d*\\.?\\d+(?:[eE][+-]?\\d+)?)%\\s*", reHex = /^#([0-9a-f]{3,8})$/, reRgbInteger = new RegExp("^rgb\\(" + [reI, reI, reI] + "\\)$"), reRgbPercent = new RegExp("^rgb\\(" + [reP, reP, reP] + "\\)$"), reRgbaInteger = new RegExp("^rgba\\(" + [reI, reI, reI, reN] + "\\)$"), reRgbaPercent = new RegExp("^rgba\\(" + [reP, reP, reP, reN] + "\\)$"), reHslPercent = new RegExp("^hsl\\(" + [reN, reP, reP] + "\\)$"), reHslaPercent = new RegExp("^hsla\\(" + [reN, reP, reP, reN] + "\\)$"); var named = { aliceblue: 0xf0f8ff, antiquewhite: 0xfaebd7, aqua: 0x00ffff, aquamarine: 0x7fffd4, azure: 0xf0ffff, beige: 0xf5f5dc, bisque: 0xffe4c4, black: 0x000000, blanchedalmond: 0xffebcd, blue: 0x0000ff, blueviolet: 0x8a2be2, brown: 0xa52a2a, burlywood: 0xdeb887, cadetblue: 0x5f9ea0, chartreuse: 0x7fff00, chocolate: 0xd2691e, coral: 0xff7f50, cornflowerblue: 0x6495ed, cornsilk: 0xfff8dc, crimson: 0xdc143c, cyan: 0x00ffff, darkblue: 0x00008b, darkcyan: 0x008b8b, darkgoldenrod: 0xb8860b, darkgray: 0xa9a9a9, darkgreen: 0x006400, darkgrey: 0xa9a9a9, darkkhaki: 0xbdb76b, darkmagenta: 0x8b008b, darkolivegreen: 0x556b2f, darkorange: 0xff8c00, darkorchid: 0x9932cc, darkred: 0x8b0000, darksalmon: 0xe9967a, darkseagreen: 0x8fbc8f, darkslateblue: 0x483d8b, darkslategray: 0x2f4f4f, darkslategrey: 0x2f4f4f, darkturquoise: 0x00ced1, darkviolet: 0x9400d3, deeppink: 0xff1493, deepskyblue: 0x00bfff, dimgray: 0x696969, dimgrey: 0x696969, dodgerblue: 0x1e90ff, firebrick: 0xb22222, floralwhite: 0xfffaf0, forestgreen: 0x228b22, fuchsia: 0xff00ff, gainsboro: 0xdcdcdc, ghostwhite: 0xf8f8ff, gold: 0xffd700, goldenrod: 0xdaa520, gray: 0x808080, green: 0x008000, greenyellow: 0xadff2f, grey: 0x808080, honeydew: 0xf0fff0, hotpink: 0xff69b4, indianred: 0xcd5c5c, indigo: 0x4b0082, ivory: 0xfffff0, khaki: 0xf0e68c, lavender: 0xe6e6fa, lavenderblush: 0xfff0f5, lawngreen: 0x7cfc00, lemonchiffon: 0xfffacd, lightblue: 0xadd8e6, lightcoral: 0xf08080, lightcyan: 0xe0ffff, lightgoldenrodyellow: 0xfafad2, lightgray: 0xd3d3d3, lightgreen: 0x90ee90, lightgrey: 0xd3d3d3, lightpink: 0xffb6c1, lightsalmon: 0xffa07a, lightseagreen: 0x20b2aa, lightskyblue: 0x87cefa, lightslategray: 0x778899, lightslategrey: 0x778899, lightsteelblue: 0xb0c4de, lightyellow: 0xffffe0, lime: 0x00ff00, limegreen: 0x32cd32, linen: 0xfaf0e6, magenta: 0xff00ff, maroon: 0x800000, mediumaquamarine: 0x66cdaa, mediumblue: 0x0000cd, mediumorchid: 0xba55d3, mediumpurple: 0x9370db, mediumseagreen: 0x3cb371, mediumslateblue: 0x7b68ee, mediumspringgreen: 0x00fa9a, mediumturquoise: 0x48d1cc, mediumvioletred: 0xc71585, midnightblue: 0x191970, mintcream: 0xf5fffa, mistyrose: 0xffe4e1, moccasin: 0xffe4b5, navajowhite: 0xffdead, navy: 0x000080, oldlace: 0xfdf5e6, olive: 0x808000, olivedrab: 0x6b8e23, orange: 0xffa500, orangered: 0xff4500, orchid: 0xda70d6, palegoldenrod: 0xeee8aa, palegreen: 0x98fb98, paleturquoise: 0xafeeee, palevioletred: 0xdb7093, papayawhip: 0xffefd5, peachpuff: 0xffdab9, peru: 0xcd853f, pink: 0xffc0cb, plum: 0xdda0dd, powderblue: 0xb0e0e6, purple: 0x800080, rebeccapurple: 0x663399, red: 0xff0000, rosybrown: 0xbc8f8f, royalblue: 0x4169e1, saddlebrown: 0x8b4513, salmon: 0xfa8072, sandybrown: 0xf4a460, seagreen: 0x2e8b57, seashell: 0xfff5ee, sienna: 0xa0522d, silver: 0xc0c0c0, skyblue: 0x87ceeb, slateblue: 0x6a5acd, slategray: 0x708090, slategrey: 0x708090, snow: 0xfffafa, springgreen: 0x00ff7f, steelblue: 0x4682b4, tan: 0xd2b48c, teal: 0x008080, thistle: 0xd8bfd8, tomato: 0xff6347, turquoise: 0x40e0d0, violet: 0xee82ee, wheat: 0xf5deb3, white: 0xffffff, whitesmoke: 0xf5f5f5, yellow: 0xffff00, yellowgreen: 0x9acd32 }; Object(__WEBPACK_IMPORTED_MODULE_0__define_js__["a" /* default */])(Color, color, { copy: function (channels) { return Object.assign(new this.constructor(), this, channels); }, displayable: function () { return this.rgb().displayable(); }, hex: color_formatHex, // Deprecated! Use color.formatHex. formatHex: color_formatHex, formatHsl: color_formatHsl, formatRgb: color_formatRgb, toString: color_formatRgb }); function color_formatHex() { return this.rgb().formatHex(); } function color_formatHsl() { return hslConvert(this).formatHsl(); } function color_formatRgb() { return this.rgb().formatRgb(); } function color(format) { var m, l; format = (format + "").trim().toLowerCase(); return (m = reHex.exec(format)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) // #ff0000 : l === 3 ? new Rgb(m >> 8 & 0xf | m >> 4 & 0xf0, m >> 4 & 0xf | m & 0xf0, (m & 0xf) << 4 | m & 0xf, 1) // #f00 : l === 8 ? rgba(m >> 24 & 0xff, m >> 16 & 0xff, m >> 8 & 0xff, (m & 0xff) / 0xff) // #ff000000 : l === 4 ? rgba(m >> 12 & 0xf | m >> 8 & 0xf0, m >> 8 & 0xf | m >> 4 & 0xf0, m >> 4 & 0xf | m & 0xf0, ((m & 0xf) << 4 | m & 0xf) / 0xff) // #f000 : null // invalid hex ) : (m = reRgbInteger.exec(format)) ? new Rgb(m[1], m[2], m[3], 1) // rgb(255, 0, 0) : (m = reRgbPercent.exec(format)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) // rgb(100%, 0%, 0%) : (m = reRgbaInteger.exec(format)) ? rgba(m[1], m[2], m[3], m[4]) // rgba(255, 0, 0, 1) : (m = reRgbaPercent.exec(format)) ? rgba(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) // rgb(100%, 0%, 0%, 1) : (m = reHslPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) // hsl(120, 50%, 50%) : (m = reHslaPercent.exec(format)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) // hsla(120, 50%, 50%, 1) : named.hasOwnProperty(format) ? rgbn(named[format]) // eslint-disable-line no-prototype-builtins : format === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null; } function rgbn(n) { return new Rgb(n >> 16 & 0xff, n >> 8 & 0xff, n & 0xff, 1); } function rgba(r, g, b, a) { if (a <= 0) r = g = b = NaN; return new Rgb(r, g, b, a); } function rgbConvert(o) { if (!(o instanceof Color)) o = color(o); if (!o) return new Rgb(); o = o.rgb(); return new Rgb(o.r, o.g, o.b, o.opacity); } function rgb(r, g, b, opacity) { return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity); } function Rgb(r, g, b, opacity) { this.r = +r; this.g = +g; this.b = +b; this.opacity = +opacity; } Object(__WEBPACK_IMPORTED_MODULE_0__define_js__["a" /* default */])(Rgb, rgb, Object(__WEBPACK_IMPORTED_MODULE_0__define_js__["b" /* extend */])(Color, { brighter: function (k) { k = k == null ? brighter : Math.pow(brighter, k); return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); }, darker: function (k) { k = k == null ? darker : Math.pow(darker, k); return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); }, rgb: function () { return this; }, displayable: function () { return -0.5 <= this.r && this.r < 255.5 && -0.5 <= this.g && this.g < 255.5 && -0.5 <= this.b && this.b < 255.5 && 0 <= this.opacity && this.opacity <= 1; }, hex: rgb_formatHex, // Deprecated! Use color.formatHex. formatHex: rgb_formatHex, formatRgb: rgb_formatRgb, toString: rgb_formatRgb })); function rgb_formatHex() { return "#" + hex(this.r) + hex(this.g) + hex(this.b); } function rgb_formatRgb() { var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a)); return (a === 1 ? "rgb(" : "rgba(") + Math.max(0, Math.min(255, Math.round(this.r) || 0)) + ", " + Math.max(0, Math.min(255, Math.round(this.g) || 0)) + ", " + Math.max(0, Math.min(255, Math.round(this.b) || 0)) + (a === 1 ? ")" : ", " + a + ")"); } function hex(value) { value = Math.max(0, Math.min(255, Math.round(value) || 0)); return (value < 16 ? "0" : "") + value.toString(16); } function hsla(h, s, l, a) { if (a <= 0) h = s = l = NaN;else if (l <= 0 || l >= 1) h = s = NaN;else if (s <= 0) h = NaN; return new Hsl(h, s, l, a); } function hslConvert(o) { if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity); if (!(o instanceof Color)) o = color(o); if (!o) return new Hsl(); if (o instanceof Hsl) return o; o = o.rgb(); var r = o.r / 255, g = o.g / 255, b = o.b / 255, min = Math.min(r, g, b), max = Math.max(r, g, b), h = NaN, s = max - min, l = (max + min) / 2; if (s) { if (r === max) h = (g - b) / s + (g < b) * 6;else if (g === max) h = (b - r) / s + 2;else h = (r - g) / s + 4; s /= l < 0.5 ? max + min : 2 - max - min; h *= 60; } else { s = l > 0 && l < 1 ? 0 : h; } return new Hsl(h, s, l, o.opacity); } function hsl(h, s, l, opacity) { return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity); } function Hsl(h, s, l, opacity) { this.h = +h; this.s = +s; this.l = +l; this.opacity = +opacity; } Object(__WEBPACK_IMPORTED_MODULE_0__define_js__["a" /* default */])(Hsl, hsl, Object(__WEBPACK_IMPORTED_MODULE_0__define_js__["b" /* extend */])(Color, { brighter: function (k) { k = k == null ? brighter : Math.pow(brighter, k); return new Hsl(this.h, this.s, this.l * k, this.opacity); }, darker: function (k) { k = k == null ? darker : Math.pow(darker, k); return new Hsl(this.h, this.s, this.l * k, this.opacity); }, rgb: function () { var h = this.h % 360 + (this.h < 0) * 360, s = isNaN(h) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s, m1 = 2 * l - m2; return new Rgb(hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2), hsl2rgb(h, m1, m2), hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2), this.opacity); }, displayable: function () { return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && 0 <= this.l && this.l <= 1 && 0 <= this.opacity && this.opacity <= 1; }, formatHsl: function () { var a = this.opacity; a = isNaN(a) ? 1 : Math.max(0, Math.min(1, a)); return (a === 1 ? "hsl(" : "hsla(") + (this.h || 0) + ", " + (this.s || 0) * 100 + "%, " + (this.l || 0) * 100 + "%" + (a === 1 ? ")" : ", " + a + ")"); } })); /* From FvD 13.37, CSS Color Module Level 3 */ function hsl2rgb(h, m1, m2) { return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255; } /***/ }), /* 86 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["b"] = extend; /* harmony default export */ __webpack_exports__["a"] = (function (constructor, factory, prototype) { constructor.prototype = factory.prototype = prototype; prototype.constructor = constructor; }); function extend(parent, definition) { var prototype = Object.create(parent.prototype); for (var key in definition) prototype[key] = definition[key]; return prototype; } /***/ }), /* 87 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = basis; function basis(t1, v0, v1, v2, v3) { var t2 = t1 * t1, t3 = t2 * t1; return ((1 - 3 * t1 + 3 * t2 - t3) * v0 + (4 - 6 * t2 + 3 * t3) * v1 + (1 + 3 * t1 + 3 * t2 - 3 * t3) * v2 + t3 * v3) / 6; } /* harmony default export */ __webpack_exports__["b"] = (function (values) { var n = values.length - 1; return function (t) { var i = t <= 0 ? t = 0 : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n), v1 = values[i], v2 = values[i + 1], v0 = i > 0 ? values[i - 1] : 2 * v1 - v2, v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1; return basis((t - i / n) * n, v0, v1, v2, v3); }; }); /***/ }), /* 88 */ /***/ (function(module, exports, __webpack_require__) { var each = __webpack_require__(3); var isArrayLike = __webpack_require__(15); var filter = function filter(arr, func) { if (!isArrayLike(arr)) { return arr; } var result = []; each(arr, function (value, index) { if (func(value, index)) { result.push(value); } }); return result; }; module.exports = filter; /***/ }), /* 89 */ /***/ (function(module, exports, __webpack_require__) { var isNil = __webpack_require__(6); var isArray = __webpack_require__(5); var each = __webpack_require__(3); module.exports = function valuesOfKey(data, name) { var rst = []; var tmpMap = {}; for (var i = 0; i < data.length; i++) { var obj = data[i]; var value = obj[name]; if (!isNil(value)) { if (!isArray(value)) { value = [value]; } each(value, function (val) { if (!tmpMap[val]) { rst.push(val); tmpMap[val] = true; } }); } } return rst; }; /***/ }), /* 90 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;/*! * EventEmitter v5.1.0 - git.io/ee * Unlicense - http://unlicense.org/ * Oliver Caldwell - http://oli.me.uk/ * @preserve */ ; (function (exports) { 'use strict'; /** * Class for managing events. * Can be extended to provide event functionality in other classes. * * @class EventEmitter Manages event registering and emitting. */ function EventEmitter() {} // Shortcuts to improve speed and size var proto = EventEmitter.prototype; var originalGlobalValue = exports.EventEmitter; /** * Finds the index of the listener for the event in its storage array. * * @param {Function[]} listeners Array of listeners to search through. * @param {Function} listener Method to look for. * @return {Number} Index of the specified listener, -1 if not found * @api private */ function indexOfListener(listeners, listener) { var i = listeners.length; while (i--) { if (listeners[i].listener === listener) { return i; } } return -1; } /** * Alias a method while keeping the context correct, to allow for overwriting of target method. * * @param {String} name The name of the target method. * @return {Function} The aliased method * @api private */ function alias(name) { return function aliasClosure() { return this[name].apply(this, arguments); }; } /** * Returns the listener array for the specified event. * Will initialise the event object and listener arrays if required. * Will return an object if you use a regex search. The object contains keys for each matched event. So /ba[rz]/ might return an object containing bar and baz. But only if you have either defined them with defineEvent or added some listeners to them. * Each property in the object response is an array of listener functions. * * @param {String|RegExp} evt Name of the event to return the listeners from. * @return {Function[]|Object} All listener functions for the event. */ proto.getListeners = function getListeners(evt) { var events = this._getEvents(); var response; var key; // Return a concatenated array of all matching events if // the selector is a regular expression. if (evt instanceof RegExp) { response = {}; for (key in events) { if (events.hasOwnProperty(key) && evt.test(key)) { response[key] = events[key]; } } } else { response = events[evt] || (events[evt] = []); } return response; }; /** * Takes a list of listener objects and flattens it into a list of listener functions. * * @param {Object[]} listeners Raw listener objects. * @return {Function[]} Just the listener functions. */ proto.flattenListeners = function flattenListeners(listeners) { var flatListeners = []; var i; for (i = 0; i < listeners.length; i += 1) { flatListeners.push(listeners[i].listener); } return flatListeners; }; /** * Fetches the requested listeners via getListeners but will always return the results inside an object. This is mainly for internal use but others may find it useful. * * @param {String|RegExp} evt Name of the event to return the listeners from. * @return {Object} All listener functions for an event in an object. */ proto.getListenersAsObject = function getListenersAsObject(evt) { var listeners = this.getListeners(evt); var response; if (listeners instanceof Array) { response = {}; response[evt] = listeners; } return response || listeners; }; function isValidListener(listener) { if (typeof listener === 'function' || listener instanceof RegExp) { return true; } else if (listener && typeof listener === 'object') { return isValidListener(listener.listener); } else { return false; } } /** * Adds a listener function to the specified event. * The listener will not be added if it is a duplicate. * If the listener returns true then it will be removed after it is called. * If you pass a regular expression as the event name then the listener will be added to all events that match it. * * @param {String|RegExp} evt Name of the event to attach the listener to. * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling. * @return {Object} Current instance of EventEmitter for chaining. */ proto.addListener = function addListener(evt, listener) { if (!isValidListener(listener)) { throw new TypeError('listener must be a function'); } var listeners = this.getListenersAsObject(evt); var listenerIsWrapped = typeof listener === 'object'; var key; for (key in listeners) { if (listeners.hasOwnProperty(key) && indexOfListener(listeners[key], listener) === -1) { listeners[key].push(listenerIsWrapped ? listener : { listener: listener, once: false }); } } return this; }; /** * Alias of addListener */ proto.on = alias('addListener'); /** * Semi-alias of addListener. It will add a listener that will be * automatically removed after its first execution. * * @param {String|RegExp} evt Name of the event to attach the listener to. * @param {Function} listener Method to be called when the event is emitted. If the function returns true then it will be removed after calling. * @return {Object} Current instance of EventEmitter for chaining. */ proto.addOnceListener = function addOnceListener(evt, listener) { return this.addListener(evt, { listener: listener, once: true }); }; /** * Alias of addOnceListener. */ proto.once = alias('addOnceListener'); /** * Defines an event name. This is required if you want to use a regex to add a listener to multiple events at once. If you don't do this then how do you expect it to know what event to add to? Should it just add to every possible match for a regex? No. That is scary and bad. * You need to tell it what event names should be matched by a regex. * * @param {String} evt Name of the event to create. * @return {Object} Current instance of EventEmitter for chaining. */ proto.defineEvent = function defineEvent(evt) { this.getListeners(evt); return this; }; /** * Uses defineEvent to define multiple events. * * @param {String[]} evts An array of event names to define. * @return {Object} Current instance of EventEmitter for chaining. */ proto.defineEvents = function defineEvents(evts) { for (var i = 0; i < evts.length; i += 1) { this.defineEvent(evts[i]); } return this; }; /** * Removes a listener function from the specified event. * When passed a regular expression as the event name, it will remove the listener from all events that match it. * * @param {String|RegExp} evt Name of the event to remove the listener from. * @param {Function} listener Method to remove from the event. * @return {Object} Current instance of EventEmitter for chaining. */ proto.removeListener = function removeListener(evt, listener) { var listeners = this.getListenersAsObject(evt); var index; var key; for (key in listeners) { if (listeners.hasOwnProperty(key)) { index = indexOfListener(listeners[key], listener); if (index !== -1) { listeners[key].splice(index, 1); } } } return this; }; /** * Alias of removeListener */ proto.off = alias('removeListener'); /** * Adds listeners in bulk using the manipulateListeners method. * If you pass an object as the second argument you can add to multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. You can also pass it an event name and an array of listeners to be added. * You can also pass it a regular expression to add the array of listeners to all events that match it. * Yeah, this function does quite a bit. That's probably a bad thing. * * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add to multiple events at once. * @param {Function[]} [listeners] An optional array of listener functions to add. * @return {Object} Current instance of EventEmitter for chaining. */ proto.addListeners = function addListeners(evt, listeners) { // Pass through to manipulateListeners return this.manipulateListeners(false, evt, listeners); }; /** * Removes listeners in bulk using the manipulateListeners method. * If you pass an object as the second argument you can remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. * You can also pass it an event name and an array of listeners to be removed. * You can also pass it a regular expression to remove the listeners from all events that match it. * * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to remove from multiple events at once. * @param {Function[]} [listeners] An optional array of listener functions to remove. * @return {Object} Current instance of EventEmitter for chaining. */ proto.removeListeners = function removeListeners(evt, listeners) { // Pass through to manipulateListeners return this.manipulateListeners(true, evt, listeners); }; /** * Edits listeners in bulk. The addListeners and removeListeners methods both use this to do their job. You should really use those instead, this is a little lower level. * The first argument will determine if the listeners are removed (true) or added (false). * If you pass an object as the second argument you can add/remove from multiple events at once. The object should contain key value pairs of events and listeners or listener arrays. * You can also pass it an event name and an array of listeners to be added/removed. * You can also pass it a regular expression to manipulate the listeners of all events that match it. * * @param {Boolean} remove True if you want to remove listeners, false if you want to add. * @param {String|Object|RegExp} evt An event name if you will pass an array of listeners next. An object if you wish to add/remove from multiple events at once. * @param {Function[]} [listeners] An optional array of listener functions to add/remove. * @return {Object} Current instance of EventEmitter for chaining. */ proto.manipulateListeners = function manipulateListeners(remove, evt, listeners) { var i; var value; var single = remove ? this.removeListener : this.addListener; var multiple = remove ? this.removeListeners : this.addListeners; // If evt is an object then pass each of its properties to this method if (typeof evt === 'object' && !(evt instanceof RegExp)) { for (i in evt) { if (evt.hasOwnProperty(i) && (value = evt[i])) { // Pass the single listener straight through to the singular method if (typeof value === 'function') { single.call(this, i, value); } else { // Otherwise pass back to the multiple function multiple.call(this, i, value); } } } } else { // So evt must be a string // And listeners must be an array of listeners // Loop over it and pass each one to the multiple method i = listeners.length; while (i--) { single.call(this, evt, listeners[i]); } } return this; }; /** * Removes all listeners from a specified event. * If you do not specify an event then all listeners will be removed. * That means every event will be emptied. * You can also pass a regex to remove all events that match it. * * @param {String|RegExp} [evt] Optional name of the event to remove all listeners for. Will remove from every event if not passed. * @return {Object} Current instance of EventEmitter for chaining. */ proto.removeEvent = function removeEvent(evt) { var type = typeof evt; var events = this._getEvents(); var key; // Remove different things depending on the state of evt if (type === 'string') { // Remove all listeners for the specified event delete events[evt]; } else if (evt instanceof RegExp) { // Remove all events matching the regex. for (key in events) { if (events.hasOwnProperty(key) && evt.test(key)) { delete events[key]; } } } else { // Remove all listeners in all events delete this._events; } return this; }; /** * Alias of removeEvent. * * Added to mirror the node API. */ proto.removeAllListeners = alias('removeEvent'); /** * Emits an event of your choice. * When emitted, every listener attached to that event will be executed. * If you pass the optional argument array then those arguments will be passed to every listener upon execution. * Because it uses `apply`, your array of arguments will be passed as if you wrote them out separately. * So they will not arrive within the array on the other side, they will be separate. * You can also pass a regular expression to emit to all events that match it. * * @param {String|RegExp} evt Name of the event to emit and execute listeners for. * @param {Array} [args] Optional array of arguments to be passed to each listener. * @return {Object} Current instance of EventEmitter for chaining. */ proto.emitEvent = function emitEvent(evt, args) { var listenersMap = this.getListenersAsObject(evt); var listeners; var listener; var i; var key; var response; for (key in listenersMap) { if (listenersMap.hasOwnProperty(key)) { listeners = listenersMap[key].slice(0); for (i = 0; i < listeners.length; i++) { // If the listener returns true then it shall be removed from the event // The function is executed either with a basic call or an apply if there is an args array listener = listeners[i]; if (listener.once === true) { this.removeListener(evt, listener.listener); } response = listener.listener.apply(this, args || []); if (response === this._getOnceReturnValue()) { this.removeListener(evt, listener.listener); } } } } return this; }; /** * Alias of emitEvent */ proto.trigger = alias('emitEvent'); /** * Subtly different from emitEvent in that it will pass its arguments on to the listeners, as opposed to taking a single array of arguments to pass on. * As with emitEvent, you can pass a regex in place of the event name to emit to all events that match it. * * @param {String|RegExp} evt Name of the event to emit and execute listeners for. * @param {...*} Optional additional arguments to be passed to each listener. * @return {Object} Current instance of EventEmitter for chaining. */ proto.emit = function emit(evt) { var args = Array.prototype.slice.call(arguments, 1); return this.emitEvent(evt, args); }; /** * Sets the current value to check against when executing listeners. If a * listeners return value matches the one set here then it will be removed * after execution. This value defaults to true. * * @param {*} value The new value to check for when executing listeners. * @return {Object} Current instance of EventEmitter for chaining. */ proto.setOnceReturnValue = function setOnceReturnValue(value) { this._onceReturnValue = value; return this; }; /** * Fetches the current value to check against when executing listeners. If * the listeners return value matches this one then it should be removed * automatically. It will return true by default. * * @return {*|Boolean} The current value to check for or the default, true. * @api private */ proto._getOnceReturnValue = function _getOnceReturnValue() { if (this.hasOwnProperty('_onceReturnValue')) { return this._onceReturnValue; } else { return true; } }; /** * Fetches the events object and creates one if required. * * @return {Object} The events storage object. * @api private */ proto._getEvents = function _getEvents() { return this._events || (this._events = {}); }; /** * Reverts the global {@link EventEmitter} to its previous value and returns a reference to this version. * * @return {Function} Non conflicting EventEmitter class. */ EventEmitter.noConflict = function noConflict() { exports.EventEmitter = originalGlobalValue; return EventEmitter; }; // Expose the class either via AMD, CommonJS or the global object if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return EventEmitter; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else if (typeof module === 'object' && module.exports) { module.exports = EventEmitter; } else { exports.EventEmitter = EventEmitter; } })(this || {}); /***/ }), /* 91 */ /***/ (function(module, exports, __webpack_require__) { var _require = __webpack_require__(18), Group = _require.Group; var _require2 = __webpack_require__(24), Label = _require2.Label; // const visualCenter = require('@antv/component/lib/label/utils/visual-center'); var Global = __webpack_require__(8); var Util = __webpack_require__(0); var IGNORE_ARR = ['line', 'point', 'path']; var ORIGIN = '_origin'; function avg(arr) { var sum = 0; Util.each(arr, function (value) { sum += value; }); return sum / arr.length; } // 计算多边形重心: https://en.wikipedia.org/wiki/Centroid#Of_a_polygon function getCentroid(xs, ys) { if (Util.isNumber(xs) && Util.isNumber(ys)) { return [xs, ys]; } var i = -1, x = 0, y = 0; var former, current = xs.length - 1; var diff, k = 0; while (++i < xs.length) { former = current; current = i; k += diff = xs[former] * ys[current] - xs[current] * ys[former]; x += (xs[former] + xs[current]) * diff; y += (ys[former] + ys[current]) * diff; } k *= 3; return [x / k, y / k]; } var GeomLabels = function GeomLabels(cfg) { GeomLabels.superclass.constructor.call(this, cfg); }; Util.extend(GeomLabels, Group); Util.augment(GeomLabels, { getDefaultCfg: function getDefaultCfg() { return { label: Global.label, /** * 用户传入的文本配置信息 * @type {Object} */ labelCfg: null, /** * 所在的坐标系 * @type {Object} */ coord: null, /** * 图表的类型 * @type {String} */ geomType: null, zIndex: 6 }; }, _renderUI: function _renderUI() { GeomLabels.superclass._renderUI.call(this); this.initLabelsCfg(); var labelsGroup = this.addGroup(); var lineGroup = this.addGroup({ elCls: 'x-line-group' }); var labelRenderer = this.get('labelRenderer'); this.set('labelsGroup', labelsGroup); this.set('lineGroup', lineGroup); this.get('labelRenderer').set('group', labelsGroup); labelRenderer.set('group', labelsGroup); labelRenderer.set('lineGroup', lineGroup); }, // 初始化labels的配置项 initLabelsCfg: function initLabelsCfg() { var self = this; var labelRenderer = new Label(); var labels = self.getDefaultLabelCfg(); var labelCfg = self.get('labelCfg'); // Util.merge(labels, labelCfg.cfg); Util.deepMix(labels, labelCfg.globalCfg || labelCfg.cfg); labelRenderer.set('config', false); if (labels.labelLine) { labelRenderer.set('labelLine', labels.labelLine); } labelRenderer.set('coord', self.get('coord')); this.set('labelRenderer', labelRenderer); self.set('label', labels); }, /** * @protected * 默认的文本样式 * @return {Object} default label config */ getDefaultLabelCfg: function getDefaultLabelCfg() { var self = this; var labelCfg = self.get('labelCfg').cfg || self.get('labelCfg').globalCfg; var geomType = self.get('geomType'); var viewTheme = self.get('viewTheme') || Global; if (geomType === 'polygon' || labelCfg && labelCfg.offset < 0 && Util.indexOf(IGNORE_ARR, geomType) === -1) { return Util.deepMix({}, self.get('label'), viewTheme.innerLabels, labelCfg); } return Util.deepMix({}, self.get('label'), viewTheme.label, labelCfg); }, /** * @protected * 获取labels * @param {Array} points points * @param {Array} shapes shapes * @return {Array} label items */ getLabelsItems: function getLabelsItems(points, shapes) { var self = this; var items = []; var geom = self.get('geom'); var coord = self.get('coord'); self._getLabelCfgs(points, shapes); var labelCfg = self.get('labelItemCfgs'); // 获取label相关的x,y的值,获取具体的x,y,防止存在数组 Util.each(points, function (point, i) { var origin = point[ORIGIN]; var label = labelCfg[i]; if (!label) { items.push(null); return; } if (!Util.isArray(label.text)) { label.text = [label.text]; } var total = label.text.length; Util.each(label.text, function (sub, subIndex) { if (Util.isNil(sub) || sub === '') { items.push(null); return; } var obj = self.getLabelPoint(label, point, subIndex); obj = Util.mix({}, label, obj); if (!obj.textAlign) { obj.textAlign = self.getLabelAlign(obj, subIndex, total); } if (geom) { obj._id = geom._getShapeId(origin) + '-glabel-' + subIndex + '-' + obj.text; } obj.coord = coord; items.push(obj); }); }); return items; }, /* /!* * @protected * 如果发生冲突则会调整文本的位置 * @param {Array} items 文本的集合 * @param {Array} shapes 关联形状 * @return {Array} adjusted items *!/ adjustItems(items, shapes) { // 多边形shape的label位于其可视中心 if (this.get('geomType') === 'polygon') { let index, shape, path, center, points; Util.each(items, (item, i) => { if (!item) return; shape = shapes[ i ]; path = shape.attr('path'); points = [[]]; index = 0; path.forEach((segment, i) => { if (segment[ 0 ] === 'z' || segment[ 0 ] === 'Z' && i !== path.length - 1) { points.push([]); index += 1; } if (segment.length === 3) { points[ index ].push([ segment[ 1 ], segment[ 2 ] ]); } }); center = visualCenter(points); item.x = center.x; item.y = center.y; }); } return items; } */ adjustItems: function adjustItems(items) { Util.each(items, function (item) { if (!item) { return; } if (item.offsetX) { item.x += item.offsetX; } if (item.offsetY) { item.y += item.offsetY; } }); return items; }, /** * drawing lines to labels * @param {Array} items labels * @param {Object} labelLine configuration for label lines */ drawLines: function drawLines(items) { var self = this; Util.each(items, function (point) { if (!point) { return; } if (point.offset > 0) { self.lineToLabel(point); } }); }, // 定义连接线 lineToLabel: function lineToLabel() {}, /** * @protected * 获取文本的位置信息 * @param {Array} labelCfg labels * @param {Object} point point * @param {Number} index index * @return {Object} point */ getLabelPoint: function getLabelPoint(labelCfg, point, index) { var self = this; var coord = self.get('coord'); var total = labelCfg.text.length; function getDimValue(value, idx) { if (Util.isArray(value)) { if (labelCfg.text.length === 1) { // 如果仅一个label,多个y,取最后一个y if (value.length <= 2) { value = value[value.length - 1]; // value = value[0]; } else { value = avg(value); } } else { value = value[idx]; } } return value; } var label = { text: labelCfg.text[index] }; // 多边形场景,多用于地图 if (point && this.get('geomType') === 'polygon') { var centroid = getCentroid(point.x, point.y); // 多边形的场景也有 x 和 y 只是数字的情况,譬如当 x 和 y 都是分类字段的时候 @see #1184 label.x = centroid[0]; label.y = centroid[1]; } else { label.x = getDimValue(point.x, index); label.y = getDimValue(point.y, index); } // get nearest point of the shape as the label line start point if (point && point.nextPoints && (point.shape === 'funnel' || point.shape === 'pyramid')) { var maxX = -Infinity; point.nextPoints.forEach(function (p) { p = coord.convert(p); if (p.x > maxX) { maxX = p.x; } }); label.x = (label.x + maxX) / 2; } // sharp edge of the pyramid if (point.shape === 'pyramid' && !point.nextPoints && point.points) { point.points.forEach(function (p) { p = coord.convert(p); if (Util.isArray(p.x) && !point.x.includes(p.x) || Util.isNumber(p.x) && point.x !== p.x) { label.x = (label.x + p.x) / 2; } }); } if (labelCfg.position) { self.setLabelPosition(label, point, index, labelCfg.position); } var offsetPoint = self.getLabelOffset(labelCfg, index, total); if (labelCfg.offsetX) { offsetPoint.x += labelCfg.offsetX; } if (labelCfg.offsetY) { offsetPoint.y += labelCfg.offsetY; } self.transLabelPoint(label); label.start = { x: label.x, y: label.y }; label.x += offsetPoint.x; label.y += offsetPoint.y; label.color = point.color; return label; }, setLabelPosition: function setLabelPosition() {}, transLabelPoint: function transLabelPoint(point) { var self = this; var coord = self.get('coord'); var tmpPoint = coord.applyMatrix(point.x, point.y, 1); point.x = tmpPoint[0]; point.y = tmpPoint[1]; }, getOffsetVector: function getOffsetVector(point) { var self = this; var offset = point.offset || 0; var coord = self.get('coord'); var vector; if (coord.isTransposed) { // 如果x,y翻转,则偏移x vector = coord.applyMatrix(offset, 0); } else { // 否则,偏转y vector = coord.applyMatrix(0, offset); } return vector; }, // 获取默认的偏移量 getDefaultOffset: function getDefaultOffset(point) { var self = this; var offset = 0; var coord = self.get('coord'); var vector = self.getOffsetVector(point); if (coord.isTransposed) { // 如果x,y翻转,则偏移x offset = vector[0]; } else { // 否则,偏转y offset = vector[1]; } var yScale = this.get('yScale'); if (yScale && point.point) { // 仅考虑 y 单值的情况,多值的情况在这里不考虑 var yValue = point.point[yScale.field]; if (yValue < 0) { offset = offset * -1; // 如果 y 值是负值,则反向 } } return offset; }, // 获取文本的偏移位置,x,y getLabelOffset: function getLabelOffset(point, index, total) { var self = this; var offset = self.getDefaultOffset(point); var coord = self.get('coord'); var transposed = coord.isTransposed; var yField = transposed ? 'x' : 'y'; var factor = transposed ? 1 : -1; // y 方向上越大,像素的坐标越小,所以transposed时将系数变成 var offsetPoint = { x: 0, y: 0 }; if (index > 0 || total === 1) { // 判断是否小于0 offsetPoint[yField] = offset * factor; } else { offsetPoint[yField] = offset * factor * -1; } return offsetPoint; }, getLabelAlign: function getLabelAlign(point, index, total) { var self = this; var align = 'center'; var coord = self.get('coord'); if (coord.isTransposed) { var offset = self.getDefaultOffset(point); // var vector = coord.applyMatrix(offset,0); if (offset < 0) { align = 'right'; } else if (offset === 0) { align = 'center'; } else { align = 'left'; } if (total > 1 && index === 0) { if (align === 'right') { align = 'left'; } else if (align === 'left') { align = 'right'; } } } return align; }, _getLabelValue: function _getLabelValue(origin, scales) { if (!Util.isArray(scales)) { scales = [scales]; } var text = []; Util.each(scales, function (scale) { var value = origin[scale.field]; if (Util.isArray(value)) { var tmp = []; Util.each(value, function (subVal) { tmp.push(scale.getText(subVal)); }); value = tmp; } else { value = scale.getText(value); } if (Util.isNil(value) || value === '') { text.push(null); } text.push(value); }); return text; }, // 获取每个label的配置 _getLabelCfgs: function _getLabelCfgs(points) { var self = this; var labelCfg = this.get('labelCfg'); var scales = labelCfg.scales; var defaultCfg = this.get('label'); var viewTheme = self.get('viewTheme') || Global; var cfgs = []; if (labelCfg.globalCfg && labelCfg.globalCfg.type) { self.set('type', labelCfg.globalCfg.type); } Util.each(points, function (point, i) { var cfg = {}; var origin = point[ORIGIN]; var originText = self._getLabelValue(origin, scales); if (labelCfg.callback) { // callback中应使用原始数据,而不是数据字符串 var originValues = scales.map(function (scale) { return origin[scale.field]; }); // 将point信息以及index信息也返回,方便能够根据point以及index,返回不同的配置 cfg = labelCfg.callback.apply(null, [].concat(originValues, [point, i])); } if (!cfg && cfg !== 0) { cfgs.push(null); return; } if (Util.isString(cfg) || Util.isNumber(cfg)) { cfg = { text: cfg }; } else { cfg.text = cfg.content || originText[0]; delete cfg.content; } cfg = Util.mix({}, defaultCfg, labelCfg.globalCfg || {}, cfg); // 兼容旧的源数据写在item.point中 point.point = origin; cfg.point = origin; if (cfg.htmlTemplate) { cfg.useHtml = true; cfg.text = cfg.htmlTemplate.call(null, cfg.text, point, i); delete cfg.htmlTemplate; } if (cfg.formatter) { cfg.text = cfg.formatter.call(null, cfg.text, point, i); delete cfg.formatter; } if (cfg.label) { // 兼容有些直接写在labelCfg.label的配置 var label = cfg.label; delete cfg.label; cfg = Util.mix(cfg, label); } if (cfg.textStyle) { // 兼容旧写法,globalCfg的offset优先级高 delete cfg.textStyle.offset; var textStyle = cfg.textStyle; if (Util.isFunction(textStyle)) { cfg.textStyle = textStyle.call(null, cfg.text, point, i); } } if (cfg.labelLine) { cfg.labelLine = Util.mix({}, defaultCfg.labelLine, cfg.labelLine); } // 因为 defaultCfg.textStyle 有可能是函数,所以这里可能没有把主题的 label 样式合进来 cfg.textStyle = Util.mix({}, defaultCfg.textStyle, viewTheme.label.textStyle, cfg.textStyle); delete cfg.items; cfgs.push(cfg); }); this.set('labelItemCfgs', cfgs); }, showLabels: function showLabels(points, shapes) { var self = this; var labelRenderer = self.get('labelRenderer'); var items = self.getLabelsItems(points, shapes); shapes = [].concat(shapes); var type = self.get('type'); items = self.adjustItems(items, shapes); self.drawLines(items); labelRenderer.set('items', items.filter(function (item, i) { if (!item) { shapes.splice(i, 1); return false; } return true; })); if (type) { labelRenderer.set('shapes', shapes); labelRenderer.set('type', type); labelRenderer.set('points', points); } labelRenderer.set('canvas', this.get('canvas')); labelRenderer.draw(); }, destroy: function destroy() { this.get('labelRenderer').destroy(); // 清理文本 GeomLabels.superclass.destroy.call(this); } }); // Util.assign(GeomLabels.prototype, Labels.LabelslabelRenderer); module.exports = GeomLabels; /***/ }), /* 92 */ /***/ (function(module, exports, __webpack_require__) { function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @fileOverview Chart、View、Geometry 的基类 * @author dxq613@gmail.com */ var EventEmitter = __webpack_require__(90); var Util = __webpack_require__(4); var Base = /*#__PURE__*/function (_EventEmitter) { _inheritsLoose(Base, _EventEmitter); var _proto = Base.prototype; _proto.getDefaultCfg = function getDefaultCfg() { return {}; }; function Base(cfg) { var _this; _this = _EventEmitter.call(this) || this; var self = _assertThisInitialized(_this); var attrs = { visible: true }; var defaultCfg = self.getDefaultCfg(); self._attrs = attrs; Util.deepMix(attrs, defaultCfg, cfg); return _this; } _proto.get = function get(name) { return this._attrs[name]; }; _proto.set = function set(name, value) { this._attrs[name] = value; } /** * @protected * @param {Boolean} visible 是否可见 * 显示、隐藏 */ ; _proto.changeVisible = function changeVisible() {}; _proto.destroy = function destroy() { var self = this; self._attrs = {}; self.removeAllListeners(); self.destroyed = true; }; return Base; }(EventEmitter); module.exports = Base; /***/ }), /* 93 */ /***/ (function(module, exports, __webpack_require__) { var Line = __webpack_require__(52); var Quadratic = __webpack_require__(173); var Cubic = __webpack_require__(94); var Arc = __webpack_require__(53); module.exports = { line: function line(x1, y1, x2, y2, lineWidth, x, y) { var box = Line.box(x1, y1, x2, y2, lineWidth); if (!this.box(box.minX, box.maxX, box.minY, box.maxY, x, y)) { return false; } var d = Line.pointDistance(x1, y1, x2, y2, x, y); if (isNaN(d)) { return false; } return d <= lineWidth / 2; }, polyline: function polyline(points, lineWidth, x, y) { var l = points.length - 1; if (l < 1) { return false; } for (var i = 0; i < l; i++) { var x1 = points[i][0]; var y1 = points[i][1]; var x2 = points[i + 1][0]; var y2 = points[i + 1][1]; if (this.line(x1, y1, x2, y2, lineWidth, x, y)) { return true; } } return false; }, cubicline: function cubicline(x1, y1, x2, y2, x3, y3, x4, y4, lineWidth, x, y) { return Cubic.pointDistance(x1, y1, x2, y2, x3, y3, x4, y4, x, y) <= lineWidth / 2; }, quadraticline: function quadraticline(x1, y1, x2, y2, x3, y3, lineWidth, x, y) { return Quadratic.pointDistance(x1, y1, x2, y2, x3, y3, x, y) <= lineWidth / 2; }, arcline: function arcline(cx, cy, r, startAngle, endAngle, clockwise, lineWidth, x, y) { return Arc.pointDistance(cx, cy, r, startAngle, endAngle, clockwise, x, y) <= lineWidth / 2; }, rect: function rect(rx, ry, width, height, x, y) { return rx <= x && x <= rx + width && ry <= y && y <= ry + height; }, circle: function circle(cx, cy, r, x, y) { return Math.pow(x - cx, 2) + Math.pow(y - cy, 2) <= Math.pow(r, 2); }, box: function box(minX, maxX, minY, maxY, x, y) { return minX <= x && x <= maxX && minY <= y && y <= maxY; } }; /***/ }), /* 94 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var vec2 = Util.vec2; function cubicAt(p0, p1, p2, p3, t) { var onet = 1 - t; return onet * onet * (onet * p3 + 3 * t * p2) + t * t * (t * p0 + 3 * onet * p1); } function cubicDerivativeAt(p0, p1, p2, p3, t) { var onet = 1 - t; return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet + (p3 - p2) * t * t); } function cubicProjectPoint(x1, y1, x2, y2, x3, y3, x4, y4, x, y, out) { var t; var interval = 0.005; var d = Infinity; var _t; var v1; var d1; var d2; var v2; var prev; var next; var EPSILON = 0.0001; var v0 = [x, y]; for (_t = 0; _t < 1; _t += 0.05) { v1 = [cubicAt(x1, x2, x3, x4, _t), cubicAt(y1, y2, y3, y4, _t)]; d1 = vec2.squaredDistance(v0, v1); if (d1 < d) { t = _t; d = d1; } } d = Infinity; for (var i = 0; i < 32; i++) { if (interval < EPSILON) { break; } prev = t - interval; next = t + interval; v1 = [cubicAt(x1, x2, x3, x4, prev), cubicAt(y1, y2, y3, y4, prev)]; d1 = vec2.squaredDistance(v0, v1); if (prev >= 0 && d1 < d) { t = prev; d = d1; } else { v2 = [cubicAt(x1, x2, x3, x4, next), cubicAt(y1, y2, y3, y4, next)]; d2 = vec2.squaredDistance(v0, v2); if (next <= 1 && d2 < d) { t = next; d = d2; } else { interval *= 0.5; } } } if (out) { out.x = cubicAt(x1, x2, x3, x4, t); out.y = cubicAt(y1, y2, y3, y4, t); } return Math.sqrt(d); } function cubicExtrema(p0, p1, p2, p3) { var a = 3 * p0 - 9 * p1 + 9 * p2 - 3 * p3; var b = 6 * p1 - 12 * p2 + 6 * p3; var c = 3 * p2 - 3 * p3; var extrema = []; var t1; var t2; var discSqrt; if (Util.isNumberEqual(a, 0)) { if (!Util.isNumberEqual(b, 0)) { t1 = -c / b; if (t1 >= 0 && t1 <= 1) { extrema.push(t1); } } } else { var disc = b * b - 4 * a * c; if (Util.isNumberEqual(disc, 0)) { extrema.push(-b / (2 * a)); } else if (disc > 0) { discSqrt = Math.sqrt(disc); t1 = (-b + discSqrt) / (2 * a); t2 = (-b - discSqrt) / (2 * a); if (t1 >= 0 && t1 <= 1) { extrema.push(t1); } if (t2 >= 0 && t2 <= 1) { extrema.push(t2); } } } return extrema; } function base3(t, p1, p2, p3, p4) { var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4; var t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; return t * t2 - 3 * p1 + 3 * p2; } function cubiclLen(x1, y1, x2, y2, x3, y3, x4, y4, z) { if (Util.isNil(z)) { z = 1; } z = z > 1 ? 1 : z < 0 ? 0 : z; var z2 = z / 2; var n = 12; var Tvalues = [-0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699, -0.9041, 0.9041, -0.9816, 0.9816]; var Cvalues = [0.2491, 0.2491, 0.2335, 0.2335, 0.2032, 0.2032, 0.1601, 0.1601, 0.1069, 0.1069, 0.0472, 0.0472]; var sum = 0; for (var i = 0; i < n; i++) { var ct = z2 * Tvalues[i] + z2; var xbase = base3(ct, x1, x2, x3, x4); var ybase = base3(ct, y1, y2, y3, y4); var comb = xbase * xbase + ybase * ybase; sum += Cvalues[i] * Math.sqrt(comb); } return z2 * sum; } module.exports = { at: cubicAt, derivativeAt: cubicDerivativeAt, projectPoint: function projectPoint(x1, y1, x2, y2, x3, y3, x4, y4, x, y) { var rst = {}; cubicProjectPoint(x1, y1, x2, y2, x3, y3, x4, y4, x, y, rst); return rst; }, pointDistance: cubicProjectPoint, extrema: cubicExtrema, len: cubiclLen }; /***/ }), /* 95 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Shape = __webpack_require__(9); var Format = __webpack_require__(37); var PathSegment = __webpack_require__(55); var Marker = function Marker(cfg) { Marker.superclass.constructor.call(this, cfg); }; Marker.Symbols = { // 圆 circle: function circle(x, y, r) { return [['M', x, y], ['m', -r, 0], ['a', r, r, 0, 1, 0, r * 2, 0], ['a', r, r, 0, 1, 0, -r * 2, 0]]; }, // 正方形 square: function square(x, y, r) { return [['M', x - r, y - r], ['L', x + r, y - r], ['L', x + r, y + r], ['L', x - r, y + r], ['Z']]; }, // 菱形 diamond: function diamond(x, y, r) { return [['M', x - r, y], ['L', x, y - r], ['L', x + r, y], ['L', x, y + r], ['Z']]; }, // 三角形 triangle: function triangle(x, y, r) { var diffY = r * Math.sin(1 / 3 * Math.PI); return [['M', x - r, y + diffY], ['L', x, y - diffY], ['L', x + r, y + diffY], ['z']]; }, // 倒三角形 'triangle-down': function triangleDown(x, y, r) { var diffY = r * Math.sin(1 / 3 * Math.PI); return [['M', x - r, y - diffY], ['L', x + r, y - diffY], ['L', x, y + diffY], ['Z']]; } }; Marker.ATTRS = { path: null, lineWidth: 1 }; Util.extend(Marker, Shape); Util.augment(Marker, { type: 'marker', canFill: true, canStroke: true, getDefaultAttrs: function getDefaultAttrs() { return { x: 0, y: 0, lineWidth: 1 }; }, calculateBox: function calculateBox() { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var r = attrs.radius; var lineWidth = this.getHitLineWidth(); var halfWidth = lineWidth / 2 + r; return { minX: cx - halfWidth, minY: cy - halfWidth, maxX: cx + halfWidth, maxY: cy + halfWidth }; }, _getPath: function _getPath() { var attrs = this._attrs; var x = attrs.x; var y = attrs.y; var r = attrs.radius || attrs.r; var symbol = attrs.symbol || 'circle'; var method; if (Util.isFunction(symbol)) { method = symbol; } else { method = Marker.Symbols[symbol]; } if (!method) { console.warn(symbol + " marker is not supported."); return null; } return method(x, y, r); }, createPath: function createPath(context) { var segments = this._cfg.segments; if (segments && !this._cfg.hasUpdate) { context.beginPath(); for (var i = 0; i < segments.length; i++) { segments[i].draw(context); } return; } var path = Format.parsePath(this._getPath()); context.beginPath(); var preSegment; segments = []; for (var _i = 0; _i < path.length; _i++) { var item = path[_i]; preSegment = new PathSegment(item, preSegment, _i === path.length - 1); segments.push(preSegment); preSegment.draw(context); } this._cfg.segments = segments; this._cfg.hasUpdate = false; } }); module.exports = Marker; /***/ }), /* 96 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(169); var SPACES = "\t\n\x0B\f\r \xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029"; var PATH_COMMAND = new RegExp('([a-z])[' + SPACES + ',]*((-?\\d*\\.?\\d*(?:e[\\-+]?\\d+)?[' + SPACES + ']*,?[' + SPACES + ']*)+)', 'ig'); var PATH_VALUES = new RegExp('(-?\\d*\\.?\\d*(?:e[\\-+]?\\d+)?)[' + SPACES + ']*,?[' + SPACES + ']*', 'ig'); // Parses given path string into an array of arrays of path segments var parsePathString = function parsePathString(pathString) { if (!pathString) { return null; } if (typeof pathString === typeof []) { return pathString; } var paramCounts = { a: 7, c: 6, o: 2, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, u: 3, z: 0 }; var data = []; String(pathString).replace(PATH_COMMAND, function (a, b, c) { var params = []; var name = b.toLowerCase(); c.replace(PATH_VALUES, function (a, b) { b && params.push(+b); }); if (name === 'm' && params.length > 2) { data.push([b].concat(params.splice(0, 2))); name = 'l'; b = b === 'm' ? 'l' : 'L'; } if (name === 'o' && params.length === 1) { data.push([b, params[0]]); } if (name === 'r') { data.push([b].concat(params)); } else { while (params.length >= paramCounts[name]) { data.push([b].concat(params.splice(0, paramCounts[name]))); if (!paramCounts[name]) { break; } } } }); return data; }; // http://schepers.cc/getting-to-the-point var catmullRom2bezier = function catmullRom2bezier(crp, z) { var d = []; for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { var p = [{ x: +crp[i - 2], y: +crp[i - 1] }, { x: +crp[i], y: +crp[i + 1] }, { x: +crp[i + 2], y: +crp[i + 3] }, { x: +crp[i + 4], y: +crp[i + 5] }]; if (z) { if (!i) { p[0] = { x: +crp[iLen - 2], y: +crp[iLen - 1] }; } else if (iLen - 4 === i) { p[3] = { x: +crp[0], y: +crp[1] }; } else if (iLen - 2 === i) { p[2] = { x: +crp[0], y: +crp[1] }; p[3] = { x: +crp[2], y: +crp[3] }; } } else { if (iLen - 4 === i) { p[3] = p[2]; } else if (!i) { p[0] = { x: +crp[i], y: +crp[i + 1] }; } } d.push(['C', (-p[0].x + 6 * p[1].x + p[2].x) / 6, (-p[0].y + 6 * p[1].y + p[2].y) / 6, (p[1].x + 6 * p[2].x - p[3].x) / 6, (p[1].y + 6 * p[2].y - p[3].y) / 6, p[2].x, p[2].y]); } return d; }; var ellipsePath = function ellipsePath(x, y, rx, ry, a) { var res = []; if (a === null && ry === null) { ry = rx; } x = +x; y = +y; rx = +rx; ry = +ry; if (a !== null) { var rad = Math.PI / 180; var x1 = x + rx * Math.cos(-ry * rad); var x2 = x + rx * Math.cos(-a * rad); var y1 = y + rx * Math.sin(-ry * rad); var y2 = y + rx * Math.sin(-a * rad); res = [['M', x1, y1], ['A', rx, rx, 0, +(a - ry > 180), 0, x2, y2]]; } else { res = [['M', x, y], ['m', 0, -ry], ['a', rx, ry, 0, 1, 1, 0, 2 * ry], ['a', rx, ry, 0, 1, 1, 0, -2 * ry], ['z']]; } return res; }; var pathToAbsolute = function pathToAbsolute(pathArray) { pathArray = parsePathString(pathArray); if (!pathArray || !pathArray.length) { return [['M', 0, 0]]; } var res = []; var x = 0; var y = 0; var mx = 0; var my = 0; var start = 0; var pa0; var dots; if (pathArray[0][0] === 'M') { x = +pathArray[0][1]; y = +pathArray[0][2]; mx = x; my = y; start++; res[0] = ['M', x, y]; } var crz = pathArray.length === 3 && pathArray[0][0] === 'M' && pathArray[1][0].toUpperCase() === 'R' && pathArray[2][0].toUpperCase() === 'Z'; for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) { res.push(r = []); pa = pathArray[i]; pa0 = pa[0]; if (pa0 !== pa0.toUpperCase()) { r[0] = pa0.toUpperCase(); switch (r[0]) { case 'A': r[1] = pa[1]; r[2] = pa[2]; r[3] = pa[3]; r[4] = pa[4]; r[5] = pa[5]; r[6] = +pa[6] + x; r[7] = +pa[7] + y; break; case 'V': r[1] = +pa[1] + y; break; case 'H': r[1] = +pa[1] + x; break; case 'R': dots = [x, y].concat(pa.slice(1)); for (var j = 2, jj = dots.length; j < jj; j++) { dots[j] = +dots[j] + x; dots[++j] = +dots[j] + y; } res.pop(); res = res.concat(catmullRom2bezier(dots, crz)); break; case 'O': res.pop(); dots = ellipsePath(x, y, pa[1], pa[2]); dots.push(dots[0]); res = res.concat(dots); break; case 'U': res.pop(); res = res.concat(ellipsePath(x, y, pa[1], pa[2], pa[3])); r = ['U'].concat(res[res.length - 1].slice(-2)); break; case 'M': mx = +pa[1] + x; my = +pa[2] + y; break; // for lint default: for (var _j = 1, _jj = pa.length; _j < _jj; _j++) { r[_j] = +pa[_j] + (_j % 2 ? x : y); } } } else if (pa0 === 'R') { dots = [x, y].concat(pa.slice(1)); res.pop(); res = res.concat(catmullRom2bezier(dots, crz)); r = ['R'].concat(pa.slice(-2)); } else if (pa0 === 'O') { res.pop(); dots = ellipsePath(x, y, pa[1], pa[2]); dots.push(dots[0]); res = res.concat(dots); } else if (pa0 === 'U') { res.pop(); res = res.concat(ellipsePath(x, y, pa[1], pa[2], pa[3])); r = ['U'].concat(res[res.length - 1].slice(-2)); } else { for (var k = 0, kk = pa.length; k < kk; k++) { r[k] = pa[k]; } } pa0 = pa0.toUpperCase(); if (pa0 !== 'O') { switch (r[0]) { case 'Z': x = +mx; y = +my; break; case 'H': x = r[1]; break; case 'V': y = r[1]; break; case 'M': mx = r[r.length - 2]; my = r[r.length - 1]; break; // for lint default: x = r[r.length - 2]; y = r[r.length - 1]; } } } return res; }; var l2c = function l2c(x1, y1, x2, y2) { return [x1, y1, x2, y2, x2, y2]; }; var q2c = function q2c(x1, y1, ax, ay, x2, y2) { var _13 = 1 / 3; var _23 = 2 / 3; return [_13 * x1 + _23 * ax, _13 * y1 + _23 * ay, _13 * x2 + _23 * ax, _13 * y2 + _23 * ay, x2, y2]; }; var a2c = function a2c(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { // for more information of where this math came from visit: // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes if (rx === ry) { rx += 1; } var _120 = Math.PI * 120 / 180; var rad = Math.PI / 180 * (+angle || 0); var res = []; var xy; var f1; var f2; var cx; var cy; var rotate = function rotate(x, y, rad) { var X = x * Math.cos(rad) - y * Math.sin(rad); var Y = x * Math.sin(rad) + y * Math.cos(rad); return { x: X, y: Y }; }; if (!recursive) { xy = rotate(x1, y1, -rad); x1 = xy.x; y1 = xy.y; xy = rotate(x2, y2, -rad); x2 = xy.x; y2 = xy.y; if (x1 === x2 && y1 === y2) { // 若弧的起始点和终点重叠则错开一点 x2 += 1; y2 += 1; } // const cos = Math.cos(Math.PI / 180 * angle); // const sin = Math.sin(Math.PI / 180 * angle); var x = (x1 - x2) / 2; var y = (y1 - y2) / 2; var h = x * x / (rx * rx) + y * y / (ry * ry); if (h > 1) { h = Math.sqrt(h); rx = h * rx; ry = h * ry; } var rx2 = rx * rx; var ry2 = ry * ry; var k = (large_arc_flag === sweep_flag ? -1 : 1) * Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))); cx = k * rx * y / ry + (x1 + x2) / 2; cy = k * -ry * x / rx + (y1 + y2) / 2; f1 = Math.asin(((y1 - cy) / ry).toFixed(9)); f2 = Math.asin(((y2 - cy) / ry).toFixed(9)); f1 = x1 < cx ? Math.PI - f1 : f1; f2 = x2 < cx ? Math.PI - f2 : f2; f1 < 0 && (f1 = Math.PI * 2 + f1); f2 < 0 && (f2 = Math.PI * 2 + f2); if (sweep_flag && f1 > f2) { f1 = f1 - Math.PI * 2; } if (!sweep_flag && f2 > f1) { f2 = f2 - Math.PI * 2; } } else { f1 = recursive[0]; f2 = recursive[1]; cx = recursive[2]; cy = recursive[3]; } var df = f2 - f1; if (Math.abs(df) > _120) { var f2old = f2; var x2old = x2; var y2old = y2; f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1); x2 = cx + rx * Math.cos(f2); y2 = cy + ry * Math.sin(f2); res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]); } df = f2 - f1; var c1 = Math.cos(f1); var s1 = Math.sin(f1); var c2 = Math.cos(f2); var s2 = Math.sin(f2); var t = Math.tan(df / 4); var hx = 4 / 3 * rx * t; var hy = 4 / 3 * ry * t; var m1 = [x1, y1]; var m2 = [x1 + hx * s1, y1 - hy * c1]; var m3 = [x2 + hx * s2, y2 - hy * c2]; var m4 = [x2, y2]; m2[0] = 2 * m1[0] - m2[0]; m2[1] = 2 * m1[1] - m2[1]; if (recursive) { return [m2, m3, m4].concat(res); } res = [m2, m3, m4].concat(res).join().split(','); var newres = []; for (var i = 0, ii = res.length; i < ii; i++) { newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; } return newres; }; var pathTocurve = function pathTocurve(path, path2) { var p = pathToAbsolute(path); var p2 = path2 && pathToAbsolute(path2); var attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }; var attrs2 = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }; var pcoms1 = []; // path commands of original path p var pcoms2 = []; // path commands of original path p2 var pfirst = ''; // temporary holder for original path command var pcom = ''; // holder for previous path command of original path var ii; var processPath = function processPath(path, d, pcom) { var nx, ny; if (!path) { return ['C', d.x, d.y, d.x, d.y, d.x, d.y]; } !(path[0] in { T: 1, Q: 1 }) && (d.qx = d.qy = null); switch (path[0]) { case 'M': d.X = path[1]; d.Y = path[2]; break; case 'A': path = ['C'].concat(a2c.apply(0, [d.x, d.y].concat(path.slice(1)))); break; case 'S': if (pcom === 'C' || pcom === 'S') { // In "S" case we have to take into account, if the previous command is C/S. nx = d.x * 2 - d.bx; // And reflect the previous ny = d.y * 2 - d.by; // command's control point relative to the current point. } else { // or some else or nothing nx = d.x; ny = d.y; } path = ['C', nx, ny].concat(path.slice(1)); break; case 'T': if (pcom === 'Q' || pcom === 'T') { // In "T" case we have to take into account, if the previous command is Q/T. d.qx = d.x * 2 - d.qx; // And make a reflection similar d.qy = d.y * 2 - d.qy; // to case "S". } else { // or something else or nothing d.qx = d.x; d.qy = d.y; } path = ['C'].concat(q2c(d.x, d.y, d.qx, d.qy, path[1], path[2])); break; case 'Q': d.qx = path[1]; d.qy = path[2]; path = ['C'].concat(q2c(d.x, d.y, path[1], path[2], path[3], path[4])); break; case 'L': path = ['C'].concat(l2c(d.x, d.y, path[1], path[2])); break; case 'H': path = ['C'].concat(l2c(d.x, d.y, path[1], d.y)); break; case 'V': path = ['C'].concat(l2c(d.x, d.y, d.x, path[1])); break; case 'Z': path = ['C'].concat(l2c(d.x, d.y, d.X, d.Y)); break; default: break; } return path; }; var fixArc = function fixArc(pp, i) { if (pp[i].length > 7) { pp[i].shift(); var pi = pp[i]; while (pi.length) { pcoms1[i] = 'A'; // if created multiple C:s, their original seg is saved p2 && (pcoms2[i] = 'A'); // the same as above pp.splice(i++, 0, ['C'].concat(pi.splice(0, 6))); } pp.splice(i, 1); ii = Math.max(p.length, p2 && p2.length || 0); } }; var fixM = function fixM(path1, path2, a1, a2, i) { if (path1 && path2 && path1[i][0] === 'M' && path2[i][0] !== 'M') { path2.splice(i, 0, ['M', a2.x, a2.y]); a1.bx = 0; a1.by = 0; a1.x = path1[i][1]; a1.y = path1[i][2]; ii = Math.max(p.length, p2 && p2.length || 0); } }; ii = Math.max(p.length, p2 && p2.length || 0); for (var i = 0; i < ii; i++) { p[i] && (pfirst = p[i][0]); // save current path command if (pfirst !== 'C') { // C is not saved yet, because it may be result of conversion pcoms1[i] = pfirst; // Save current path command i && (pcom = pcoms1[i - 1]); // Get previous path command pcom } p[i] = processPath(p[i], attrs, pcom); // Previous path command is inputted to processPath if (pcoms1[i] !== 'A' && pfirst === 'C') pcoms1[i] = 'C'; // A is the only command // which may produce multiple C:s // so we have to make sure that C is also C in original path fixArc(p, i); // fixArc adds also the right amount of A:s to pcoms1 if (p2) { // the same procedures is done to p2 p2[i] && (pfirst = p2[i][0]); if (pfirst !== 'C') { pcoms2[i] = pfirst; i && (pcom = pcoms2[i - 1]); } p2[i] = processPath(p2[i], attrs2, pcom); if (pcoms2[i] !== 'A' && pfirst === 'C') { pcoms2[i] = 'C'; } fixArc(p2, i); } fixM(p, p2, attrs, attrs2, i); fixM(p2, p, attrs2, attrs, i); var seg = p[i]; var seg2 = p2 && p2[i]; var seglen = seg.length; var seg2len = p2 && seg2.length; attrs.x = seg[seglen - 2]; attrs.y = seg[seglen - 1]; attrs.bx = parseFloat(seg[seglen - 4]) || attrs.x; attrs.by = parseFloat(seg[seglen - 3]) || attrs.y; attrs2.bx = p2 && (parseFloat(seg2[seg2len - 4]) || attrs2.x); attrs2.by = p2 && (parseFloat(seg2[seg2len - 3]) || attrs2.y); attrs2.x = p2 && seg2[seg2len - 2]; attrs2.y = p2 && seg2[seg2len - 1]; } return p2 ? [p, p2] : p; }; var p2s = /,?([a-z]),?/gi; var parsePathArray = function parsePathArray(path) { return path.join(',').replace(p2s, '$1'); }; var base3 = function base3(t, p1, p2, p3, p4) { var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4; var t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; return t * t2 - 3 * p1 + 3 * p2; }; var bezlen = function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { if (z === null) { z = 1; } z = z > 1 ? 1 : z < 0 ? 0 : z; var z2 = z / 2; var n = 12; var Tvalues = [-0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699, -0.9041, 0.9041, -0.9816, 0.9816]; var Cvalues = [0.2491, 0.2491, 0.2335, 0.2335, 0.2032, 0.2032, 0.1601, 0.1601, 0.1069, 0.1069, 0.0472, 0.0472]; var sum = 0; for (var i = 0; i < n; i++) { var ct = z2 * Tvalues[i] + z2; var xbase = base3(ct, x1, x2, x3, x4); var ybase = base3(ct, y1, y2, y3, y4); var comb = xbase * xbase + ybase * ybase; sum += Cvalues[i] * Math.sqrt(comb); } return z2 * sum; }; var curveDim = function curveDim(x0, y0, x1, y1, x2, y2, x3, y3) { var tvalues = []; var bounds = [[], []]; var a; var b; var c; var t; for (var i = 0; i < 2; ++i) { if (i === 0) { b = 6 * x0 - 12 * x1 + 6 * x2; a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3; c = 3 * x1 - 3 * x0; } else { b = 6 * y0 - 12 * y1 + 6 * y2; a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3; c = 3 * y1 - 3 * y0; } if (Math.abs(a) < 1e-12) { if (Math.abs(b) < 1e-12) { continue; } t = -c / b; if (t > 0 && t < 1) { tvalues.push(t); } continue; } var b2ac = b * b - 4 * c * a; var sqrtb2ac = Math.sqrt(b2ac); if (b2ac < 0) { continue; } var t1 = (-b + sqrtb2ac) / (2 * a); if (t1 > 0 && t1 < 1) { tvalues.push(t1); } var t2 = (-b - sqrtb2ac) / (2 * a); if (t2 > 0 && t2 < 1) { tvalues.push(t2); } } var j = tvalues.length; var jlen = j; var mt; while (j--) { t = tvalues[j]; mt = 1 - t; bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3; bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3; } bounds[0][jlen] = x0; bounds[1][jlen] = y0; bounds[0][jlen + 1] = x3; bounds[1][jlen + 1] = y3; bounds[0].length = bounds[1].length = jlen + 2; return { min: { x: Math.min.apply(0, bounds[0]), y: Math.min.apply(0, bounds[1]) }, max: { x: Math.max.apply(0, bounds[0]), y: Math.max.apply(0, bounds[1]) } }; }; var intersect = function intersect(x1, y1, x2, y2, x3, y3, x4, y4) { if (Math.max(x1, x2) < Math.min(x3, x4) || Math.min(x1, x2) > Math.max(x3, x4) || Math.max(y1, y2) < Math.min(y3, y4) || Math.min(y1, y2) > Math.max(y3, y4)) { return; } var nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4); var ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4); var denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); if (!denominator) { return; } var px = nx / denominator; var py = ny / denominator; var px2 = +px.toFixed(2); var py2 = +py.toFixed(2); if (px2 < +Math.min(x1, x2).toFixed(2) || px2 > +Math.max(x1, x2).toFixed(2) || px2 < +Math.min(x3, x4).toFixed(2) || px2 > +Math.max(x3, x4).toFixed(2) || py2 < +Math.min(y1, y2).toFixed(2) || py2 > +Math.max(y1, y2).toFixed(2) || py2 < +Math.min(y3, y4).toFixed(2) || py2 > +Math.max(y3, y4).toFixed(2)) { return; } return { x: px, y: py }; }; var isPointInsideBBox = function isPointInsideBBox(bbox, x, y) { return x >= bbox.x && x <= bbox.x + bbox.width && y >= bbox.y && y <= bbox.y + bbox.height; }; var rectPath = function rectPath(x, y, w, h, r) { if (r) { return [['M', +x + +r, y], ['l', w - r * 2, 0], ['a', r, r, 0, 0, 1, r, r], ['l', 0, h - r * 2], ['a', r, r, 0, 0, 1, -r, r], ['l', r * 2 - w, 0], ['a', r, r, 0, 0, 1, -r, -r], ['l', 0, r * 2 - h], ['a', r, r, 0, 0, 1, r, -r], ['z']]; } var res = [['M', x, y], ['l', w, 0], ['l', 0, h], ['l', -w, 0], ['z']]; res.parsePathArray = parsePathArray; return res; }; var box = function box(x, y, width, height) { if (x === null) { x = y = width = height = 0; } if (y === null) { y = x.y; width = x.width; height = x.height; x = x.x; } return { x: x, y: y, width: width, w: width, height: height, h: height, x2: x + width, y2: y + height, cx: x + width / 2, cy: y + height / 2, r1: Math.min(width, height) / 2, r2: Math.max(width, height) / 2, r0: Math.sqrt(width * width + height * height) / 2, path: rectPath(x, y, width, height), vb: [x, y, width, height].join(' ') }; }; var isBBoxIntersect = function isBBoxIntersect(bbox1, bbox2) { bbox1 = box(bbox1); bbox2 = box(bbox2); return isPointInsideBBox(bbox2, bbox1.x, bbox1.y) || isPointInsideBBox(bbox2, bbox1.x2, bbox1.y) || isPointInsideBBox(bbox2, bbox1.x, bbox1.y2) || isPointInsideBBox(bbox2, bbox1.x2, bbox1.y2) || isPointInsideBBox(bbox1, bbox2.x, bbox2.y) || isPointInsideBBox(bbox1, bbox2.x2, bbox2.y) || isPointInsideBBox(bbox1, bbox2.x, bbox2.y2) || isPointInsideBBox(bbox1, bbox2.x2, bbox2.y2) || (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x) && (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y); }; var bezierBBox = function bezierBBox(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) { if (!Util.isArray(p1x)) { p1x = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y]; } var bbox = curveDim.apply(null, p1x); return box(bbox.min.x, bbox.min.y, bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y); }; var findDotsAtSegment = function findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { var t1 = 1 - t; var t13 = Math.pow(t1, 3); var t12 = Math.pow(t1, 2); var t2 = t * t; var t3 = t2 * t; var x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x; var y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y; var mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x); var my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y); var nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x); var ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y); var ax = t1 * p1x + t * c1x; var ay = t1 * p1y + t * c1y; var cx = t1 * c2x + t * p2x; var cy = t1 * c2y + t * p2y; var alpha = 90 - Math.atan2(mx - nx, my - ny) * 180 / Math.PI; // (mx > nx || my < ny) && (alpha += 180); return { x: x, y: y, m: { x: mx, y: my }, n: { x: nx, y: ny }, start: { x: ax, y: ay }, end: { x: cx, y: cy }, alpha: alpha }; }; var interHelper = function interHelper(bez1, bez2, justCount) { var bbox1 = bezierBBox(bez1); var bbox2 = bezierBBox(bez2); if (!isBBoxIntersect(bbox1, bbox2)) { return justCount ? 0 : []; } var l1 = bezlen.apply(0, bez1); var l2 = bezlen.apply(0, bez2); var n1 = ~~(l1 / 8); var n2 = ~~(l2 / 8); var dots1 = []; var dots2 = []; var xy = {}; var res = justCount ? 0 : []; for (var i = 0; i < n1 + 1; i++) { var d = findDotsAtSegment.apply(0, bez1.concat(i / n1)); dots1.push({ x: d.x, y: d.y, t: i / n1 }); } for (var _i = 0; _i < n2 + 1; _i++) { var _d = findDotsAtSegment.apply(0, bez2.concat(_i / n2)); dots2.push({ x: _d.x, y: _d.y, t: _i / n2 }); } for (var _i2 = 0; _i2 < n1; _i2++) { for (var j = 0; j < n2; j++) { var di = dots1[_i2]; var di1 = dots1[_i2 + 1]; var dj = dots2[j]; var dj1 = dots2[j + 1]; var ci = Math.abs(di1.x - di.x) < 0.001 ? 'y' : 'x'; var cj = Math.abs(dj1.x - dj.x) < 0.001 ? 'y' : 'x'; var is = intersect(di.x, di.y, di1.x, di1.y, dj.x, dj.y, dj1.x, dj1.y); if (is) { if (xy[is.x.toFixed(4)] === is.y.toFixed(4)) { continue; } xy[is.x.toFixed(4)] = is.y.toFixed(4); var t1 = di.t + Math.abs((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t); var t2 = dj.t + Math.abs((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t); if (t1 >= 0 && t1 <= 1 && t2 >= 0 && t2 <= 1) { if (justCount) { res++; } else { res.push({ x: is.x, y: is.y, t1: t1, t2: t2 }); } } } } } return res; }; var interPathHelper = function interPathHelper(path1, path2, justCount) { path1 = pathTocurve(path1); path2 = pathTocurve(path2); var x1; var y1; var x2; var y2; var x1m; var y1m; var x2m; var y2m; var bez1; var bez2; var res = justCount ? 0 : []; for (var i = 0, ii = path1.length; i < ii; i++) { var pi = path1[i]; if (pi[0] === 'M') { x1 = x1m = pi[1]; y1 = y1m = pi[2]; } else { if (pi[0] === 'C') { bez1 = [x1, y1].concat(pi.slice(1)); x1 = bez1[6]; y1 = bez1[7]; } else { bez1 = [x1, y1, x1, y1, x1m, y1m, x1m, y1m]; x1 = x1m; y1 = y1m; } for (var j = 0, jj = path2.length; j < jj; j++) { var pj = path2[j]; if (pj[0] === 'M') { x2 = x2m = pj[1]; y2 = y2m = pj[2]; } else { if (pj[0] === 'C') { bez2 = [x2, y2].concat(pj.slice(1)); x2 = bez2[6]; y2 = bez2[7]; } else { bez2 = [x2, y2, x2, y2, x2m, y2m, x2m, y2m]; x2 = x2m; y2 = y2m; } var intr = interHelper(bez1, bez2, justCount); if (justCount) { res += intr; } else { for (var k = 0, kk = intr.length; k < kk; k++) { intr[k].segment1 = i; intr[k].segment2 = j; intr[k].bez1 = bez1; intr[k].bez2 = bez2; } res = res.concat(intr); } } } } } return res; }; var pathIntersection = function pathIntersection(path1, path2) { return interPathHelper(path1, path2); }; function decasteljau(points, t) { var left = []; var right = []; function recurse(points, t) { if (points.length === 1) { left.push(points[0]); right.push(points[0]); } else { var middlePoints = []; for (var i = 0; i < points.length - 1; i++) { if (i === 0) { left.push(points[0]); } if (i === points.length - 2) { right.push(points[i + 1]); } middlePoints[i] = [(1 - t) * points[i][0] + t * points[i + 1][0], (1 - t) * points[i][1] + t * points[i + 1][1]]; } recurse(middlePoints, t); } } if (points.length) { recurse(points, t); } return { left: left, right: right.reverse() }; } function splitCurve(start, end, count) { var points = [[start[1], start[2]]]; count = count || 2; var segments = []; if (end[0] === 'A') { points.push(end[6]); points.push(end[7]); } else if (end[0] === 'C') { points.push([end[1], end[2]]); points.push([end[3], end[4]]); points.push([end[5], end[6]]); } else if (end[0] === 'S' || end[0] === 'Q') { points.push([end[1], end[2]]); points.push([end[3], end[4]]); } else { points.push([end[1], end[2]]); } var leftSegments = points; var t = 1 / count; for (var i = 0; i < count - 1; i++) { var rt = t / (1 - t * i); var split = decasteljau(leftSegments, rt); segments.push(split.left); leftSegments = split.right; } segments.push(leftSegments); var result = segments.map(function (segment) { var cmd = []; if (segment.length === 4) { cmd.push('C'); cmd = cmd.concat(segment[2]); } if (segment.length >= 3) { if (segment.length === 3) { cmd.push('Q'); } cmd = cmd.concat(segment[1]); } if (segment.length === 2) { cmd.push('L'); } cmd = cmd.concat(segment[segment.length - 1]); return cmd; }); return result; } var splitSegment = function splitSegment(start, end, count) { if (count === 1) { return [[].concat(start)]; } var segments = []; if (end[0] === 'L' || end[0] === 'C' || end[0] === 'Q') { segments = segments.concat(splitCurve(start, end, count)); } else { var temp = [].concat(start); if (temp[0] === 'M') { temp[0] = 'L'; } for (var i = 0; i <= count - 1; i++) { segments.push(temp); } } return segments; }; var fillPath = function fillPath(source, target) { if (source.length === 1) { return source; } var sourceLen = source.length - 1; var targetLen = target.length - 1; var ratio = sourceLen / targetLen; var segmentsToFill = []; if (source.length === 1 && source[0][0] === 'M') { for (var i = 0; i < targetLen - sourceLen; i++) { source.push(source[0]); } return source; } for (var _i3 = 0; _i3 < targetLen; _i3++) { var index = Math.floor(ratio * _i3); segmentsToFill[index] = (segmentsToFill[index] || 0) + 1; } var filled = segmentsToFill.reduce(function (filled, count, i) { if (i === sourceLen) { return filled.concat(source[sourceLen]); } return filled.concat(splitSegment(source[i], source[i + 1], count)); }, []); filled.unshift(source[0]); if (target[targetLen] === 'Z' || target[targetLen] === 'z') { filled.push('Z'); } return filled; }; var isEqual = function isEqual(obj1, obj2) { if (obj1.length !== obj2.length) { return false; } var result = true; Util.each(obj1, function (item, i) { if (item !== obj2[i]) { result = false; return false; } }); return result; }; function getMinDiff(del, add, modify) { var type = null; var min = modify; if (add < min) { min = add; type = 'add'; } if (del < min) { min = del; type = 'del'; } return { type: type, min: min }; } /* * https://en.wikipedia.org/wiki/Levenshtein_distance * 计算两条path的编辑距离 */ var levenshteinDistance = function levenshteinDistance(source, target) { var sourceLen = source.length; var targetLen = target.length; var sourceSegment, targetSegment; var temp = 0; if (sourceLen === 0 || targetLen === 0) { return null; } var dist = []; for (var i = 0; i <= sourceLen; i++) { dist[i] = []; dist[i][0] = { min: i }; } for (var j = 0; j <= targetLen; j++) { dist[0][j] = { min: j }; } for (var _i4 = 1; _i4 <= sourceLen; _i4++) { sourceSegment = source[_i4 - 1]; for (var _j2 = 1; _j2 <= targetLen; _j2++) { targetSegment = target[_j2 - 1]; if (isEqual(sourceSegment, targetSegment)) { temp = 0; } else { temp = 1; } var del = dist[_i4 - 1][_j2].min + 1; var add = dist[_i4][_j2 - 1].min + 1; var modify = dist[_i4 - 1][_j2 - 1].min + temp; dist[_i4][_j2] = getMinDiff(del, add, modify); } } return dist; }; var fillPathByDiff = function fillPathByDiff(source, target) { var diffMatrix = levenshteinDistance(source, target); var sourceLen = source.length; var targetLen = target.length; var changes = []; var index = 1; var minPos = 1; // 如果source和target不是完全不相等 if (diffMatrix[sourceLen][targetLen] !== sourceLen) { // 获取从source到target所需改动 for (var i = 1; i <= sourceLen; i++) { var min = diffMatrix[i][i].min; minPos = i; for (var j = index; j <= targetLen; j++) { if (diffMatrix[i][j].min < min) { min = diffMatrix[i][j].min; minPos = j; } } index = minPos; if (diffMatrix[i][index].type) { changes.push({ index: i - 1, type: diffMatrix[i][index].type }); } } // 对source进行增删path for (var _i5 = changes.length - 1; _i5 >= 0; _i5--) { index = changes[_i5].index; if (changes[_i5].type === 'add') { source.splice(index, 0, [].concat(source[index])); } else { source.splice(index, 1); } } } // source尾部补齐 sourceLen = source.length; var diff = targetLen - sourceLen; if (sourceLen < targetLen) { for (var _i6 = 0; _i6 < diff; _i6++) { if (source[sourceLen - 1][0] === 'z' || source[sourceLen - 1][0] === 'Z') { source.splice(sourceLen - 2, 0, source[sourceLen - 2]); } else { source.push(source[sourceLen - 1]); } sourceLen += 1; } } return source; }; // 将两个点均分成count个点 function _splitPoints(points, former, count) { var result = [].concat(points); var index; var t = 1 / (count + 1); var formerEnd = _getSegmentPoints(former)[0]; for (var i = 1; i <= count; i++) { t *= i; index = Math.floor(points.length * t); if (index === 0) { result.unshift([formerEnd[0] * t + points[index][0] * (1 - t), formerEnd[1] * t + points[index][1] * (1 - t)]); } else { result.splice(index, 0, [formerEnd[0] * t + points[index][0] * (1 - t), formerEnd[1] * t + points[index][1] * (1 - t)]); } } return result; } /* * 抽取pathSegment中的关键点 * M,L,A,Q,H,V一个端点 * Q, S抽取一个端点,一个控制点 * C抽取一个端点,两个控制点 */ function _getSegmentPoints(segment) { var points = []; switch (segment[0]) { case 'M': points.push([segment[1], segment[2]]); break; case 'L': points.push([segment[1], segment[2]]); break; case 'A': points.push([segment[6], segment[7]]); break; case 'Q': points.push([segment[3], segment[4]]); points.push([segment[1], segment[2]]); break; case 'T': points.push([segment[1], segment[2]]); break; case 'C': points.push([segment[5], segment[6]]); points.push([segment[1], segment[2]]); points.push([segment[3], segment[4]]); break; case 'S': points.push([segment[3], segment[4]]); points.push([segment[1], segment[2]]); break; case 'H': points.push([segment[1], segment[1]]); break; case 'V': points.push([segment[1], segment[1]]); break; default: } return points; } var formatPath = function formatPath(fromPath, toPath) { if (fromPath.length <= 1) { return fromPath; } var points; for (var i = 0; i < toPath.length; i++) { if (fromPath[i][0] !== toPath[i][0]) { // 获取fromPath的pathSegment的端点,根据toPath的指令对其改造 points = _getSegmentPoints(fromPath[i]); switch (toPath[i][0]) { case 'M': fromPath[i] = ['M'].concat(points[0]); break; case 'L': fromPath[i] = ['L'].concat(points[0]); break; case 'A': fromPath[i] = [].concat(toPath[i]); fromPath[i][6] = points[0][0]; fromPath[i][7] = points[0][1]; break; case 'Q': if (points.length < 2) { if (i > 0) { points = _splitPoints(points, fromPath[i - 1], 1); } else { fromPath[i] = toPath[i]; break; } } fromPath[i] = ['Q'].concat(points.reduce(function (arr, i) { return arr.concat(i); }, [])); break; case 'T': fromPath[i] = ['T'].concat(points[0]); break; case 'C': if (points.length < 3) { if (i > 0) { points = _splitPoints(points, fromPath[i - 1], 2); } else { fromPath[i] = toPath[i]; break; } } fromPath[i] = ['C'].concat(points.reduce(function (arr, i) { return arr.concat(i); }, [])); break; case 'S': if (points.length < 2) { if (i > 0) { points = _splitPoints(points, fromPath[i - 1], 1); } else { fromPath[i] = toPath[i]; break; } } fromPath[i] = ['S'].concat(points.reduce(function (arr, i) { return arr.concat(i); }, [])); break; default: fromPath[i] = toPath[i]; } } } return fromPath; }; module.exports = { parsePathString: parsePathString, parsePathArray: parsePathArray, pathTocurve: pathTocurve, pathToAbsolute: pathToAbsolute, catmullRomToBezier: catmullRom2bezier, rectPath: rectPath, fillPath: fillPath, fillPathByDiff: fillPathByDiff, formatPath: formatPath, intersection: pathIntersection }; /***/ }), /* 97 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @fileOverview The base class of continuous legend * @author sima.zhang */ var Util = __webpack_require__(4); var Legend = __webpack_require__(192); var Slider = __webpack_require__(385); var _require = __webpack_require__(16), FONT_FAMILY = _require.FONT_FAMILY; var TRIGGER_WIDTH = 8; var Event = Util.Event; var Group = Util.Group; var Continuous = /*#__PURE__*/function (_Legend) { _inheritsLoose(Continuous, _Legend); function Continuous() { return _Legend.apply(this, arguments) || this; } var _proto = Continuous.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Legend.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * 类型 * @type {String} */ type: 'continuous-legend', /** * 子项 * @type {Array} */ items: null, /** * 布局方式 * horizontal 水平 * vertical 垂直 * @type {String} */ layout: 'vertical', /** * 宽度 * @type {Number} */ width: 20, /** * 高度 * @type {Number} */ height: 156, /** * 默认文本图形属性 * @type {ATTRS} */ textStyle: { fill: '#333', textAlign: 'center', textBaseline: 'middle', stroke: '#fff', lineWidth: 5, fontFamily: FONT_FAMILY }, hoverTextStyle: { fill: 'rgba(0,0,0,0.25)' }, /** * 连续图例是否可滑动 * @type {Boolean} */ slidable: true, /** * 两头滑块的样式 * @type {object} */ triggerAttr: { fill: '#fff', // shadowOffsetX: -2, // shadowOffsetY: 2, shadowBlur: 10, shadowColor: 'rgba(0,0,0,0.65)', radius: 2 }, /** * slider 的范围 * @type {array}} */ _range: [0, 100], /** * 中间 bar 背景灰色 * @type {ATTRS} */ middleBackgroundStyle: { fill: '#D9D9D9' }, /** * 文本与图例间距 * @type {Number} */ textOffset: 4, /** * line segment to seperate the unslidable slider blocks * @type {object} */ lineStyle: { lineWidth: 1, stroke: '#fff' }, /** * the pointer while activate the legend by mouse hovering or called by outside * @type {object} */ pointerStyle: { // color: '#ccc', fill: 'rgb(230, 230, 230)' } }); }; _proto._calStartPoint = function _calStartPoint() { var start = { x: 10, y: this.get('titleGap') - TRIGGER_WIDTH }; var titleShape = this.get('titleShape'); if (titleShape) { var titleBox = titleShape.getBBox(); start.y += titleBox.height; } return start; }; _proto.beforeRender = function beforeRender() { var items = this.get('items'); if (!Util.isArray(items) || Util.isEmpty(items)) { return; } _Legend.prototype.beforeRender.call(this); this.set('firstItem', items[0]); this.set('lastItem', items[items.length - 1]); }; _proto._formatItemValue = function _formatItemValue(value) { var formatter = this.get('formatter') || this.get('itemFormatter'); if (formatter) { value = formatter.call(this, value); } return value; }; _proto.render = function render() { _Legend.prototype.render.call(this); if (this.get('slidable')) { this._renderSlider(); } else { this._renderUnslidable(); } }; _proto._renderSlider = function _renderSlider() { var minHandleElement = new Group(); var maxHandleElement = new Group(); var backgroundElement = new Group(); var start = this._calStartPoint(); var group = this.get('group'); var slider = group.addGroup(Slider, { minHandleElement: minHandleElement, maxHandleElement: maxHandleElement, backgroundElement: backgroundElement, layout: this.get('layout'), range: this.get('_range'), width: this.get('width'), height: this.get('height') }); slider.translate(start.x, start.y); this.set('slider', slider); var shape = this._renderSliderShape(); shape.attr('clip', slider.get('middleHandleElement')); this._renderTrigger(); } // the middle bar ; _proto._addMiddleBar = function _addMiddleBar(parent, name, attrs) { // background of the middle bar parent.addShape(name, { attrs: Util.mix({}, attrs, this.get('middleBackgroundStyle')) }); // frontground of the middle bar return parent.addShape(name, { attrs: attrs }); }; _proto._renderTrigger = function _renderTrigger() { var min = this.get('firstItem'); var max = this.get('lastItem'); var layout = this.get('layout'); var textStyle = this.get('textStyle'); var triggerAttr = this.get('triggerAttr'); var minBlockAttr = Util.mix({}, triggerAttr); var maxBlockAttr = Util.mix({}, triggerAttr); var minTextAttr = Util.mix({ text: this._formatItemValue(min.value) + '' }, textStyle); var maxTextAttr = Util.mix({ text: this._formatItemValue(max.value) + '' }, textStyle); if (layout === 'vertical') { this._addVerticalTrigger('min', minBlockAttr, minTextAttr); this._addVerticalTrigger('max', maxBlockAttr, maxTextAttr); } else { this._addHorizontalTrigger('min', minBlockAttr, minTextAttr); this._addHorizontalTrigger('max', maxBlockAttr, maxTextAttr); } }; _proto._addVerticalTrigger = function _addVerticalTrigger(type, blockAttr, textAttr) { var slider = this.get('slider'); var trigger = slider.get(type + 'HandleElement'); var width = this.get('width'); var button = trigger.addShape('rect', { attrs: Util.mix({ x: width / 2 - TRIGGER_WIDTH - 2, y: type === 'min' ? 0 : -TRIGGER_WIDTH, width: 2 * TRIGGER_WIDTH + 2, height: TRIGGER_WIDTH }, blockAttr) }); var text = trigger.addShape('text', { attrs: Util.mix(textAttr, { x: width + this.get('textOffset'), y: type === 'max' ? -4 : 4, textAlign: 'start', lineHeight: 1, textBaseline: 'middle' }) }); var layout = this.get('layout'); var trigerCursor = layout === 'vertical' ? 'ns-resize' : 'ew-resize'; button.attr('cursor', trigerCursor); text.attr('cursor', trigerCursor); this.set(type + 'ButtonElement', button); this.set(type + 'TextElement', text); }; _proto._addHorizontalTrigger = function _addHorizontalTrigger(type, blockAttr, textAttr) { var slider = this.get('slider'); var trigger = slider.get(type + 'HandleElement'); var button = trigger.addShape('rect', { attrs: Util.mix({ x: type === 'min' ? -TRIGGER_WIDTH : 0, y: -TRIGGER_WIDTH - this.get('height') / 2, width: TRIGGER_WIDTH, height: 2 * TRIGGER_WIDTH }, blockAttr) }); var text = trigger.addShape('text', { attrs: Util.mix(textAttr, { x: type === 'min' ? -TRIGGER_WIDTH - 4 : TRIGGER_WIDTH + 4, y: TRIGGER_WIDTH / 2 + this.get('textOffset') + 10, textAlign: type === 'min' ? 'end' : 'start', textBaseline: 'middle' }) }); var layout = this.get('layout'); var trigerCursor = layout === 'vertical' ? 'ns-resize' : 'ew-resize'; button.attr('cursor', trigerCursor); text.attr('cursor', trigerCursor); this.set(type + 'ButtonElement', button); this.set(type + 'TextElement', text); }; _proto._bindEvents = function _bindEvents() { var _this = this; if (this.get('slidable')) { var slider = this.get('slider'); slider.on('sliderchange', function (ev) { var range = ev.range; var firstItemValue = _this.get('firstItem').value; var lastItemValue = _this.get('lastItem').value; var minValue = firstItemValue + range[0] / 100 * (lastItemValue - firstItemValue); var maxValue = firstItemValue + range[1] / 100 * (lastItemValue - firstItemValue); _this._updateElement(minValue, maxValue); var itemFiltered = new Event('itemfilter', ev, true, true); itemFiltered.range = [minValue, maxValue]; _this.emit('itemfilter', itemFiltered); }); } if (this.get('hoverable')) { this.get('group').on('mousemove', Util.wrapBehavior(this, '_onMouseMove')); this.get('group').on('mouseleave', Util.wrapBehavior(this, '_onMouseLeave')); } } // update the text of min and max trigger ; _proto._updateElement = function _updateElement(min, max) { var minTextElement = this.get('minTextElement'); var maxTextElement = this.get('maxTextElement'); if (max > 1) { // 对于大于 1 的值,默认显示为整数 min = parseInt(min, 10); max = parseInt(max, 10); } minTextElement.attr('text', this._formatItemValue(min) + ''); maxTextElement.attr('text', this._formatItemValue(max) + ''); }; _proto._onMouseLeave = function _onMouseLeave() { var hoverPointer = this.get('group').findById('hoverPointer'); hoverPointer && hoverPointer.destroy(); var hoverText = this.get('group').findById('hoverText'); hoverText && hoverText.destroy(); this.get('canvas').draw(); } // activate the legend while mouse moving ; _proto._onMouseMove = function _onMouseMove(ev) { var height = this.get('height'); var width = this.get('width'); var items = this.get('items'); var el = this.get('canvas').get('el'); var el_bbox = el.getBoundingClientRect(); var bbox = this.get('group').getBBox(); var value; if (this.get('layout') === 'vertical') { var valuePadding = 5; if (this.get('type') === 'color-legend') { valuePadding = 30; } var titleOffset = this.get('titleGap'); var titleShape = this.get('titleShape'); if (titleShape) titleOffset += titleShape.getBBox().maxY - titleShape.getBBox().minY; var currentPage = ev.clientY || ev.event.clientY; currentPage = currentPage - el_bbox.y - this.get('group').attr('matrix')[7] + bbox.y - valuePadding + titleOffset; value = items[0].value + (1 - currentPage / height) * (items[items.length - 1].value - items[0].value); } else { var _currentPage = ev.clientX || ev.event.clientX; _currentPage = _currentPage - el_bbox.x - this.get('group').attr('matrix')[6]; value = items[0].value + _currentPage / width * (items[items.length - 1].value - items[0].value); } value = value.toFixed(2); this.activate(value); this.emit('mousehover', { value: value }); } // activated by mouse moving or being called ; _proto.activate = function activate(value) { if (!value) { return; } var hoverPointer = this.get('group').findById('hoverPointer'); var hoverText = this.get('group').findById('hoverText'); var items = this.get('items'); if (value < items[0].value || value > items[items.length - 1].value) { return; } var height = this.get('height'); var width = this.get('width'); var titleShape = this.get('titleShape'); var titleGap = this.get('titleGap'); var points = []; var page = (value - items[0].value) / (items[items.length - 1].value - items[0].value); var textStyle; if (this.get('layout') === 'vertical') { // revise the offset var paddingY = 0, paddingX = 0; if (this.get('type') === 'color-legend') { paddingY = titleGap; if (titleShape) paddingY += titleShape.getBBox().height; } if (this.get('slidable')) { if (this.get('type') === 'color-legend') { paddingY -= 13; } else { paddingY = titleGap - 15; if (titleShape) paddingY += titleShape.getBBox().height; } paddingX += 10; } page = (1 - page) * height; points = [[paddingX, page + paddingY], [paddingX - 10, page + paddingY - 5], [paddingX - 10, page + paddingY + 5]]; textStyle = Util.mix({}, { x: width + this.get('textOffset') / 2 + paddingX, y: page + paddingY, text: this._formatItemValue(value) + '' // 以字符串格式展示 }, this.get('textStyle'), { textAlign: 'start' }); } else { var _paddingY = 0, _paddingX = 0; if (this.get('type') === 'color-legend') { _paddingY = titleGap; if (titleShape) _paddingY += titleShape.getBBox().height; } if (this.get('slidable')) { if (this.get('type') === 'color-legend') { // hoverPointer三角形的高 _paddingY -= 7; } else { _paddingY = titleGap; if (!titleShape) _paddingY -= 7; } _paddingX += 10; } page *= width; points = [[page + _paddingX, _paddingY], [page + _paddingX - 5, _paddingY - 10], [page + _paddingX + 5, _paddingY - 10]]; textStyle = Util.mix({}, { x: page - 5, y: height + this.get('textOffset') + _paddingY, text: this._formatItemValue(value) + '' // 以字符串格式展示 }, this.get('textStyle')); } var hoverTextStyle = Util.mix(textStyle, this.get('hoverTextStyle')); if (!hoverText) { // mouse enter the legend, add hoverText hoverText = this.get('group').addShape('text', { attrs: hoverTextStyle }); hoverText.set('id', 'hoverText'); } else { // mouse move, update hoverText hoverText.attr(hoverTextStyle); } if (!hoverPointer) { // mouse enter the legend, add hoverPointer hoverPointer = this.get('group').addShape('Polygon', { attrs: Util.mix({ points: points }, this.get('pointerStyle')) }); hoverPointer.set('id', 'hoverPointer'); } else { // mouse move, update hoverPointer hoverPointer.attr(Util.mix({ points: points }, this.get('pointerStyle'))); } this.get('canvas').draw(); }; _proto.deactivate = function deactivate() { var hoverPointer = this.get('group').findById('hoverPointer'); hoverPointer && hoverPointer.destroy(); var hoverText = this.get('group').findById('hoverText'); hoverText && hoverText.destroy(); this.get('canvas').draw(); }; return Continuous; }(Legend); module.exports = Continuous; /***/ }), /* 98 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Component = __webpack_require__(92); var Util = __webpack_require__(4); var Tooltip = /*#__PURE__*/function (_Component) { _inheritsLoose(Tooltip, _Component); function Tooltip() { return _Component.apply(this, arguments) || this; } var _proto = Tooltip.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Component.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * tooltip container * @type {Dom / String} */ /** * 右下角坐标 * @type {Number} */ x: 0, /** * y 右下角坐标 * @type {Number} */ y: 0, /** * tooltip 记录项 * @type {Array} */ items: null, /** * tooltip 标题 * @type {Array} */ titleContent: null, /** * 是否展示 title * @type {Boolean} */ showTitle: true, /** * 视图范围 * @type {Object} */ plotRange: null, /** * x轴上,移动到位置的偏移量 * @type {Number} */ offset: 10, // TODO:支持xy两个方向上的offset /** * 时间戳 * @type {Number} */ timeStamp: 0, /** * 将 tooltip 展示在指定区域内 * @type {Boolean} */ inPlot: true, /** * tooltip 辅助线配置 * @type {Object} */ crosshairs: null }); }; _proto.isContentChange = function isContentChange(title, items) { var titleContent = this.get('titleContent'); var lastItems = this.get('items'); var isChanged = !(title === titleContent && lastItems.length === items.length); if (!isChanged) { Util.each(items, function (item, index) { var preItem = lastItems[index]; for (var key in item) { if (item.hasOwnProperty(key)) { if (!Util.isObject(item[key]) && item[key] !== preItem[key]) { isChanged = true; break; } } } if (isChanged) { return false; } }); } return isChanged; }; _proto.setContent = function setContent(title, items) { var timeStamp = new Date().valueOf(); this.set('items', items); this.set('titleContent', title); this.set('timeStamp', timeStamp); this.render(); return this; }; _proto.setPosition = function setPosition(x, y) { this.set('x', x); this.set('y', y); }; _proto.render = function render() {}; _proto.clear = function clear() {}; _proto.show = function show() { this.set('visible', true); }; _proto.hide = function hide() { this.set('visible', false); }; return Tooltip; }(Component); module.exports = Tooltip; /***/ }), /* 99 */, /* 100 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview 提取公共代码到util方法 * @author dxq613@gmail.com */ var isString = __webpack_require__(12); var isDate = __webpack_require__(111); module.exports = { toTimeStamp: function toTimeStamp(value) { if (isString(value)) { if (value.indexOf('T') > 0) { value = new Date(value).getTime(); } else { value = new Date(value.replace(/-/ig, '/')).getTime(); } } if (isDate(value)) { value = value.getTime(); } return value; } }; /***/ }), /* 101 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__timer_js__ = __webpack_require__(83); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "now", function() { return __WEBPACK_IMPORTED_MODULE_0__timer_js__["b"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "timer", function() { return __WEBPACK_IMPORTED_MODULE_0__timer_js__["c"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "timerFlush", function() { return __WEBPACK_IMPORTED_MODULE_0__timer_js__["d"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__timeout_js__ = __webpack_require__(229); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "timeout", function() { return __WEBPACK_IMPORTED_MODULE_1__timeout_js__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__interval_js__ = __webpack_require__(230); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interval", function() { return __WEBPACK_IMPORTED_MODULE_2__interval_js__["a"]; }); /***/ }), /* 102 */, /* 103 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__linear_js__ = __webpack_require__(231); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeLinear", function() { return __WEBPACK_IMPORTED_MODULE_0__linear_js__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__quad_js__ = __webpack_require__(232); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeQuad", function() { return __WEBPACK_IMPORTED_MODULE_1__quad_js__["b"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeQuadIn", function() { return __WEBPACK_IMPORTED_MODULE_1__quad_js__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeQuadOut", function() { return __WEBPACK_IMPORTED_MODULE_1__quad_js__["c"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeQuadInOut", function() { return __WEBPACK_IMPORTED_MODULE_1__quad_js__["b"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__cubic_js__ = __webpack_require__(233); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeCubic", function() { return __WEBPACK_IMPORTED_MODULE_2__cubic_js__["b"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeCubicIn", function() { return __WEBPACK_IMPORTED_MODULE_2__cubic_js__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeCubicOut", function() { return __WEBPACK_IMPORTED_MODULE_2__cubic_js__["c"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeCubicInOut", function() { return __WEBPACK_IMPORTED_MODULE_2__cubic_js__["b"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__poly_js__ = __webpack_require__(234); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easePoly", function() { return __WEBPACK_IMPORTED_MODULE_3__poly_js__["b"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easePolyIn", function() { return __WEBPACK_IMPORTED_MODULE_3__poly_js__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easePolyOut", function() { return __WEBPACK_IMPORTED_MODULE_3__poly_js__["c"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easePolyInOut", function() { return __WEBPACK_IMPORTED_MODULE_3__poly_js__["b"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__sin_js__ = __webpack_require__(235); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeSin", function() { return __WEBPACK_IMPORTED_MODULE_4__sin_js__["b"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeSinIn", function() { return __WEBPACK_IMPORTED_MODULE_4__sin_js__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeSinOut", function() { return __WEBPACK_IMPORTED_MODULE_4__sin_js__["c"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeSinInOut", function() { return __WEBPACK_IMPORTED_MODULE_4__sin_js__["b"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__exp_js__ = __webpack_require__(236); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeExp", function() { return __WEBPACK_IMPORTED_MODULE_5__exp_js__["b"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeExpIn", function() { return __WEBPACK_IMPORTED_MODULE_5__exp_js__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeExpOut", function() { return __WEBPACK_IMPORTED_MODULE_5__exp_js__["c"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeExpInOut", function() { return __WEBPACK_IMPORTED_MODULE_5__exp_js__["b"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__circle_js__ = __webpack_require__(237); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeCircle", function() { return __WEBPACK_IMPORTED_MODULE_6__circle_js__["b"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeCircleIn", function() { return __WEBPACK_IMPORTED_MODULE_6__circle_js__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeCircleOut", function() { return __WEBPACK_IMPORTED_MODULE_6__circle_js__["c"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeCircleInOut", function() { return __WEBPACK_IMPORTED_MODULE_6__circle_js__["b"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__bounce_js__ = __webpack_require__(238); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeBounce", function() { return __WEBPACK_IMPORTED_MODULE_7__bounce_js__["c"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeBounceIn", function() { return __WEBPACK_IMPORTED_MODULE_7__bounce_js__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeBounceOut", function() { return __WEBPACK_IMPORTED_MODULE_7__bounce_js__["c"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeBounceInOut", function() { return __WEBPACK_IMPORTED_MODULE_7__bounce_js__["b"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__back_js__ = __webpack_require__(239); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeBack", function() { return __WEBPACK_IMPORTED_MODULE_8__back_js__["b"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeBackIn", function() { return __WEBPACK_IMPORTED_MODULE_8__back_js__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeBackOut", function() { return __WEBPACK_IMPORTED_MODULE_8__back_js__["c"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeBackInOut", function() { return __WEBPACK_IMPORTED_MODULE_8__back_js__["b"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__elastic_js__ = __webpack_require__(240); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeElastic", function() { return __WEBPACK_IMPORTED_MODULE_9__elastic_js__["c"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeElasticIn", function() { return __WEBPACK_IMPORTED_MODULE_9__elastic_js__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeElasticOut", function() { return __WEBPACK_IMPORTED_MODULE_9__elastic_js__["c"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "easeElasticInOut", function() { return __WEBPACK_IMPORTED_MODULE_9__elastic_js__["b"]; }); /***/ }), /* 104 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { Position: __webpack_require__(330), Color: __webpack_require__(331), Shape: __webpack_require__(332), Size: __webpack_require__(333), Opacity: __webpack_require__(334), ColorUtil: __webpack_require__(165) }; /***/ }), /* 105 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview Scale entry, used to reference all the scales * @author dxq613@gmail.com */ var lowerFirst = __webpack_require__(106); var Base = __webpack_require__(20); Base.Linear = __webpack_require__(38); Base.Identity = __webpack_require__(209); Base.Cat = __webpack_require__(108); Base.Time = __webpack_require__(210); Base.TimeCat = __webpack_require__(212); Base.Log = __webpack_require__(213); Base.Pow = __webpack_require__(214); var _loop = function _loop(k) { if (Base.hasOwnProperty(k)) { var methodName = lowerFirst(k); Base[methodName] = function (cfg) { return new Base[k](cfg); }; } }; for (var k in Base) { _loop(k); } var CAT_ARR = ['cat', 'timeCat']; Base.isCategory = function (type) { return CAT_ARR.indexOf(type) >= 0; }; module.exports = Base; /***/ }), /* 106 */ /***/ (function(module, exports, __webpack_require__) { var toString = __webpack_require__(26); var lowerFirst = function lowerFirst(value) { var str = toString(value); return str.charAt(0).toLowerCase() + str.substring(1); }; module.exports = lowerFirst; /***/ }), /* 107 */ /***/ (function(module, exports) { /** * @fileOverview 计算方法 * @author dxq613@gmail.com */ // 如果小数点后面超过 10 位浮点数时进行一下处理 var DECIMAL_LENGTH = 12; // 获取系数 function getFactor(v) { var factor = 1; if (v === Infinity || v === -Infinity) { throw new Error('Not support Infinity!'); } if (v < 1) { var count = 0; while (v < 1) { factor = factor / 10; v = v * 10; count++; } // 浮点数计算出现问题 if (factor.toString().length > DECIMAL_LENGTH) { factor = parseFloat(factor.toFixed(count)); } } else { while (v > 10) { factor = factor * 10; v = v / 10; } } return factor; } // 取小于当前值的 function arrayFloor(values, value) { var length = values.length; if (length === 0) { return NaN; } var pre = values[0]; if (value < values[0]) { return NaN; } if (value >= values[length - 1]) { return values[length - 1]; } for (var i = 1; i < values.length; i++) { if (value < values[i]) { break; } pre = values[i]; } return pre; } // 大于当前值的第一个 function arrayCeiling(values, value) { var length = values.length; if (length === 0) { return NaN; } // var pre = values[0]; var rst; if (value > values[length - 1]) { return NaN; } if (value < values[0]) { return values[0]; } for (var i = 1; i < values.length; i++) { if (value <= values[i]) { rst = values[i]; break; } } return rst; } var Util = { // 获取逼近的数值 snapFactorTo: function snapFactorTo(v, arr, snapType) { // 假设 v = -512,isFloor = true if (isNaN(v)) { return NaN; } var factor = 1; // 计算系数 if (v !== 0) { if (v < 0) { factor = -1; } v = v * factor; // v = 512 var tmpFactor = getFactor(v); factor = factor * tmpFactor; // factor = -100 v = v / tmpFactor; // v = 5.12 } if (snapType === 'floor') { v = Util.snapFloor(arr, v); // v = 5 } else if (snapType === 'ceil') { v = Util.snapCeiling(arr, v); // v = 6 } else { v = Util.snapTo(arr, v); // 四舍五入 5 } var rst = parseFloat((v * factor).toPrecision(DECIMAL_LENGTH)); // 如果出现浮点数计算问题,需要处理一下 // 如果出现浮点数计算问题,需要处理一下 if (Math.abs(factor) < 1 && rst.toString().length > DECIMAL_LENGTH) { var decimalVal = parseInt(1 / factor); var symbol = factor > 0 ? 1 : -1; rst = v / decimalVal * symbol; } return rst; }, // 获取逼近的倍数 snapMultiple: function snapMultiple(v, base, snapType) { var div; if (snapType === 'ceil') { div = Math.ceil(v / base); } else if (snapType === 'floor') { div = Math.floor(v / base); } else { div = Math.round(v / base); } return div * base; }, /** * 获取逼近的值,用于对齐数据 * @param {Array} values 数据集合 * @param {Number} value 数值 * @return {Number} 逼近的值 */ snapTo: function snapTo(values, value) { // 这里假定values是升序排列 var floorVal = arrayFloor(values, value); var ceilingVal = arrayCeiling(values, value); if (isNaN(floorVal) || isNaN(ceilingVal)) { if (values[0] >= value) { return values[0]; } var last = values[values.length - 1]; if (last <= value) { return last; } } if (Math.abs(value - floorVal) < Math.abs(ceilingVal - value)) { return floorVal; } return ceilingVal; }, /** * 获取逼近的最小值,用于对齐数据 * @param {Array} values 数据集合 * @param {Number} value 数值 * @return {Number} 逼近的最小值 */ snapFloor: function snapFloor(values, value) { // 这里假定values是升序排列 return arrayFloor(values, value); }, /** * 获取逼近的最大值,用于对齐数据 * @param {Array} values 数据集合 * @param {Number} value 数值 * @return {Number} 逼近的最大值 */ snapCeiling: function snapCeiling(values, value) { // 这里假定values是升序排列 return arrayCeiling(values, value); }, fixedBase: function fixedBase(v, base) { var str = base.toString(); var index = str.indexOf('.'); var indexOfExp = str.indexOf('e-'); // 判断是否带小数点,1.000001 1.23e-9 if (index < 0 && indexOfExp < 0) { // base为整数 return Math.round(v); } var length = indexOfExp >= 0 ? parseInt(str.substr(indexOfExp + 2), 10) : str.substr(index + 1).length; if (length > 20) { length = 20; } return parseFloat(v.toFixed(length)); } }; module.exports = Util; /***/ }), /* 108 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var Base = __webpack_require__(20); var catAuto = __webpack_require__(109); var each = __webpack_require__(3); var isNumber = __webpack_require__(11); var isString = __webpack_require__(12); var Category = /*#__PURE__*/function (_Base) { _inheritsLoose(Category, _Base); function Category() { return _Base.apply(this, arguments) || this; } var _proto = Category.prototype; _proto._initDefaultCfg = function _initDefaultCfg() { _Base.prototype._initDefaultCfg.call(this); this.type = 'cat'; /** * 是否分类度量 * @type {Boolean} */ this.isCategory = true; this.isRounding = true; // 是否进行取整操作 } /** * @override */ ; _proto.init = function init() { var self = this; var values = self.values; var tickCount = self.tickCount; each(values, function (v, i) { values[i] = v.toString(); }); if (!self.ticks) { var ticks = values; if (tickCount) { var temp = catAuto({ maxCount: tickCount, data: values, isRounding: self.isRounding }); ticks = temp.ticks; } this.ticks = ticks; } } /** * @override */ ; _proto.getText = function getText(value) { if (this.values.indexOf(value) === -1 && isNumber(value)) { value = this.values[Math.round(value)]; } return _Base.prototype.getText.call(this, value); } /** * @override */ ; _proto.translate = function translate(value) { var index = this.values.indexOf(value); if (index === -1 && isNumber(value)) { index = value; } else if (index === -1) { index = NaN; } return index; } /** * @override */ ; _proto.scale = function scale(value) { var rangeMin = this.rangeMin(); var rangeMax = this.rangeMax(); var percent; if (isString(value) || this.values.indexOf(value) !== -1) { value = this.translate(value); } if (this.values.length > 1) { percent = value / (this.values.length - 1); } else { percent = value; } return rangeMin + percent * (rangeMax - rangeMin); } /** * @override */ ; _proto.invert = function invert(value) { if (isString(value)) { // 如果已经是字符串 return value; } var min = this.rangeMin(); var max = this.rangeMax(); // 归一到 范围内 if (value < min) { value = min; } if (value > max) { value = max; } var percent = (value - min) / (max - min); var index = Math.round(percent * (this.values.length - 1)) % this.values.length; index = index || 0; return this.values[index]; }; return Category; }(Base); Base.Cat = Category; module.exports = Category; /***/ }), /* 109 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview 计算分类的的坐标点 * @author dxq613@gmail.com */ var each = __webpack_require__(3); var MAX_COUNT = 8; var SUB_COUNT = 4; // 控制个数不能过小 function getSimpleArray(data) { var arr = []; each(data, function (sub) { arr = arr.concat(sub); }); return arr; } function getGreatestFactor(count, number) { var i; for (i = number; i > 0; i--) { if (count % i === 0) { break; } } // 如果是素数,没有可以整除的数字 if (i === 1) { for (i = number; i > 0; i--) { if ((count - 1) % i === 0) { break; } } } return i; } module.exports = function (info) { var rst = {}; var ticks = []; var isRounding = info.isRounding; var categories = getSimpleArray(info.data); var length = categories.length; var maxCount = info.maxCount || MAX_COUNT; var tickCount; if (isRounding) { // 取整操作 tickCount = getGreatestFactor(length - 1, maxCount - 1) + 1; // 如果计算出来只有两个坐标点,则直接使用传入的 maxCount if (tickCount === 2) { tickCount = maxCount; } else if (tickCount < maxCount - SUB_COUNT) { tickCount = maxCount - SUB_COUNT; } } else { tickCount = maxCount; } if (!isRounding && length <= tickCount + tickCount / 2) { ticks = [].concat(categories); } else { var step = parseInt(length / (tickCount - 1), 10); var groups = categories.map(function (e, i) { return i % step === 0 ? categories.slice(i, i + step) : null; }).filter(function (e) { return e; }); for (var i = 1, groupLen = groups.length; i < groupLen && (isRounding ? i * step < length - step : i < tickCount - 1); i++) { ticks.push(groups[i][0]); } if (categories.length) { ticks.unshift(categories[0]); var last = categories[length - 1]; if (ticks.indexOf(last) === -1) { ticks.push(last); } } } rst.categories = categories; rst.ticks = ticks; return rst; }; /***/ }), /* 110 */ /***/ (function(module, exports, __webpack_require__) { var __WEBPACK_AMD_DEFINE_RESULT__;(function (main) { 'use strict'; /** * Parse or format dates * @class fecha */ var fecha = {}; var token = /d{1,4}|M{1,4}|YY(?:YY)?|S{1,3}|Do|ZZ|([HhMsDm])\1?|[aA]|"[^"]*"|'[^']*'/g; var twoDigits = /\d\d?/; var threeDigits = /\d{3}/; var fourDigits = /\d{4}/; var word = /[0-9]*['a-z\u00A0-\u05FF\u0700-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]+|[\u0600-\u06FF\/]+(\s*?[\u0600-\u06FF]+){1,2}/i; var literal = /\[([^]*?)\]/gm; var noop = function () {}; function shorten(arr, sLen) { var newArr = []; for (var i = 0, len = arr.length; i < len; i++) { newArr.push(arr[i].substr(0, sLen)); } return newArr; } function monthUpdate(arrName) { return function (d, v, i18n) { var index = i18n[arrName].indexOf(v.charAt(0).toUpperCase() + v.substr(1).toLowerCase()); if (~index) { d.month = index; } }; } function pad(val, len) { val = String(val); len = len || 2; while (val.length < len) { val = '0' + val; } return val; } var dayNames = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']; var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var monthNamesShort = shorten(monthNames, 3); var dayNamesShort = shorten(dayNames, 3); fecha.i18n = { dayNamesShort: dayNamesShort, dayNames: dayNames, monthNamesShort: monthNamesShort, monthNames: monthNames, amPm: ['am', 'pm'], DoFn: function DoFn(D) { return D + ['th', 'st', 'nd', 'rd'][D % 10 > 3 ? 0 : (D - D % 10 !== 10) * D % 10]; } }; var formatFlags = { D: function (dateObj) { return dateObj.getDate(); }, DD: function (dateObj) { return pad(dateObj.getDate()); }, Do: function (dateObj, i18n) { return i18n.DoFn(dateObj.getDate()); }, d: function (dateObj) { return dateObj.getDay(); }, dd: function (dateObj) { return pad(dateObj.getDay()); }, ddd: function (dateObj, i18n) { return i18n.dayNamesShort[dateObj.getDay()]; }, dddd: function (dateObj, i18n) { return i18n.dayNames[dateObj.getDay()]; }, M: function (dateObj) { return dateObj.getMonth() + 1; }, MM: function (dateObj) { return pad(dateObj.getMonth() + 1); }, MMM: function (dateObj, i18n) { return i18n.monthNamesShort[dateObj.getMonth()]; }, MMMM: function (dateObj, i18n) { return i18n.monthNames[dateObj.getMonth()]; }, YY: function (dateObj) { return String(dateObj.getFullYear()).substr(2); }, YYYY: function (dateObj) { return pad(dateObj.getFullYear(), 4); }, h: function (dateObj) { return dateObj.getHours() % 12 || 12; }, hh: function (dateObj) { return pad(dateObj.getHours() % 12 || 12); }, H: function (dateObj) { return dateObj.getHours(); }, HH: function (dateObj) { return pad(dateObj.getHours()); }, m: function (dateObj) { return dateObj.getMinutes(); }, mm: function (dateObj) { return pad(dateObj.getMinutes()); }, s: function (dateObj) { return dateObj.getSeconds(); }, ss: function (dateObj) { return pad(dateObj.getSeconds()); }, S: function (dateObj) { return Math.round(dateObj.getMilliseconds() / 100); }, SS: function (dateObj) { return pad(Math.round(dateObj.getMilliseconds() / 10), 2); }, SSS: function (dateObj) { return pad(dateObj.getMilliseconds(), 3); }, a: function (dateObj, i18n) { return dateObj.getHours() < 12 ? i18n.amPm[0] : i18n.amPm[1]; }, A: function (dateObj, i18n) { return dateObj.getHours() < 12 ? i18n.amPm[0].toUpperCase() : i18n.amPm[1].toUpperCase(); }, ZZ: function (dateObj) { var o = dateObj.getTimezoneOffset(); return (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4); } }; var parseFlags = { D: [twoDigits, function (d, v) { d.day = v; }], Do: [new RegExp(twoDigits.source + word.source), function (d, v) { d.day = parseInt(v, 10); }], M: [twoDigits, function (d, v) { d.month = v - 1; }], YY: [twoDigits, function (d, v) { var da = new Date(), cent = +('' + da.getFullYear()).substr(0, 2); d.year = '' + (v > 68 ? cent - 1 : cent) + v; }], h: [twoDigits, function (d, v) { d.hour = v; }], m: [twoDigits, function (d, v) { d.minute = v; }], s: [twoDigits, function (d, v) { d.second = v; }], YYYY: [fourDigits, function (d, v) { d.year = v; }], S: [/\d/, function (d, v) { d.millisecond = v * 100; }], SS: [/\d{2}/, function (d, v) { d.millisecond = v * 10; }], SSS: [threeDigits, function (d, v) { d.millisecond = v; }], d: [twoDigits, noop], ddd: [word, noop], MMM: [word, monthUpdate('monthNamesShort')], MMMM: [word, monthUpdate('monthNames')], a: [word, function (d, v, i18n) { var val = v.toLowerCase(); if (val === i18n.amPm[0]) { d.isPm = false; } else if (val === i18n.amPm[1]) { d.isPm = true; } }], ZZ: [/([\+\-]\d\d:?\d\d|Z)/, function (d, v) { if (v === 'Z') v = '+00:00'; var parts = (v + '').match(/([\+\-]|\d\d)/gi), minutes; if (parts) { minutes = +(parts[1] * 60) + parseInt(parts[2], 10); d.timezoneOffset = parts[0] === '+' ? minutes : -minutes; } }] }; parseFlags.dd = parseFlags.d; parseFlags.dddd = parseFlags.ddd; parseFlags.DD = parseFlags.D; parseFlags.mm = parseFlags.m; parseFlags.hh = parseFlags.H = parseFlags.HH = parseFlags.h; parseFlags.MM = parseFlags.M; parseFlags.ss = parseFlags.s; parseFlags.A = parseFlags.a; // Some common format strings fecha.masks = { default: 'ddd MMM DD YYYY HH:mm:ss', shortDate: 'M/D/YY', mediumDate: 'MMM D, YYYY', longDate: 'MMMM D, YYYY', fullDate: 'dddd, MMMM D, YYYY', shortTime: 'HH:mm', mediumTime: 'HH:mm:ss', longTime: 'HH:mm:ss.SSS' }; /*** * Format a date * @method format * @param {Date|number} dateObj * @param {string} mask Format of the date, i.e. 'mm-dd-yy' or 'shortDate' */ fecha.format = function (dateObj, mask, i18nSettings) { var i18n = i18nSettings || fecha.i18n; if (typeof dateObj === 'number') { dateObj = new Date(dateObj); } if (Object.prototype.toString.call(dateObj) !== '[object Date]' || isNaN(dateObj.getTime())) { throw new Error('Invalid Date in fecha.format'); } mask = fecha.masks[mask] || mask || fecha.masks['default']; var literals = []; // Make literals inactive by replacing them with ?? mask = mask.replace(literal, function ($0, $1) { literals.push($1); return '??'; }); // Apply formatting rules mask = mask.replace(token, function ($0) { return $0 in formatFlags ? formatFlags[$0](dateObj, i18n) : $0.slice(1, $0.length - 1); }); // Inline literal values back into the formatted value return mask.replace(/\?\?/g, function () { return literals.shift(); }); }; /** * Parse a date string into an object, changes - into / * @method parse * @param {string} dateStr Date string * @param {string} format Date parse format * @returns {Date|boolean} */ fecha.parse = function (dateStr, format, i18nSettings) { var i18n = i18nSettings || fecha.i18n; if (typeof format !== 'string') { throw new Error('Invalid format in fecha.parse'); } format = fecha.masks[format] || format; // Avoid regular expression denial of service, fail early for really long strings // https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS if (dateStr.length > 1000) { return false; } var isValid = true; var dateInfo = {}; format.replace(token, function ($0) { if (parseFlags[$0]) { var info = parseFlags[$0]; var index = dateStr.search(info[0]); if (!~index) { isValid = false; } else { dateStr.replace(info[0], function (result) { info[1](dateInfo, result, i18n); dateStr = dateStr.substr(index + result.length); return result; }); } } return parseFlags[$0] ? '' : $0.slice(1, $0.length - 1); }); if (!isValid) { return false; } var today = new Date(); if (dateInfo.isPm === true && dateInfo.hour != null && +dateInfo.hour !== 12) { dateInfo.hour = +dateInfo.hour + 12; } else if (dateInfo.isPm === false && +dateInfo.hour === 12) { dateInfo.hour = 0; } var date; if (dateInfo.timezoneOffset != null) { dateInfo.minute = +(dateInfo.minute || 0) - +dateInfo.timezoneOffset; date = new Date(Date.UTC(dateInfo.year || today.getFullYear(), dateInfo.month || 0, dateInfo.day || 1, dateInfo.hour || 0, dateInfo.minute || 0, dateInfo.second || 0, dateInfo.millisecond || 0)); } else { date = new Date(dateInfo.year || today.getFullYear(), dateInfo.month || 0, dateInfo.day || 1, dateInfo.hour || 0, dateInfo.minute || 0, dateInfo.second || 0, dateInfo.millisecond || 0); } return date; }; /* istanbul ignore next */ if (typeof module !== 'undefined' && module.exports) { module.exports = fecha; } else if (true) { !(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return fecha; }).call(exports, __webpack_require__, exports, module), __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__)); } else { main.fecha = fecha; } })(this); /***/ }), /* 111 */ /***/ (function(module, exports, __webpack_require__) { var isType = __webpack_require__(14); var isDate = function isDate(value) { return isType(value, 'Date'); }; module.exports = isDate; /***/ }), /* 112 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { Canvas: __webpack_require__(215), Group: __webpack_require__(115), Shape: __webpack_require__(7), Arc: __webpack_require__(120), Circle: __webpack_require__(121), Dom: __webpack_require__(122), Ellipse: __webpack_require__(123), Fan: __webpack_require__(124), Image: __webpack_require__(125), Line: __webpack_require__(126), Marker: __webpack_require__(81), Path: __webpack_require__(127), Polygon: __webpack_require__(128), Polyline: __webpack_require__(129), Rect: __webpack_require__(130), Text: __webpack_require__(131), PathSegment: __webpack_require__(46), PathUtil: __webpack_require__(82), Event: __webpack_require__(78), EventEmitter: __webpack_require__(117), // version, etc. version: '3.4.10' }; /***/ }), /* 113 */ /***/ (function(module, exports) { var toString = {}.toString; var getType = function getType(value) { return toString.call(value).replace(/^\[object /, '').replace(/\]$/, ''); }; module.exports = getType; /***/ }), /* 114 */ /***/ (function(module, exports) { var objectProto = Object.prototype; var isPrototype = function isPrototype(value) { var Ctor = value && value.constructor; var proto = typeof Ctor === 'function' && Ctor.prototype || objectProto; return value === proto; }; module.exports = isPrototype; /***/ }), /* 115 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Element = __webpack_require__(116); var Shape = __webpack_require__(226); var SHAPE_MAP = {}; // 缓存图形类型 var INDEX = '_INDEX'; var CLONE_CFGS = ['zIndex', 'capture', 'visible']; function getComparer(compare) { return function (left, right) { var result = compare(left, right); return result === 0 ? left[INDEX] - right[INDEX] : result; }; } function find(children, x, y) { var rst; for (var i = children.length - 1; i >= 0; i--) { var child = children[i]; if (child._cfg.visible && child._cfg.capture) { if (child.isGroup) { rst = child.getShape(x, y); } else if (child.isHit(x, y)) { rst = child; } } if (rst) { break; } } return rst; } function _cloneArrayAttr(arr) { var result = []; for (var i = 0; i < arr.length; i++) { result.push(arr[i]); } return result; } var Group = function Group(cfg) { Group.superclass.constructor.call(this, cfg); this.set('children', []); this.set('tobeRemoved', []); this._beforeRenderUI(); this._renderUI(); this._bindUI(); }; function initClassCfgs(c) { if (c._cfg || c === Group) { return; } var superCon = c.superclass.constructor; if (superCon && !superCon._cfg) { initClassCfgs(superCon); } c._cfg = {}; Util.merge(c._cfg, superCon._cfg); Util.merge(c._cfg, c.CFG); } Util.extend(Group, Element); Util.augment(Group, { isGroup: true, type: 'group', canFill: true, canStroke: true, getDefaultCfg: function getDefaultCfg() { initClassCfgs(this.constructor); return Util.merge({}, this.constructor._cfg); }, _beforeRenderUI: function _beforeRenderUI() {}, _renderUI: function _renderUI() {}, _bindUI: function _bindUI() {}, addShape: function addShape(type, cfg) { var canvas = this.get('canvas'); cfg = cfg || {}; var shapeType = SHAPE_MAP[type]; if (!shapeType) { shapeType = Util.upperFirst(type); SHAPE_MAP[type] = shapeType; } if (cfg.attrs && canvas) { var attrs = cfg.attrs; if (type === 'text') { // 临时解决 var topFontFamily = canvas.get('fontFamily'); if (topFontFamily) { attrs.fontFamily = attrs.fontFamily ? attrs.fontFamily : topFontFamily; } } } cfg.canvas = canvas; cfg.type = type; var rst = new Shape[shapeType](cfg); this.add(rst); return rst; }, /** 添加图组 * @param {Function|Object|undefined} param 图组类 * @param {Object} cfg 配置项 * @return {Object} rst 图组 */ addGroup: function addGroup(param, cfg) { var canvas = this.get('canvas'); var rst; cfg = Util.merge({}, cfg); if (Util.isFunction(param)) { if (cfg) { cfg.canvas = canvas; cfg.parent = this; rst = new param(cfg); } else { rst = new param({ canvas: canvas, parent: this }); } this.add(rst); } else if (Util.isObject(param)) { param.canvas = canvas; rst = new Group(param); this.add(rst); } else if (param === undefined) { rst = new Group(); this.add(rst); } else { return false; } return rst; }, /** 绘制背景 * @param {Array} padding 内边距 * @param {Attrs} attrs 图形属性 * @param {Shape} backShape 背景图形 * @return {Object} 背景层对象 */ renderBack: function renderBack(padding, attrs) { var backShape = this.get('backShape'); var innerBox = this.getBBox(); // const parent = this.get('parent'); // getParent Util.merge(attrs, { x: innerBox.minX - padding[3], y: innerBox.minY - padding[0], width: innerBox.width + padding[1] + padding[3], height: innerBox.height + padding[0] + padding[2] }); if (backShape) { backShape.attr(attrs); } else { backShape = this.addShape('rect', { zIndex: -1, attrs: attrs }); } this.set('backShape', backShape); this.sort(); return backShape; }, removeChild: function removeChild(item, destroy) { if (arguments.length >= 2) { if (this.contain(item)) { item.remove(destroy); } } else { if (arguments.length === 1) { if (Util.isBoolean(item)) { destroy = item; } else { if (this.contain(item)) { item.remove(true); } return this; } } if (arguments.length === 0) { destroy = true; } Group.superclass.remove.call(this, destroy); } return this; }, /** * 向组中添加shape或者group * @param {Object} items 图形或者分组 * @return {Object} group 本尊 */ add: function add(items) { var self = this; var children = self.get('children'); if (Util.isArray(items)) { Util.each(items, function (item) { var parent = item.get('parent'); if (parent) { parent.removeChild(item, false); } self._setCfgProperty(item); }); self._cfg.children = children.concat(items); } else { var item = items; var parent = item.get('parent'); if (parent) { parent.removeChild(item, false); } self._setCfgProperty(item); children.push(item); } return self; }, _setCfgProperty: function _setCfgProperty(item) { var cfg = this._cfg; item.set('parent', this); item.set('canvas', cfg.canvas); if (cfg.timeline) { item.set('timeline', cfg.timeline); } }, contain: function contain(item) { var children = this.get('children'); return children.indexOf(item) > -1; }, getChildByIndex: function getChildByIndex(index) { var children = this.get('children'); return children[index]; }, getFirst: function getFirst() { return this.getChildByIndex(0); }, getLast: function getLast() { var lastIndex = this.get('children').length - 1; return this.getChildByIndex(lastIndex); }, getBBox: function getBBox() { var self = this; var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; var children = self.get('children'); if (children.length > 0) { Util.each(children, function (child) { if (child.get('visible')) { if (child.isGroup && child.get('children').length === 0) { return; } var _box = child.getBBox(); if (!_box) { return true; } var leftTop = [_box.minX, _box.minY, 1]; var leftBottom = [_box.minX, _box.maxY, 1]; var rightTop = [_box.maxX, _box.minY, 1]; var rightBottom = [_box.maxX, _box.maxY, 1]; child.apply(leftTop); child.apply(leftBottom); child.apply(rightTop); child.apply(rightBottom); var boxMinX = Math.min(leftTop[0], leftBottom[0], rightTop[0], rightBottom[0]); var boxMaxX = Math.max(leftTop[0], leftBottom[0], rightTop[0], rightBottom[0]); var boxMinY = Math.min(leftTop[1], leftBottom[1], rightTop[1], rightBottom[1]); var boxMaxY = Math.max(leftTop[1], leftBottom[1], rightTop[1], rightBottom[1]); if (boxMinX < minX) { minX = boxMinX; } if (boxMaxX > maxX) { maxX = boxMaxX; } if (boxMinY < minY) { minY = boxMinY; } if (boxMaxY > maxY) { maxY = boxMaxY; } } }); } else { minX = 0; maxX = 0; minY = 0; maxY = 0; } var box = { minX: minX, minY: minY, maxX: maxX, maxY: maxY }; box.x = box.minX; box.y = box.minY; box.width = box.maxX - box.minX; box.height = box.maxY - box.minY; return box; }, getCount: function getCount() { return this.get('children').length; }, sort: function sort() { var children = this.get('children'); // 稳定排序 Util.each(children, function (child, index) { child[INDEX] = index; return child; }); children.sort(getComparer(function (obj1, obj2) { return obj1.get('zIndex') - obj2.get('zIndex'); })); return this; }, findById: function findById(id) { return this.find(function (item) { return item.get('id') === id; }); }, /** * 根据查找函数查找分组或者图形 * @param {Function} fn 匹配函数 * @return {Canvas.Base} 分组或者图形 */ find: function find(fn) { if (Util.isString(fn)) { return this.findById(fn); } var children = this.get('children'); var rst = null; Util.each(children, function (item) { if (fn(item)) { rst = item; } else if (item.find) { rst = item.find(fn); } if (rst) { return false; } }); return rst; }, /** * @param {Function} fn filter mathod * @return {Array} all the matching shapes and groups */ findAll: function findAll(fn) { var children = this.get('children'); var rst = []; var childRst = []; Util.each(children, function (item) { if (fn(item)) { rst.push(item); } if (item.findAllBy) { childRst = item.findAllBy(fn); rst = rst.concat(childRst); } }); return rst; }, /** * @Deprecated * @param {Function} fn filter method * @return {Object} found shape or group */ findBy: function findBy(fn) { var children = this.get('children'); var rst = null; Util.each(children, function (item) { if (fn(item)) { rst = item; } else if (item.findBy) { rst = item.findBy(fn); } if (rst) { return false; } }); return rst; }, /** * @Deprecated * @param {Function} fn filter mathod * @return {Array} all the matching shapes and groups */ findAllBy: function findAllBy(fn) { var children = this.get('children'); var rst = []; var childRst = []; Util.each(children, function (item) { if (fn(item)) { rst.push(item); } if (item.findAllBy) { childRst = item.findAllBy(fn); rst = rst.concat(childRst); } }); return rst; }, getShape: function getShape(x, y) { var self = this; var clip = self._attrs.clip; var children = self._cfg.children; var rst; if (clip) { var v = [x, y, 1]; clip.invert(v, self.get('canvas')); // 已经在外面转换 if (clip.isPointInPath(v[0], v[1])) { rst = find(children, x, y); } } else { rst = find(children, x, y); } return rst; }, clearTotalMatrix: function clearTotalMatrix() { var m = this.get('totalMatrix'); if (m) { this.setSilent('totalMatrix', null); var children = this._cfg.children; for (var i = 0; i < children.length; i++) { var child = children[i]; child.clearTotalMatrix(); } } }, clear: function clear(delayRemove) { if (this.get('destroyed')) { return; } var children = this._cfg.children; for (var i = children.length - 1; i >= 0; i--) { children[i].remove(true, delayRemove); } this._cfg.children = []; return this; }, destroy: function destroy() { if (this.get('destroyed')) { return; } this.clear(); Group.superclass.destroy.call(this); }, clone: function clone() { var self = this; var children = self._cfg.children; var _attrs = self._attrs; var attrs = {}; Util.each(_attrs, function (i, k) { if (k === 'matrix') { attrs[k] = _cloneArrayAttr(_attrs[k]); } else { attrs[k] = _attrs[k]; } }); var clone = new Group({ attrs: attrs, canvas: self.get('canvas') }); Util.each(children, function (child) { clone.add(child.clone()); }); // 对于一些在 cfg 中的特殊属性做 clone Util.each(CLONE_CFGS, function (cfg) { clone._cfg[cfg] = self._cfg[cfg]; }); return clone; } }); module.exports = Group; /***/ }), /* 116 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Attribute = __webpack_require__(222); var Transform = __webpack_require__(223); var Animate = __webpack_require__(224); var EventEmitter = __webpack_require__(225); var Element = function Element(cfg) { this._cfg = { zIndex: 0, capture: true, visible: true, destroyed: false }; // 配置存放地 Util.assign(this._cfg, this.getDefaultCfg(), cfg); // Element.CFG不合并,提升性能 合并默认配置,用户配置->继承默认配置->Element默认配置 this.initAttrs(this._cfg.attrs); // 初始化绘图属性 this._cfg.attrs = {}; this.initTransform(); // 初始化变换 this.init(); // 类型初始化 }; Element.CFG = { /** * 唯一标示 * @type {Number} */ id: null, /** * Z轴的层叠关系,Z值越大离用户越近 * @type {Number} */ zIndex: 0, /** * Canvas对象 * @type: {Object} */ canvas: null, /** * 父元素指针 * @type {Object} */ parent: null, /** * 用来设置当前对象是否能被捕捉 * true 能 * false 不能 * 对象默认是都可以被捕捉的, 当capture为false时,group.getShape(x, y)方法无法获得该元素 * 通过将不必要捕捉的元素的该属性设置成false, 来提高捕捉性能 * @type {Boolean} **/ capture: true, /** * 画布的上下文 * @type {Object} */ context: null, /** * 是否显示 * @type {Boolean} */ visible: true, /** * 是否被销毁 * @type: {Boolean} */ destroyed: false }; Util.augment(Element, Attribute, Transform, EventEmitter, Animate, { init: function init() { this.setSilent('animable', true); this.setSilent('animating', false); // 初始时不处于动画状态 }, getParent: function getParent() { return this._cfg.parent; }, /** * 获取默认的配置信息 * @protected * @return {Object} 默认的属性 */ getDefaultCfg: function getDefaultCfg() { return {}; }, set: function set(name, value) { if (name === 'zIndex' && this._beforeSetZIndex) { this._beforeSetZIndex(value); } if (name === 'loading' && this._beforeSetLoading) { this._beforeSetLoading(value); } this._cfg[name] = value; return this; }, // deprecated setSilent: function setSilent(name, value) { this._cfg[name] = value; }, get: function get(name) { return this._cfg[name]; }, show: function show() { this._cfg.visible = true; return this; }, hide: function hide() { this._cfg.visible = false; return this; }, remove: function remove(destroy, delayRemove) { var cfg = this._cfg; var parent = cfg.parent; var el = cfg.el; if (parent) { Util.remove(parent.get('children'), this); } if (el) { if (delayRemove) { parent && parent._cfg.tobeRemoved.push(el); } else { el.parentNode.removeChild(el); } } if (destroy || destroy === undefined) { this.destroy(); } return this; }, destroy: function destroy() { var destroyed = this.get('destroyed'); if (destroyed) { return; } this._attrs = null; this.removeEvent(); // 移除所有的事件 this._cfg = { destroyed: true }; }, toFront: function toFront() { var cfg = this._cfg; var parent = cfg.parent; if (!parent) { return; } var children = parent._cfg.children; var el = cfg.el; var index = children.indexOf(this); children.splice(index, 1); children.push(this); if (el) { el.parentNode.removeChild(el); cfg.el = null; } }, toBack: function toBack() { var cfg = this._cfg; var parent = cfg.parent; if (!parent) { return; } var children = parent._cfg.children; var el = cfg.el; var index = children.indexOf(this); children.splice(index, 1); children.unshift(this); if (el) { var parentNode = el.parentNode; parentNode.removeChild(el); parentNode.insertBefore(el, parentNode.firstChild); } }, _beforeSetZIndex: function _beforeSetZIndex(zIndex) { var parent = this._cfg.parent; this._cfg.zIndex = zIndex; if (!Util.isNil(parent)) { parent.sort(); } var el = this._cfg.el; if (el) { var children = parent._cfg.children; var index = children.indexOf(this); var parentNode = el.parentNode; parentNode.removeChild(el); if (index === children.length - 1) { parentNode.appendChild(el); } else { parentNode.insertBefore(el, parentNode.childNodes[index]); } } return zIndex; }, _setAttrs: function _setAttrs(attrs) { this.attr(attrs); return attrs; }, setZIndex: function setZIndex(zIndex) { this._cfg.zIndex = zIndex; return this._beforeSetZIndex(zIndex); }, clone: function clone() { return Util.clone(this); }, getBBox: function getBBox() {} }); module.exports = Element; /***/ }), /* 117 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(59); var slice = Array.prototype.slice; function indexOfCallback(events, callback) { var i = events.length; while (i--) { if (events[i].callback === callback) { return i; } } return -1; } var EventEmitter = function EventEmitter() {}; Util.augment(EventEmitter, { on: function on(evt, callback, one) { var self = this; if (!Util.isFunction(callback)) { throw new TypeError('listener should be a function'); } if (!self._cfg._events) { self._cfg._events = {}; } if (!self._cfg._events[evt]) { self._cfg._events[evt] = []; } self._cfg._events[evt].push({ callback: callback, one: one }); return this; }, one: function one(evt, callback) { this.on(evt, callback, true); return this; }, emit: function emit(evt) { if (this.get('destroyed')) { return; } if (!this._cfg._events || Util.isEmpty(this._cfg._events)) { return; } var events = this._cfg._events[evt]; if (Util.isEmpty(events)) { return; } var args = arguments; var arg = slice.call(args, 1); var length = events.length; for (var i = 0; i < length;) { if (!events[i]) { continue; } events[i].callback.apply(this, arg); if (events[i] && events[i].one) { events.splice(i, 1); length--; } else { i++; } } }, trigger: function trigger() { this.emit.apply(this, arguments); }, off: function off(evt, callback) { var events = this._cfg._events; if (!events || Util.isEmpty(events)) { return; } if (arguments.length === 0) { this._cfg._events = {}; return this; } if (events[evt]) { var index = indexOfCallback(events[evt], callback); if (index >= 0) { events[evt].splice(index, 1); } if (events[evt].length === 0) { delete events[evt]; } } }, removeEvent: function removeEvent(evt) { if (typeof evt === 'undefined') { this._cfg._events = {}; } else { delete this._cfg._events[evt]; } return this; }, _getEvents: function _getEvents() { return this._cfg._events || {}; } }); module.exports = EventEmitter; /***/ }), /* 118 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var vec2 = Util.vec2; function quadraticAt(p0, p1, p2, t) { var onet = 1 - t; return onet * (onet * p0 + 2 * t * p1) + t * t * p2; } function quadraticProjectPoint(x1, y1, x2, y2, x3, y3, x, y, out) { var t; var interval = 0.005; var d = Infinity; var d1; var v1; var v2; var _t; var d2; var i; var EPSILON = 0.0001; var v0 = [x, y]; for (_t = 0; _t < 1; _t += 0.05) { v1 = [quadraticAt(x1, x2, x3, _t), quadraticAt(y1, y2, y3, _t)]; d1 = vec2.squaredDistance(v0, v1); if (d1 < d) { t = _t; d = d1; } } d = Infinity; for (i = 0; i < 32; i++) { if (interval < EPSILON) { break; } var prev = t - interval; var next = t + interval; v1 = [quadraticAt(x1, x2, x3, prev), quadraticAt(y1, y2, y3, prev)]; d1 = vec2.squaredDistance(v0, v1); if (prev >= 0 && d1 < d) { t = prev; d = d1; } else { v2 = [quadraticAt(x1, x2, x3, next), quadraticAt(y1, y2, y3, next)]; d2 = vec2.squaredDistance(v0, v2); if (next <= 1 && d2 < d) { t = next; d = d2; } else { interval *= 0.5; } } } if (out) { out.x = quadraticAt(x1, x2, x3, t); out.y = quadraticAt(y1, y2, y3, t); } return Math.sqrt(d); } function quadraticExtrema(p0, p1, p2) { var a = p0 + p2 - 2 * p1; if (Util.isNumberEqual(a, 0)) { return [0.5]; } var rst = (p0 - p1) / a; if (rst <= 1 && rst >= 0) { return [rst]; } return []; } module.exports = { at: quadraticAt, projectPoint: function projectPoint(x1, y1, x2, y2, x3, y3, x, y) { var rst = {}; quadraticProjectPoint(x1, y1, x2, y2, x3, y3, x, y, rst); return rst; }, pointDistance: quadraticProjectPoint, extrema: quadraticExtrema }; /***/ }), /* 119 */ /***/ (function(module, exports) { module.exports = { xAt: function xAt(psi, rx, ry, cx, t) { return rx * Math.cos(psi) * Math.cos(t) - ry * Math.sin(psi) * Math.sin(t) + cx; }, yAt: function yAt(psi, rx, ry, cy, t) { return rx * Math.sin(psi) * Math.cos(t) + ry * Math.cos(psi) * Math.sin(t) + cy; }, xExtrema: function xExtrema(psi, rx, ry) { return Math.atan(-ry / rx * Math.tan(psi)); }, yExtrema: function yExtrema(psi, rx, ry) { return Math.atan(ry / (rx * Math.tan(psi))); } }; /***/ }), /* 120 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Shape = __webpack_require__(7); var ArcMath = __webpack_require__(44); var Arrow = __webpack_require__(45); function _getArcX(x, radius, angle) { return x + radius * Math.cos(angle); } function _getArcY(y, radius, angle) { return y + radius * Math.sin(angle); } var Arc = function Arc(cfg) { Arc.superclass.constructor.call(this, cfg); }; Arc.ATTRS = { x: 0, y: 0, r: 0, startAngle: 0, endAngle: 0, clockwise: false, lineWidth: 1, startArrow: false, endArrow: false }; Util.extend(Arc, Shape); Util.augment(Arc, { canStroke: true, type: 'arc', getDefaultAttrs: function getDefaultAttrs() { return { x: 0, y: 0, r: 0, startAngle: 0, endAngle: 0, clockwise: false, lineWidth: 1, startArrow: false, endArrow: false }; }, calculateBox: function calculateBox() { var attrs = this._attrs; var x = attrs.x, y = attrs.y, r = attrs.r, startAngle = attrs.startAngle, endAngle = attrs.endAngle, clockwise = attrs.clockwise; var lineWidth = this.getHitLineWidth(); var halfWidth = lineWidth / 2; var box = ArcMath.box(x, y, r, startAngle, endAngle, clockwise); box.minX -= halfWidth; box.minY -= halfWidth; box.maxX += halfWidth; box.maxY += halfWidth; return box; }, getStartTangent: function getStartTangent() { var attrs = this._attrs; var x = attrs.x, y = attrs.y, startAngle = attrs.startAngle, r = attrs.r, clockwise = attrs.clockwise; var diff = Math.PI / 180; if (clockwise) { diff *= -1; } var result = []; var x1 = _getArcX(x, r, startAngle + diff); var y1 = _getArcY(y, r, startAngle + diff); var x2 = _getArcX(x, r, startAngle); var y2 = _getArcY(y, r, startAngle); result.push([x1, y1]); result.push([x2, y2]); return result; }, getEndTangent: function getEndTangent() { var attrs = this._attrs; var x = attrs.x, y = attrs.y, endAngle = attrs.endAngle, r = attrs.r, clockwise = attrs.clockwise; var diff = Math.PI / 180; var result = []; if (clockwise) { diff *= -1; } var x1 = _getArcX(x, r, endAngle + diff); var y1 = _getArcY(y, r, endAngle + diff); var x2 = _getArcX(x, r, endAngle); var y2 = _getArcY(y, r, endAngle); result.push([x2, y2]); result.push([x1, y1]); return result; }, createPath: function createPath(context) { var attrs = this._attrs; var x = attrs.x, y = attrs.y, r = attrs.r, startAngle = attrs.startAngle, endAngle = attrs.endAngle, clockwise = attrs.clockwise; context = context || self.get('context'); context.beginPath(); context.arc(x, y, r, startAngle, endAngle, clockwise); }, afterPath: function afterPath(context) { var attrs = this._attrs; context = context || this.get('context'); if (attrs.startArrow) { var startPoints = this.getStartTangent(); Arrow.addStartArrow(context, attrs, startPoints[0][0], startPoints[0][1], startPoints[1][0], startPoints[1][1]); } if (attrs.endArrow) { var endPoints = this.getEndTangent(); Arrow.addEndArrow(context, attrs, endPoints[0][0], endPoints[0][1], endPoints[1][0], endPoints[1][1]); } } }); module.exports = Arc; /***/ }), /* 121 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Shape = __webpack_require__(7); var Circle = function Circle(cfg) { Circle.superclass.constructor.call(this, cfg); }; Circle.ATTRS = { x: 0, y: 0, r: 0, lineWidth: 1 }; Util.extend(Circle, Shape); Util.augment(Circle, { canFill: true, canStroke: true, type: 'circle', getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1 }; }, calculateBox: function calculateBox() { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var r = attrs.r; var lineWidth = this.getHitLineWidth(); var halfWidth = lineWidth / 2 + r; return { minX: cx - halfWidth, minY: cy - halfWidth, maxX: cx + halfWidth, maxY: cy + halfWidth }; }, createPath: function createPath(context) { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var r = attrs.r; context.beginPath(); context.arc(cx, cy, r, 0, Math.PI * 2, false); context.closePath(); } }); module.exports = Circle; /***/ }), /* 122 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Shape = __webpack_require__(7); var Dom = function Dom(cfg) { Dom.superclass.constructor.call(this, cfg); }; Util.extend(Dom, Shape); Util.augment(Dom, { canFill: true, canStroke: true, type: 'dom', calculateBox: function calculateBox() { var self = this; var attrs = self._attrs; var x = attrs.x; var y = attrs.y; var width = attrs.width; var height = attrs.height; var lineWidth = this.getHitLineWidth(); var halfWidth = lineWidth / 2; return { minX: x - halfWidth, minY: y - halfWidth, maxX: x + width + halfWidth, maxY: y + height + halfWidth }; } }); module.exports = Dom; /***/ }), /* 123 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Shape = __webpack_require__(7); var Ellipse = function Ellipse(cfg) { Ellipse.superclass.constructor.call(this, cfg); }; Ellipse.ATTRS = { x: 0, y: 0, rx: 1, ry: 1, lineWidth: 1 }; Util.extend(Ellipse, Shape); Util.augment(Ellipse, { canFill: true, canStroke: true, type: 'ellipse', getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1 }; }, calculateBox: function calculateBox() { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var rx = attrs.rx; var ry = attrs.ry; var lineWidth = this.getHitLineWidth(); var halfXWidth = rx + lineWidth / 2; var halfYWidth = ry + lineWidth / 2; return { minX: cx - halfXWidth, minY: cy - halfYWidth, maxX: cx + halfXWidth, maxY: cy + halfYWidth }; }, createPath: function createPath(context) { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var rx = attrs.rx; var ry = attrs.ry; context = context || self.get('context'); var r = rx > ry ? rx : ry; var scaleX = rx > ry ? 1 : rx / ry; var scaleY = rx > ry ? ry / rx : 1; var m = [1, 0, 0, 0, 1, 0, 0, 0, 1]; Util.mat3.scale(m, m, [scaleX, scaleY]); Util.mat3.translate(m, m, [cx, cy]); context.beginPath(); context.save(); context.transform(m[0], m[1], m[3], m[4], m[6], m[7]); context.arc(0, 0, r, 0, Math.PI * 2); context.restore(); context.closePath(); } }); module.exports = Ellipse; /***/ }), /* 124 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Shape = __webpack_require__(7); var ArcMath = __webpack_require__(44); var Fan = function Fan(cfg) { Fan.superclass.constructor.call(this, cfg); }; Fan.ATTRS = { x: 0, y: 0, rs: 0, re: 0, startAngle: 0, endAngle: 0, clockwise: false, lineWidth: 1 }; Util.extend(Fan, Shape); Util.augment(Fan, { canFill: true, canStroke: true, type: 'fan', getDefaultAttrs: function getDefaultAttrs() { return { clockwise: false, lineWidth: 1, rs: 0, re: 0 }; }, calculateBox: function calculateBox() { var self = this; var attrs = self._attrs; var cx = attrs.x; var cy = attrs.y; var rs = attrs.rs; var re = attrs.re; var startAngle = attrs.startAngle; var endAngle = attrs.endAngle; var clockwise = attrs.clockwise; var lineWidth = this.getHitLineWidth(); var boxs = ArcMath.box(cx, cy, rs, startAngle, endAngle, clockwise); var boxe = ArcMath.box(cx, cy, re, startAngle, endAngle, clockwise); var minX = Math.min(boxs.minX, boxe.minX); var minY = Math.min(boxs.minY, boxe.minY); var maxX = Math.max(boxs.maxX, boxe.maxX); var maxY = Math.max(boxs.maxY, boxe.maxY); var halfWidth = lineWidth / 2; return { minX: minX - halfWidth, minY: minY - halfWidth, maxX: maxX + halfWidth, maxY: maxY + halfWidth }; }, createPath: function createPath(context) { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var rs = attrs.rs; var re = attrs.re; var startAngle = attrs.startAngle; var endAngle = attrs.endAngle; var clockwise = attrs.clockwise; var ssp = { x: Math.cos(startAngle) * rs + cx, y: Math.sin(startAngle) * rs + cy }; var sep = { x: Math.cos(startAngle) * re + cx, y: Math.sin(startAngle) * re + cy }; var esp = { x: Math.cos(endAngle) * rs + cx, y: Math.sin(endAngle) * rs + cy }; context = context || self.get('context'); context.beginPath(); context.moveTo(ssp.x, ssp.y); context.lineTo(sep.x, sep.y); context.arc(cx, cy, re, startAngle, endAngle, clockwise); context.lineTo(esp.x, esp.y); context.arc(cx, cy, rs, endAngle, startAngle, !clockwise); context.closePath(); } }); module.exports = Fan; /***/ }), /* 125 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Shape = __webpack_require__(7); var CImage = function CImage(cfg) { CImage.superclass.constructor.call(this, cfg); }; CImage.ATTRS = { x: 0, y: 0, img: undefined, width: 0, height: 0, sx: null, sy: null, swidth: null, sheight: null }; Util.extend(CImage, Shape); Util.augment(CImage, { type: 'image', isHitBox: function isHitBox() { return false; }, calculateBox: function calculateBox() { var attrs = this._attrs; if (!this._cfg.attrs || this._cfg.attrs.img !== attrs.img) { this._setAttrImg(); } var x = attrs.x; var y = attrs.y; var width = attrs.width; var height = attrs.height; return { minX: x, minY: y, maxX: x + width, maxY: y + height }; }, _beforeSetLoading: function _beforeSetLoading(loading) { var canvas = this.get('canvas'); if (loading === false && this.get('toDraw') === true) { this._cfg.loading = false; canvas.draw(); } return loading; }, _setAttrImg: function _setAttrImg() { var self = this; var attrs = self._attrs; var img = attrs.img; if (Util.isString(img)) { var image = new Image(); image.onload = function () { if (self.get('destroyed')) return false; self.attr('imgSrc', img); self.attr('img', image); var callback = self.get('callback'); if (callback) { callback.call(self); } self.set('loading', false); }; image.src = img; image.crossOrigin = 'Anonymous'; self.set('loading', true); } else if (img instanceof Image) { if (!attrs.width) { self.attr('width', img.width); } if (!attrs.height) { self.attr('height', img.height); } return img; } else if (img instanceof HTMLElement && Util.isString(img.nodeName) && img.nodeName.toUpperCase() === 'CANVAS') { if (!attrs.width) { self.attr('width', Number(img.getAttribute('width'))); } if (!attrs.height) { self.attr('height', Number(img.getAttribute('height'))); } return img; } else if (img instanceof ImageData) { if (!attrs.width) { self.attr('width', img.width); } if (!attrs.height) { self.attr('height', img.height); } return img; } else { return null; } }, drawInner: function drawInner(context) { if (this._cfg.hasUpdate) { this._setAttrImg(); } if (this.get('loading')) { this.set('toDraw', true); return; } this._drawImage(context); this._cfg.hasUpdate = false; }, _drawImage: function _drawImage(context) { var attrs = this._attrs; var x = attrs.x; var y = attrs.y; var image = attrs.img; var width = attrs.width; var height = attrs.height; var sx = attrs.sx; var sy = attrs.sy; var swidth = attrs.swidth; var sheight = attrs.sheight; this.set('toDraw', false); var img = image; if (img instanceof ImageData) { img = new Image(); img.src = image; } if (img instanceof Image || img instanceof HTMLElement && Util.isString(img.nodeName) && img.nodeName.toUpperCase() === 'CANVAS') { if (Util.isNil(sx) || Util.isNil(sy) || Util.isNil(swidth) || Util.isNil(sheight)) { context.drawImage(img, x, y, width, height); return; } if (!Util.isNil(sx) && !Util.isNil(sy) && !Util.isNil(swidth) && !Util.isNil(sheight)) { context.drawImage(img, sx, sy, swidth, sheight, x, y, width, height); return; } } return; } }); module.exports = CImage; /***/ }), /* 126 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Shape = __webpack_require__(7); var Arrow = __webpack_require__(45); var LineMath = __webpack_require__(43); var Line = function Line(cfg) { Line.superclass.constructor.call(this, cfg); }; Line.ATTRS = { x1: 0, y1: 0, x2: 0, y2: 0, lineWidth: 1, startArrow: false, endArrow: false }; Util.extend(Line, Shape); Util.augment(Line, { canStroke: true, type: 'line', getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1, startArrow: false, endArrow: false }; }, calculateBox: function calculateBox() { var attrs = this._attrs; var x1 = attrs.x1, y1 = attrs.y1, x2 = attrs.x2, y2 = attrs.y2; var lineWidth = this.getHitLineWidth(); return LineMath.box(x1, y1, x2, y2, lineWidth); }, createPath: function createPath(context) { var self = this; var attrs = this._attrs; var x1 = attrs.x1, y1 = attrs.y1, x2 = attrs.x2, y2 = attrs.y2; // 如果定义了箭头,并且是自定义箭头,线条相应缩进 if (attrs.startArrow && attrs.startArrow.d) { var dist = Arrow.getShortenOffset(x1, y1, x2, y2, attrs.startArrow.d); x1 += dist.dx; y1 += dist.dy; } if (attrs.endArrow && attrs.endArrow.d) { var _dist = Arrow.getShortenOffset(x1, y1, x2, y2, attrs.endArrow.d); x2 -= _dist.dx; y2 -= _dist.dy; } context = context || self.get('context'); context.beginPath(); context.moveTo(x1, y1); context.lineTo(x2, y2); }, afterPath: function afterPath(context) { var self = this; var attrs = self._attrs; var x1 = attrs.x1, y1 = attrs.y1, x2 = attrs.x2, y2 = attrs.y2; context = context || self.get('context'); if (attrs.startArrow) { Arrow.addStartArrow(context, attrs, x2, y2, x1, y1); } if (attrs.endArrow) { Arrow.addEndArrow(context, attrs, x1, y1, x2, y2); } }, getPoint: function getPoint(t) { var attrs = this._attrs; return { x: LineMath.at(attrs.x1, attrs.x2, t), y: LineMath.at(attrs.y1, attrs.y2, t) }; } }); module.exports = Line; /***/ }), /* 127 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Shape = __webpack_require__(7); var PathSegment = __webpack_require__(46); var Format = __webpack_require__(31); var Arrow = __webpack_require__(45); var PathUtil = __webpack_require__(82); var CubicMath = __webpack_require__(80); var Path = function Path(cfg) { Path.superclass.constructor.call(this, cfg); }; Path.ATTRS = { path: null, lineWidth: 1, startArrow: false, endArrow: false }; Util.extend(Path, Shape); Util.augment(Path, { canFill: true, canStroke: true, type: 'path', getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1, startArrow: false, endArrow: false }; }, _afterSetAttrPath: function _afterSetAttrPath(path) { var self = this; if (Util.isNil(path)) { self.setSilent('segments', null); self.setSilent('box', undefined); return; } var pathArray = Format.parsePath(path); var preSegment; var segments = []; if (!Util.isArray(pathArray) || pathArray.length === 0 || pathArray[0][0] !== 'M' && pathArray[0][0] !== 'm') { return; } var count = pathArray.length; for (var i = 0; i < pathArray.length; i++) { var item = pathArray[i]; preSegment = new PathSegment(item, preSegment, i === count - 1); segments.push(preSegment); } self.setSilent('segments', segments); self.setSilent('tCache', null); self.setSilent('totalLength', null); self.setSilent('box', null); }, calculateBox: function calculateBox() { var self = this; var segments = self.get('segments'); if (!segments) { return null; } var lineWidth = this.getHitLineWidth(); var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; Util.each(segments, function (segment) { segment.getBBox(lineWidth); var box = segment.box; if (box) { if (box.minX < minX) { minX = box.minX; } if (box.maxX > maxX) { maxX = box.maxX; } if (box.minY < minY) { minY = box.minY; } if (box.maxY > maxY) { maxY = box.maxY; } } }); if (minX === Infinity || minY === Infinity) { return { minX: 0, minY: 0, maxX: 0, maxY: 0 }; } return { minX: minX, minY: minY, maxX: maxX, maxY: maxY }; }, _setTcache: function _setTcache() { var totalLength = 0; var tempLength = 0; var tCache = []; var segmentT; var segmentL; var segmentN; var l; var curve = this._cfg.curve; if (!curve) { return; } Util.each(curve, function (segment, i) { segmentN = curve[i + 1]; l = segment.length; if (segmentN) { totalLength += CubicMath.len(segment[l - 2], segment[l - 1], segmentN[1], segmentN[2], segmentN[3], segmentN[4], segmentN[5], segmentN[6]); } }); this._cfg.totalLength = totalLength; if (totalLength === 0) { this._cfg.tCache = []; return; } Util.each(curve, function (segment, i) { segmentN = curve[i + 1]; l = segment.length; if (segmentN) { segmentT = []; segmentT[0] = tempLength / totalLength; segmentL = CubicMath.len(segment[l - 2], segment[l - 1], segmentN[1], segmentN[2], segmentN[3], segmentN[4], segmentN[5], segmentN[6]); tempLength += segmentL; segmentT[1] = tempLength / totalLength; tCache.push(segmentT); } }); this._cfg.tCache = tCache; }, getTotalLength: function getTotalLength() { var totalLength = this.get('totalLength'); if (!Util.isNil(totalLength)) { return totalLength; } this._calculateCurve(); this._setTcache(); return this.get('totalLength'); }, _calculateCurve: function _calculateCurve() { var self = this; var attrs = self._attrs; var path = attrs.path; this._cfg.curve = PathUtil.pathTocurve(path); }, getStartTangent: function getStartTangent() { var segments = this.get('segments'); var startPoint, endPoint, tangent, result; if (segments.length > 1) { startPoint = segments[0].endPoint; endPoint = segments[1].endPoint; tangent = segments[1].startTangent; result = []; if (Util.isFunction(tangent)) { var v = tangent(); result.push([startPoint.x - v[0], startPoint.y - v[1]]); result.push([startPoint.x, startPoint.y]); } else { result.push([endPoint.x, endPoint.y]); result.push([startPoint.x, startPoint.y]); } } return result; }, getEndTangent: function getEndTangent() { var segments = this.get('segments'); var segmentsLen = segments.length; var startPoint, endPoint, tangent, result; if (segmentsLen > 1) { startPoint = segments[segmentsLen - 2].endPoint; endPoint = segments[segmentsLen - 1].endPoint; tangent = segments[segmentsLen - 1].endTangent; result = []; if (Util.isFunction(tangent)) { var v = tangent(); result.push([endPoint.x - v[0], endPoint.y - v[1]]); result.push([endPoint.x, endPoint.y]); } else { result.push([startPoint.x, startPoint.y]); result.push([endPoint.x, endPoint.y]); } } return result; }, getPoint: function getPoint(t) { var tCache = this._cfg.tCache; var subt; var index; if (!tCache) { this._calculateCurve(); this._setTcache(); tCache = this._cfg.tCache; } var curve = this._cfg.curve; if (!tCache || tCache.length === 0) { if (curve) { return { x: curve[0][1], y: curve[0][2] }; } return null; } Util.each(tCache, function (v, i) { if (t >= v[0] && t <= v[1]) { subt = (t - v[0]) / (v[1] - v[0]); index = i; } }); var seg = curve[index]; if (Util.isNil(seg) || Util.isNil(index)) { return null; } var l = seg.length; var nextSeg = curve[index + 1]; return { x: CubicMath.at(seg[l - 2], nextSeg[1], nextSeg[3], nextSeg[5], 1 - subt), y: CubicMath.at(seg[l - 1], nextSeg[2], nextSeg[4], nextSeg[6], 1 - subt) }; }, createPath: function createPath(context) { var self = this; var attrs = self._attrs; var segments = self.get('segments'); if (!Util.isArray(segments)) { return; } var segmentsLen = segments.length; if (segmentsLen === 0) { return; } context = context || self.get('context'); context.beginPath(); if (attrs.startArrow && attrs.startArrow.d) { // 如果 startArrow 需要做偏移,为了保证 path 长度一定,需要向内缩进一定距离 // 如果直接修改 PathSegment 的 params 会导致画布每重绘一次线条便缩短一截 // 所以在绘制时计算要缩进的距离,直接绘制出来 var tangent = self.getStartTangent(); var dist = Arrow.getShortenOffset(tangent[0][0], tangent[0][1], tangent[1][0], tangent[1][1], attrs.startArrow.d); segments[0].shortenDraw(context, dist.dx, dist.dy); } else { segments[0].draw(context); } for (var i = 1; i < segmentsLen - 2; i++) { segments[i].draw(context); } if (attrs.endArrow && attrs.endArrow.d) { // 如果 endArrow 需要做偏移,跟 startArrow 一样处理 // 为了防止结尾为 'Z' 的 segment 缩短不起效,需要取最后两个 segment 特殊处理 var _tangent = self.getEndTangent(); var _dist = Arrow.getShortenOffset(_tangent[0][0], _tangent[0][1], _tangent[1][0], _tangent[1][1], attrs.endArrow.d); var segment = segments[segmentsLen - 1]; if (segment.command.toUpperCase() === 'Z') { if (segments[segmentsLen - 2]) { segments[segmentsLen - 2].shortenDraw(context, _dist.dx, _dist.dy); } segment.draw(context); } else { if (segmentsLen > 2) { segments[segmentsLen - 2].draw(context); } segment.shortenDraw(context, _dist.dx, _dist.dy); } } else { if (segments[segmentsLen - 2]) { segments[segmentsLen - 2].draw(context); } segments[segmentsLen - 1].draw(context); } }, afterPath: function afterPath(context) { var self = this; var attrs = self._attrs; var segments = self.get('segments'); var path = attrs.path; context = context || self.get('context'); if (!Util.isArray(segments)) { return; } if (segments.length === 1) { return; } if (!attrs.startArrow && !attrs.endArrow) { return; } if (path[path.length - 1] === 'z' || path[path.length - 1] === 'Z' || attrs.fill) { // 闭合路径不绘制箭头 return; } var startPoints = self.getStartTangent(); Arrow.addStartArrow(context, attrs, startPoints[0][0], startPoints[0][1], startPoints[1][0], startPoints[1][1]); var endPoints = self.getEndTangent(); Arrow.addEndArrow(context, attrs, endPoints[0][0], endPoints[0][1], endPoints[1][0], endPoints[1][1]); } }); module.exports = Path; /***/ }), /* 128 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Shape = __webpack_require__(7); var Polygon = function Polygon(cfg) { Polygon.superclass.constructor.call(this, cfg); }; Polygon.ATTRS = { points: null, lineWidth: 1 }; Util.extend(Polygon, Shape); Util.augment(Polygon, { canFill: true, canStroke: true, type: 'polygon', getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1 }; }, calculateBox: function calculateBox() { var self = this; var attrs = self._attrs; var points = attrs.points; var lineWidth = this.getHitLineWidth(); if (!points || points.length === 0) { return null; } var minX = Infinity; var minY = Infinity; var maxX = -Infinity; var maxY = -Infinity; Util.each(points, function (point) { var x = point[0]; var y = point[1]; if (x < minX) { minX = x; } if (x > maxX) { maxX = x; } if (y < minY) { minY = y; } if (y > maxY) { maxY = y; } }); var halfWidth = lineWidth / 2; return { minX: minX - halfWidth, minY: minY - halfWidth, maxX: maxX + halfWidth, maxY: maxY + halfWidth }; }, createPath: function createPath(context) { var self = this; var attrs = self._attrs; var points = attrs.points; if (points.length < 2) { return; } context = context || self.get('context'); context.beginPath(); Util.each(points, function (point, index) { if (index === 0) { context.moveTo(point[0], point[1]); } else { context.lineTo(point[0], point[1]); } }); context.closePath(); } }); module.exports = Polygon; /***/ }), /* 129 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Shape = __webpack_require__(7); var Arrow = __webpack_require__(45); var LineMath = __webpack_require__(43); var Polyline = function Polyline(cfg) { Polyline.superclass.constructor.call(this, cfg); }; Polyline.ATTRS = { points: null, lineWidth: 1, startArrow: false, endArrow: false, tCache: null }; Util.extend(Polyline, Shape); Util.augment(Polyline, { canStroke: true, type: 'polyline', tCache: null, // 缓存各点的t getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1, startArrow: false, endArrow: false }; }, calculateBox: function calculateBox() { var self = this; var attrs = self._attrs; var lineWidth = this.getHitLineWidth(); var points = attrs.points; if (!points || points.length === 0) { return null; } var minX = Infinity; var minY = Infinity; var maxX = -Infinity; var maxY = -Infinity; Util.each(points, function (point) { var x = point[0]; var y = point[1]; if (x < minX) { minX = x; } if (x > maxX) { maxX = x; } if (y < minY) { minY = y; } if (y > maxY) { maxY = y; } }); var halfWidth = lineWidth / 2; return { minX: minX - halfWidth, minY: minY - halfWidth, maxX: maxX + halfWidth, maxY: maxY + halfWidth }; }, _setTcache: function _setTcache() { var self = this; var attrs = self._attrs; var points = attrs.points; var totalLength = 0; var tempLength = 0; var tCache = []; var segmentT; var segmentL; if (!points || points.length === 0) { return; } Util.each(points, function (p, i) { if (points[i + 1]) { totalLength += LineMath.len(p[0], p[1], points[i + 1][0], points[i + 1][1]); } }); if (totalLength <= 0) { return; } Util.each(points, function (p, i) { if (points[i + 1]) { segmentT = []; segmentT[0] = tempLength / totalLength; segmentL = LineMath.len(p[0], p[1], points[i + 1][0], points[i + 1][1]); tempLength += segmentL; segmentT[1] = tempLength / totalLength; tCache.push(segmentT); } }); this.tCache = tCache; }, createPath: function createPath(context) { var self = this; var attrs = self._attrs; var points = attrs.points; var i; if (points.length < 2) { return; } var len = points.length - 1; var x1 = points[0][0], y1 = points[0][1], x2 = points[len][0], y2 = points[len][1]; // 如果定义了箭头,并且是自定义箭头,线条相应缩进 if (attrs.startArrow && attrs.startArrow.d) { var dist = Arrow.getShortenOffset(points[0][0], points[0][1], points[1][0], points[1][1], attrs.startArrow.d); x1 += dist.dx; y1 += dist.dy; } if (attrs.endArrow && attrs.endArrow.d) { var _dist = Arrow.getShortenOffset(points[len - 1][0], points[len - 1][1], points[len][0], points[len][1], attrs.endArrow.d); x2 -= _dist.dx; y2 -= _dist.dy; } context = context || self.get('context'); context.beginPath(); context.moveTo(x1, y1); for (i = 1; i < len; i++) { context.lineTo(points[i][0], points[i][1]); } context.lineTo(x2, y2); }, getStartTangent: function getStartTangent() { var points = this.__attrs.points; var result = []; result.push([points[1][0], points[1][1]]); result.push([points[0][0], points[0][1]]); return result; }, getEndTangent: function getEndTangent() { var points = this.__attrs.points; var l = points.length - 1; var result = []; result.push([points[l - 1][0], points[l - 1][1]]); result.push([points[l][0], points[l][1]]); return result; }, afterPath: function afterPath(context) { var self = this; var attrs = self._attrs; var points = attrs.points; var l = points.length - 1; context = context || self.get('context'); if (attrs.startArrow) { Arrow.addStartArrow(context, attrs, points[1][0], points[1][1], points[0][0], points[0][1]); } if (attrs.endArrow) { Arrow.addEndArrow(context, attrs, points[l - 1][0], points[l - 1][1], points[l][0], points[l][1]); } }, getPoint: function getPoint(t) { var attrs = this._attrs; var points = attrs.points; var tCache = this.tCache; var subt; var index; if (!tCache) { this._setTcache(); tCache = this.tCache; } Util.each(tCache, function (v, i) { if (t >= v[0] && t <= v[1]) { subt = (t - v[0]) / (v[1] - v[0]); index = i; } }); return { x: LineMath.at(points[index][0], points[index + 1][0], subt), y: LineMath.at(points[index][1], points[index + 1][1], subt) }; } }); module.exports = Polyline; /***/ }), /* 130 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var _require = __webpack_require__(31), parseRadius = _require.parseRadius; var Shape = __webpack_require__(7); var Rect = function Rect(cfg) { Rect.superclass.constructor.call(this, cfg); }; Rect.ATTRS = { x: 0, y: 0, width: 0, height: 0, radius: 0, lineWidth: 1 }; Util.extend(Rect, Shape); Util.augment(Rect, { canFill: true, canStroke: true, type: 'rect', getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1, radius: 0 }; }, calculateBox: function calculateBox() { var self = this; var attrs = self._attrs; var x = attrs.x; var y = attrs.y; var width = attrs.width; var height = attrs.height; var lineWidth = this.getHitLineWidth(); var halfWidth = lineWidth / 2; return { minX: x - halfWidth, minY: y - halfWidth, maxX: x + width + halfWidth, maxY: y + height + halfWidth }; }, createPath: function createPath(context) { var self = this; var attrs = self._attrs; var x = attrs.x; var y = attrs.y; var width = attrs.width; var height = attrs.height; var radius = attrs.radius; context = context || self.get('context'); context.beginPath(); if (radius === 0) { // 改成原生的rect方法 context.rect(x, y, width, height); } else { var r = parseRadius(radius); context.moveTo(x + r.r1, y); context.lineTo(x + width - r.r2, y); r.r2 !== 0 && context.arc(x + width - r.r2, y + r.r2, r.r2, -Math.PI / 2, 0); context.lineTo(x + width, y + height - r.r3); r.r3 !== 0 && context.arc(x + width - r.r3, y + height - r.r3, r.r3, 0, Math.PI / 2); context.lineTo(x + r.r4, y + height); r.r4 !== 0 && context.arc(x + r.r4, y + height - r.r4, r.r4, Math.PI / 2, Math.PI); context.lineTo(x, y + r.r1); r.r1 !== 0 && context.arc(x + r.r1, y + r.r1, r.r1, Math.PI, Math.PI * 1.5); context.closePath(); } } }); module.exports = Rect; /***/ }), /* 131 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Shape = __webpack_require__(7); var CText = function CText(cfg) { CText.superclass.constructor.call(this, cfg); }; CText.ATTRS = { x: 0, y: 0, text: null, fontSize: 12, fontFamily: 'sans-serif', fontStyle: 'normal', fontWeight: 'normal', fontVariant: 'normal', textAlign: 'start', textBaseline: 'bottom', lineHeight: null, textArr: null }; Util.extend(CText, Shape); Util.augment(CText, { canFill: true, canStroke: true, type: 'text', getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1, lineCount: 1, fontSize: 12, fontFamily: 'sans-serif', fontStyle: 'normal', fontWeight: 'normal', fontVariant: 'normal', textAlign: 'start', textBaseline: 'bottom' }; }, initTransform: function initTransform() { var fontSize = this._attrs.fontSize; if (fontSize && +fontSize < 12) { // 小于 12 像素的文本进行 scale 处理 this.transform([['t', -1 * this._attrs.x, -1 * this._attrs.y], ['s', +fontSize / 12, +fontSize / 12], ['t', this._attrs.x, this._attrs.y]]); } }, _assembleFont: function _assembleFont() { // var self = this; var attrs = this._attrs; var fontSize = attrs.fontSize; var fontFamily = attrs.fontFamily; var fontWeight = attrs.fontWeight; var fontStyle = attrs.fontStyle; // self.attr('fontStyle'); var fontVariant = attrs.fontVariant; // self.attr('fontVariant'); // self.attr('font', [fontStyle, fontVariant, fontWeight, fontSize + 'px', fontFamily].join(' ')); attrs.font = [fontStyle, fontVariant, fontWeight, fontSize + 'px', fontFamily].join(' '); }, _setAttrText: function _setAttrText() { var attrs = this._attrs; var text = attrs.text; var textArr = null; if (Util.isString(text)) { if (text.indexOf('\n') !== -1) { textArr = text.split('\n'); var lineCount = textArr.length; attrs.lineCount = lineCount; } else { attrs.lineCount = 1; } } attrs.textArr = textArr; }, _getTextHeight: function _getTextHeight() { var attrs = this._attrs; var lineCount = attrs.lineCount; var fontSize = attrs.fontSize * 1; if (lineCount > 1) { var spaceingY = this._getSpaceingY(); return fontSize * lineCount + spaceingY * (lineCount - 1); } return fontSize; }, isHitBox: function isHitBox() { return false; }, calculateBox: function calculateBox() { var self = this; var attrs = self._attrs; var cfg = this._cfg; if (!cfg.attrs || cfg.hasUpdate) { this._assembleFont(); this._setAttrText(); } if (!attrs.textArr) { this._setAttrText(); } var x = attrs.x; var y = attrs.y; var width = self.measureText(); // attrs.width if (!width) { // 如果width不存在,四点共其实点 return { minX: x, minY: y, maxX: x, maxY: y }; } var height = self._getTextHeight(); // attrs.height var textAlign = attrs.textAlign; var textBaseline = attrs.textBaseline; var lineWidth = self.getHitLineWidth(); var point = { x: x, y: y - height }; if (textAlign) { if (textAlign === 'end' || textAlign === 'right') { point.x -= width; } else if (textAlign === 'center') { point.x -= width / 2; } } if (textBaseline) { if (textBaseline === 'top') { point.y += height; } else if (textBaseline === 'middle') { point.y += height / 2; } } this.set('startPoint', point); var halfWidth = lineWidth / 2; return { minX: point.x - halfWidth, minY: point.y - halfWidth, maxX: point.x + width + halfWidth, maxY: point.y + height + halfWidth }; }, _getSpaceingY: function _getSpaceingY() { var attrs = this._attrs; var lineHeight = attrs.lineHeight; var fontSize = attrs.fontSize * 1; return lineHeight ? lineHeight - fontSize : fontSize * 0.14; }, drawInner: function drawInner(context) { var self = this; var attrs = self._attrs; var cfg = this._cfg; if (!cfg.attrs || cfg.hasUpdate) { this._assembleFont(); this._setAttrText(); } context.font = attrs.font; var text = attrs.text; if (!text) { return; } var textArr = attrs.textArr; var x = attrs.x; var y = attrs.y; context.beginPath(); if (self.hasStroke()) { var strokeOpacity = attrs.strokeOpacity; if (!Util.isNil(strokeOpacity) && strokeOpacity !== 1) { context.globalAlpha = strokeOpacity; } if (textArr) { self._drawTextArr(context, false); } else { context.strokeText(text, x, y); } context.globalAlpha = 1; } if (self.hasFill()) { var fillOpacity = attrs.fillOpacity; if (!Util.isNil(fillOpacity) && fillOpacity !== 1) { context.globalAlpha = fillOpacity; } if (textArr) { self._drawTextArr(context, true); } else { context.fillText(text, x, y); } } cfg.hasUpdate = false; }, _drawTextArr: function _drawTextArr(context, fill) { var textArr = this._attrs.textArr; var textBaseline = this._attrs.textBaseline; var fontSize = this._attrs.fontSize * 1; var spaceingY = this._getSpaceingY(); var x = this._attrs.x; var y = this._attrs.y; var box = this.getBBox(); var height = box.maxY - box.minY; var subY; Util.each(textArr, function (subText, index) { subY = y + index * (spaceingY + fontSize) - height + fontSize; // bottom; if (textBaseline === 'middle') subY += height - fontSize - (height - fontSize) / 2; if (textBaseline === 'top') subY += height - fontSize; if (fill) { context.fillText(subText, x, subY); } else { context.strokeText(subText, x, subY); } }); }, measureText: function measureText() { var self = this; var attrs = self._attrs; var text = attrs.text; var font = attrs.font; var textArr = attrs.textArr; var measureWidth; var width = 0; if (Util.isNil(text)) return undefined; var context = document.createElement('canvas').getContext('2d'); context.save(); context.font = font; if (textArr) { Util.each(textArr, function (subText) { measureWidth = context.measureText(subText).width; if (width < measureWidth) { width = measureWidth; } context.restore(); }); } else { width = context.measureText(text).width; context.restore(); } return width; } }); module.exports = CText; /***/ }), /* 132 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = tpmt; // tpmt is two power minus ten times t scaled to [0,1] function tpmt(x) { return (Math.pow(2, -10 * x) - 0.0009765625) * 1.0009775171065494; } /***/ }), /* 133 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__src_value__ = __webpack_require__(84); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolate", function() { return __WEBPACK_IMPORTED_MODULE_0__src_value__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__src_array__ = __webpack_require__(138); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateArray", function() { return __WEBPACK_IMPORTED_MODULE_1__src_array__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__src_basis__ = __webpack_require__(87); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateBasis", function() { return __WEBPACK_IMPORTED_MODULE_2__src_basis__["b"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__src_basisClosed__ = __webpack_require__(136); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateBasisClosed", function() { return __WEBPACK_IMPORTED_MODULE_3__src_basisClosed__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_4__src_date__ = __webpack_require__(139); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateDate", function() { return __WEBPACK_IMPORTED_MODULE_4__src_date__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__src_number__ = __webpack_require__(47); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateNumber", function() { return __WEBPACK_IMPORTED_MODULE_5__src_number__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__src_object__ = __webpack_require__(140); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateObject", function() { return __WEBPACK_IMPORTED_MODULE_6__src_object__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__src_round__ = __webpack_require__(243); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateRound", function() { return __WEBPACK_IMPORTED_MODULE_7__src_round__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_8__src_string__ = __webpack_require__(141); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateString", function() { return __WEBPACK_IMPORTED_MODULE_8__src_string__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_9__src_transform_index__ = __webpack_require__(244); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateTransformCss", function() { return __WEBPACK_IMPORTED_MODULE_9__src_transform_index__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateTransformSvg", function() { return __WEBPACK_IMPORTED_MODULE_9__src_transform_index__["b"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_10__src_zoom__ = __webpack_require__(247); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateZoom", function() { return __WEBPACK_IMPORTED_MODULE_10__src_zoom__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_11__src_rgb__ = __webpack_require__(135); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateRgb", function() { return __WEBPACK_IMPORTED_MODULE_11__src_rgb__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateRgbBasis", function() { return __WEBPACK_IMPORTED_MODULE_11__src_rgb__["b"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateRgbBasisClosed", function() { return __WEBPACK_IMPORTED_MODULE_11__src_rgb__["c"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_12__src_hsl__ = __webpack_require__(248); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateHsl", function() { return __WEBPACK_IMPORTED_MODULE_12__src_hsl__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateHslLong", function() { return __WEBPACK_IMPORTED_MODULE_12__src_hsl__["b"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_13__src_lab__ = __webpack_require__(249); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateLab", function() { return __WEBPACK_IMPORTED_MODULE_13__src_lab__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_14__src_hcl__ = __webpack_require__(250); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateHcl", function() { return __WEBPACK_IMPORTED_MODULE_14__src_hcl__["a"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateHclLong", function() { return __WEBPACK_IMPORTED_MODULE_14__src_hcl__["b"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_15__src_cubehelix__ = __webpack_require__(251); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateCubehelix", function() { return __WEBPACK_IMPORTED_MODULE_15__src_cubehelix__["b"]; }); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "interpolateCubehelixLong", function() { return __WEBPACK_IMPORTED_MODULE_15__src_cubehelix__["a"]; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_16__src_quantize__ = __webpack_require__(252); /* harmony reexport (binding) */ __webpack_require__.d(__webpack_exports__, "quantize", function() { return __WEBPACK_IMPORTED_MODULE_16__src_quantize__["a"]; }); /***/ }), /* 134 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return deg2rad; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return rad2deg; }); var deg2rad = Math.PI / 180; var rad2deg = 180 / Math.PI; /***/ }), /* 135 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return rgbBasis; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return rgbBasisClosed; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_d3_color__ = __webpack_require__(19); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__basis__ = __webpack_require__(87); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__basisClosed__ = __webpack_require__(136); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_3__color__ = __webpack_require__(32); /* harmony default export */ __webpack_exports__["a"] = ((function rgbGamma(y) { var color = Object(__WEBPACK_IMPORTED_MODULE_3__color__["b" /* gamma */])(y); function rgb(start, end) { var r = color((start = Object(__WEBPACK_IMPORTED_MODULE_0_d3_color__["f" /* rgb */])(start)).r, (end = Object(__WEBPACK_IMPORTED_MODULE_0_d3_color__["f" /* rgb */])(end)).r), g = color(start.g, end.g), b = color(start.b, end.b), opacity = Object(__WEBPACK_IMPORTED_MODULE_3__color__["a" /* default */])(start.opacity, end.opacity); return function (t) { start.r = r(t); start.g = g(t); start.b = b(t); start.opacity = opacity(t); return start + ""; }; } rgb.gamma = rgbGamma; return rgb; })(1)); function rgbSpline(spline) { return function (colors) { var n = colors.length, r = new Array(n), g = new Array(n), b = new Array(n), i, color; for (i = 0; i < n; ++i) { color = Object(__WEBPACK_IMPORTED_MODULE_0_d3_color__["f" /* rgb */])(colors[i]); r[i] = color.r || 0; g[i] = color.g || 0; b[i] = color.b || 0; } r = spline(r); g = spline(g); b = spline(b); color.opacity = 1; return function (t) { color.r = r(t); color.g = g(t); color.b = b(t); return color + ""; }; }; } var rgbBasis = rgbSpline(__WEBPACK_IMPORTED_MODULE_1__basis__["b" /* default */]); var rgbBasisClosed = rgbSpline(__WEBPACK_IMPORTED_MODULE_2__basisClosed__["a" /* default */]); /***/ }), /* 136 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__basis__ = __webpack_require__(87); /* harmony default export */ __webpack_exports__["a"] = (function (values) { var n = values.length; return function (t) { var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n), v0 = values[(i + n - 1) % n], v1 = values[i % n], v2 = values[(i + 1) % n], v3 = values[(i + 2) % n]; return Object(__WEBPACK_IMPORTED_MODULE_0__basis__["a" /* basis */])((t - i / n) * n, v0, v1, v2, v3); }; }); /***/ }), /* 137 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony default export */ __webpack_exports__["a"] = (function (x) { return function () { return x; }; }); /***/ }), /* 138 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__value__ = __webpack_require__(84); /* harmony default export */ __webpack_exports__["a"] = (function (a, b) { var nb = b ? b.length : 0, na = a ? Math.min(nb, a.length) : 0, x = new Array(na), c = new Array(nb), i; for (i = 0; i < na; ++i) x[i] = Object(__WEBPACK_IMPORTED_MODULE_0__value__["a" /* default */])(a[i], b[i]); for (; i < nb; ++i) c[i] = b[i]; return function (t) { for (i = 0; i < na; ++i) c[i] = x[i](t); return c; }; }); /***/ }), /* 139 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony default export */ __webpack_exports__["a"] = (function (a, b) { var d = new Date(); return a = +a, b -= a, function (t) { return d.setTime(a + b * t), d; }; }); /***/ }), /* 140 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__value__ = __webpack_require__(84); /* harmony default export */ __webpack_exports__["a"] = (function (a, b) { var i = {}, c = {}, k; if (a === null || typeof a !== "object") a = {}; if (b === null || typeof b !== "object") b = {}; for (k in b) { if (k in a) { i[k] = Object(__WEBPACK_IMPORTED_MODULE_0__value__["a" /* default */])(a[k], b[k]); } else { c[k] = b[k]; } } return function (t) { for (k in i) c[k] = i[k](t); return c; }; }); /***/ }), /* 141 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__number__ = __webpack_require__(47); var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, reB = new RegExp(reA.source, "g"); function zero(b) { return function () { return b; }; } function one(b) { return function (t) { return b(t) + ""; }; } /* harmony default export */ __webpack_exports__["a"] = (function (a, b) { var bi = reA.lastIndex = reB.lastIndex = 0, // scan index for next number in b am, // current match in a bm, // current match in b bs, // string preceding current number in b, if any i = -1, // index in s s = [], // string constants and placeholders q = []; // number interpolators // Coerce inputs to strings. a = a + "", b = b + ""; // Interpolate pairs of numbers in a & b. while ((am = reA.exec(a)) && (bm = reB.exec(b))) { if ((bs = bm.index) > bi) { // a string precedes the next number in b bs = b.slice(bi, bs); if (s[i]) s[i] += bs; // coalesce with previous string else s[++i] = bs; } if ((am = am[0]) === (bm = bm[0])) { // numbers in a & b match if (s[i]) s[i] += bm; // coalesce with previous string else s[++i] = bm; } else { // interpolate non-matching numbers s[++i] = null; q.push({ i: i, x: Object(__WEBPACK_IMPORTED_MODULE_0__number__["a" /* default */])(am, bm) }); } bi = reB.lastIndex; } // Add remains of b. if (bi < b.length) { bs = b.slice(bi); if (s[i]) s[i] += bs; // coalesce with previous string else s[++i] = bs; } // Special optimization for only a single match. // Otherwise, interpolate each of the numbers and rejoin the string. return s.length < 2 ? q[0] ? one(q[0].x) : zero(b) : (b = q.length, function (t) { for (var i = 0, o; i < b; ++i) s[(o = q[i]).i] = o.x(t); return s.join(""); }); }); /***/ }), /* 142 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview Default animation configuration for geoms * @author sima.zhang */ var Util = __webpack_require__(0); var Action = __webpack_require__(328); var defaultAnimationCfg = { appear: { duration: 450, easing: 'easeQuadOut' }, // 初始入场动画配置 update: { duration: 450, easing: 'easeQuadInOut' }, // 更新时发生变更的动画配置 enter: { duration: 400, easing: 'easeQuadInOut', delay: 100 }, // 更新时新增元素的入场动画配置 leave: { duration: 350, easing: 'easeQuadIn' } // 更新时销毁动画配置 }; var Animate = { line: { appear: function appear() { return Action.appear.clipIn; }, enter: function enter() { return Action.enter.clipIn; }, leave: function leave() { return Action.leave.lineWidthOut; } }, path: { appear: function appear() { return Action.appear.clipIn; }, enter: function enter() { return Action.enter.clipIn; }, leave: function leave() { return Action.leave.lineWidthOut; } }, area: { appear: function appear() { return Action.appear.clipIn; }, enter: function enter() { return Action.enter.fadeIn; }, leave: function leave() { return Action.leave.fadeOut; }, cfg: { appear: { duration: 500, easing: 'easeQuadOut' }, update: { duration: 450, easing: 'easeQuadInOut' }, enter: { duration: 600, delay: 150, easing: 'easeQuadInOut' }, leave: { easing: 'easeQuadOut', duration: 350 } } }, polygon: { appear: function appear() { return Action.appear.zoomIn; }, enter: function enter() { return Action.enter.zoomIn; }, leave: function leave() { return Action.leave.zoomOut; } }, edge: { appear: function appear() { return Action.appear.pathIn; }, enter: function enter() { return Action.enter.pathIn; }, leave: function leave() { return Action.leave.pathOut; } }, interval: { appear: function appear(coord) { var result; if (coord.isPolar) { result = Action.appear.zoomIn; if (coord.isTransposed || coord.type === 'theta') { result = Action.appear.fanIn; } } else if (coord.isRect) { result = coord.isTransposed ? Action.appear.scaleInX : Action.appear.scaleInY; } else { result = Action.appear.zoomIn; } return result; }, enter: function enter(coord) { if (coord.isRect || coord.isTransposed || coord.type === 'theta') { return Action.enter.fadeIn; } return Action.enter.zoomIn; }, leave: function leave() { return Action.leave.fadeOut; }, update: function update(coord) { if (coord.type === 'theta') { return Action.update.fanIn; } } }, point: { appear: function appear() { return Action.appear.zoomIn; }, enter: function enter() { return Action.enter.zoomIn; }, leave: function leave() { return Action.leave.zoomOut; } }, schema: { appear: function appear() { return Action.appear.clipIn; }, enter: function enter() { return Action.enter.clipIn; }, leave: function leave() { return Action.leave.lineWidthOut; } }, contour: null, heatmap: null, label: { appear: function appear() { return Action.appear.fadeIn; }, enter: function enter() { return Action.enter.fadeIn; }, leave: function leave() { return Action.leave.fadeOut; }, cfg: { appear: { duration: 900 } } }, 'axis-label': { enter: function enter() { return Action.appear.fadeIn; }, leave: function leave() { return Action.leave.fadeOut; }, update: function update(coord) { if (coord.isPolar) { return Action.appear.fadeIn; } } }, 'axis-ticks': { enter: function enter() { return Action.appear.fadeIn; }, leave: function leave() { return Action.leave.fadeOut; }, update: function update(coord) { if (coord.isPolar) { return Action.appear.fadeIn; } } }, 'axis-grid': { enter: function enter() { return Action.appear.fadeIn; }, leave: function leave() { return Action.leave.fadeOut; }, update: function update(coord) { if (coord.isPolar) { return Action.appear.fadeIn; } } }, 'axis-grid-rect': { enter: function enter() { return Action.appear.fadeIn; }, leave: function leave() { return Action.leave.fadeOut; }, update: function update() { return Action.leave.fadeIn; } }, labelLine: { appear: function appear() { return Action.appear.pathIn; }, enter: function enter() { return Action.enter.pathIn; }, leave: function leave() { return Action.leave.pathOut; } } }; Animate.Action = Action; Animate.defaultCfg = defaultAnimationCfg; // 获取动画 Animate.getAnimation = function (geomType, coord, animationType) { var geomAnimateCfg = this[geomType]; if (geomAnimateCfg) { var animation = geomAnimateCfg[animationType]; if (Util.isFunction(animation)) { return animation(coord); } } return false; }; // 获取动画配置 Animate.getAnimateCfg = function (geomType, animationType) { var defaultCfg = defaultAnimationCfg[animationType]; if (this[geomType] && this[geomType].cfg && this[geomType].cfg[animationType]) { return Util.deepMix({}, defaultCfg, this[geomType].cfg[animationType]); } return defaultCfg; }; // 注册动画 Animate.registerAnimation = function (animationType, animationName, animationFun) { if (!this.Action[animationType]) { this.Action[animationType] = {}; } this.Action[animationType][animationName] = animationFun; }; module.exports = Animate; /***/ }), /* 143 */ /***/ (function(module, exports, __webpack_require__) { var each = __webpack_require__(3); var mix = __webpack_require__(10); // collections var DOMUtil = __webpack_require__(266); var arrayUtil = __webpack_require__(275); var eventUtil = __webpack_require__(286); var formatUtil = __webpack_require__(289); var mathUtil = __webpack_require__(293); var matrixUtil = __webpack_require__(50); var objectUtil = __webpack_require__(302); var pathUtil = __webpack_require__(306); var stringUtil = __webpack_require__(312); var typeUtil = __webpack_require__(316); var util = { // collections DOMUtil: DOMUtil, DomUtil: DOMUtil, MatrixUtil: matrixUtil, PathUtil: pathUtil, arrayUtil: arrayUtil, domUtil: DOMUtil, eventUtil: eventUtil, formatUtil: formatUtil, mathUtil: mathUtil, matrixUtil: matrixUtil, objectUtil: objectUtil, stringUtil: stringUtil, pathUtil: pathUtil, typeUtil: typeUtil, // others augment: __webpack_require__(66), clone: __webpack_require__(39), debounce: __webpack_require__(322), deepMix: __webpack_require__(27), each: each, extend: __webpack_require__(65), filter: __webpack_require__(88), group: __webpack_require__(160), groupBy: __webpack_require__(162), groupToMap: __webpack_require__(161), indexOf: __webpack_require__(323), isEmpty: __webpack_require__(61), isEqual: __webpack_require__(40), isEqualWith: __webpack_require__(324), map: __webpack_require__(325), mix: mix, pick: __webpack_require__(326), throttle: __webpack_require__(327), toArray: __webpack_require__(29), toString: __webpack_require__(26), uniqueId: __webpack_require__(62) }; each([DOMUtil, arrayUtil, eventUtil, formatUtil, mathUtil, matrixUtil, objectUtil, pathUtil, stringUtil, typeUtil], function (collection) { mix(util, collection); }); module.exports = util; /***/ }), /* 144 */ /***/ (function(module, exports, __webpack_require__) { var keys = __webpack_require__(145); var isNil = __webpack_require__(6); function isMatch(obj, attrs) { var _keys = keys(attrs); var length = _keys.length; if (isNil(obj)) return !length; for (var i = 0; i < length; i += 1) { var key = _keys[i]; if (attrs[key] !== obj[key] || !(key in obj)) { return false; } } return true; } module.exports = isMatch; /***/ }), /* 145 */ /***/ (function(module, exports, __webpack_require__) { var each = __webpack_require__(3); var isFunction = __webpack_require__(13); var keys = Object.keys ? function (obj) { return Object.keys(obj); } : function (obj) { var result = []; each(obj, function (value, key) { if (!(isFunction(obj) && key === 'prototype')) { result.push(key); } }); return result; }; module.exports = keys; /***/ }), /* 146 */ /***/ (function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(15); var splice = Array.prototype.splice; var pullAt = function pullAt(arr, indexes) { if (!isArrayLike(arr)) { return []; } var length = arr ? indexes.length : 0; var last = length - 1; while (length--) { var previous = void 0; var index = indexes[length]; if (length === last || index !== previous) { previous = index; splice.call(arr, index, 1); } } return arr; }; module.exports = pullAt; /***/ }), /* 147 */ /***/ (function(module, exports, __webpack_require__) { var each = __webpack_require__(3); var contains = __webpack_require__(48); var uniq = function uniq(arr) { var resultArr = []; each(arr, function (item) { if (!contains(resultArr, item)) { resultArr.push(item); } }); return resultArr; }; module.exports = uniq; /***/ }), /* 148 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(5); var isFunction = __webpack_require__(13); var each = __webpack_require__(3); /** * @param {Array} arr The array to iterate over. * @param {Function} [fn] The iteratee invoked per element. * @return {*} Returns the maximum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * maxBy(objects, function(o) { return o.n; }); * // => { 'n': 2 } * * maxBy(objects, 'n'); * // => { 'n': 2 } */ var maxBy = function maxBy(arr, fn) { if (!isArray(arr)) { return undefined; } var max = arr[0]; var maxData = void 0; if (isFunction(fn)) { maxData = fn(arr[0]); } else { maxData = arr[0][fn]; } var data = void 0; each(arr, function (val) { if (isFunction(fn)) { data = fn(val); } else { data = val[fn]; } if (data > maxData) { max = val; maxData = data; } }); return max; }; module.exports = maxBy; /***/ }), /* 149 */ /***/ (function(module, exports) { module.exports = parseInt; /***/ }), /* 150 */ /***/ (function(module, exports) { module.exports = function (obj, key) { return obj.hasOwnProperty(key); }; /***/ }), /* 151 */ /***/ (function(module, exports, __webpack_require__) { var each = __webpack_require__(3); var isFunction = __webpack_require__(13); var values = Object.values ? function (obj) { return Object.values(obj); } : function (obj) { var result = []; each(obj, function (value, key) { if (!(isFunction(obj) && key === 'prototype')) { result.push(value); } }); return result; }; module.exports = values; /***/ }), /* 152 */ /***/ (function(module, exports, __webpack_require__) { var parsePathArray = __webpack_require__(153); module.exports = function rectPath(x, y, w, h, r) { if (r) { return [['M', +x + +r, y], ['l', w - r * 2, 0], ['a', r, r, 0, 0, 1, r, r], ['l', 0, h - r * 2], ['a', r, r, 0, 0, 1, -r, r], ['l', r * 2 - w, 0], ['a', r, r, 0, 0, 1, -r, -r], ['l', 0, r * 2 - h], ['a', r, r, 0, 0, 1, r, -r], ['z']]; } var res = [['M', x, y], ['l', w, 0], ['l', 0, h], ['l', -w, 0], ['z']]; res.parsePathArray = parsePathArray; return res; }; /***/ }), /* 153 */ /***/ (function(module, exports) { var p2s = /,?([a-z]),?/gi; module.exports = function parsePathArray(path) { return path.join(',').replace(p2s, '$1'); }; /***/ }), /* 154 */ /***/ (function(module, exports, __webpack_require__) { var pathToAbsolute = __webpack_require__(155); var a2c = function a2c(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { // for more information of where this math came from visit: // http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes if (rx === ry) { rx += 1; } var _120 = Math.PI * 120 / 180; var rad = Math.PI / 180 * (+angle || 0); var res = []; var xy = void 0; var f1 = void 0; var f2 = void 0; var cx = void 0; var cy = void 0; var rotate = function rotate(x, y, rad) { var X = x * Math.cos(rad) - y * Math.sin(rad); var Y = x * Math.sin(rad) + y * Math.cos(rad); return { x: X, y: Y }; }; if (!recursive) { xy = rotate(x1, y1, -rad); x1 = xy.x; y1 = xy.y; xy = rotate(x2, y2, -rad); x2 = xy.x; y2 = xy.y; if (x1 === x2 && y1 === y2) { // 若弧的起始点和终点重叠则错开一点 x2 += 1; y2 += 1; } // const cos = Math.cos(Math.PI / 180 * angle); // const sin = Math.sin(Math.PI / 180 * angle); var x = (x1 - x2) / 2; var y = (y1 - y2) / 2; var h = x * x / (rx * rx) + y * y / (ry * ry); if (h > 1) { h = Math.sqrt(h); rx = h * rx; ry = h * ry; } var rx2 = rx * rx; var ry2 = ry * ry; var k = (large_arc_flag === sweep_flag ? -1 : 1) * Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))); cx = k * rx * y / ry + (x1 + x2) / 2; cy = k * -ry * x / rx + (y1 + y2) / 2; f1 = Math.asin(((y1 - cy) / ry).toFixed(9)); f2 = Math.asin(((y2 - cy) / ry).toFixed(9)); f1 = x1 < cx ? Math.PI - f1 : f1; f2 = x2 < cx ? Math.PI - f2 : f2; f1 < 0 && (f1 = Math.PI * 2 + f1); f2 < 0 && (f2 = Math.PI * 2 + f2); if (sweep_flag && f1 > f2) { f1 = f1 - Math.PI * 2; } if (!sweep_flag && f2 > f1) { f2 = f2 - Math.PI * 2; } } else { f1 = recursive[0]; f2 = recursive[1]; cx = recursive[2]; cy = recursive[3]; } var df = f2 - f1; if (Math.abs(df) > _120) { var f2old = f2; var x2old = x2; var y2old = y2; f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1); x2 = cx + rx * Math.cos(f2); y2 = cy + ry * Math.sin(f2); res = a2c(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]); } df = f2 - f1; var c1 = Math.cos(f1); var s1 = Math.sin(f1); var c2 = Math.cos(f2); var s2 = Math.sin(f2); var t = Math.tan(df / 4); var hx = 4 / 3 * rx * t; var hy = 4 / 3 * ry * t; var m1 = [x1, y1]; var m2 = [x1 + hx * s1, y1 - hy * c1]; var m3 = [x2 + hx * s2, y2 - hy * c2]; var m4 = [x2, y2]; m2[0] = 2 * m1[0] - m2[0]; m2[1] = 2 * m1[1] - m2[1]; if (recursive) { return [m2, m3, m4].concat(res); } res = [m2, m3, m4].concat(res).join().split(','); var newres = []; for (var i = 0, ii = res.length; i < ii; i++) { newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; } return newres; }; var l2c = function l2c(x1, y1, x2, y2) { return [x1, y1, x2, y2, x2, y2]; }; var q2c = function q2c(x1, y1, ax, ay, x2, y2) { var _13 = 1 / 3; var _23 = 2 / 3; return [_13 * x1 + _23 * ax, _13 * y1 + _23 * ay, _13 * x2 + _23 * ax, _13 * y2 + _23 * ay, x2, y2]; }; module.exports = function pathTocurve(path, path2) { var p = pathToAbsolute(path); var p2 = path2 && pathToAbsolute(path2); var attrs = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }; var attrs2 = { x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null }; var pcoms1 = []; // path commands of original path p var pcoms2 = []; // path commands of original path p2 var pfirst = ''; // temporary holder for original path command var pcom = ''; // holder for previous path command of original path var ii = void 0; var processPath = function processPath(path, d, pcom) { var nx = void 0, ny = void 0; if (!path) { return ['C', d.x, d.y, d.x, d.y, d.x, d.y]; } !(path[0] in { T: 1, Q: 1 }) && (d.qx = d.qy = null); switch (path[0]) { case 'M': d.X = path[1]; d.Y = path[2]; break; case 'A': path = ['C'].concat(a2c.apply(0, [d.x, d.y].concat(path.slice(1)))); break; case 'S': if (pcom === 'C' || pcom === 'S') { // In "S" case we have to take into account, if the previous command is C/S. nx = d.x * 2 - d.bx; // And reflect the previous ny = d.y * 2 - d.by; // command's control point relative to the current point. } else { // or some else or nothing nx = d.x; ny = d.y; } path = ['C', nx, ny].concat(path.slice(1)); break; case 'T': if (pcom === 'Q' || pcom === 'T') { // In "T" case we have to take into account, if the previous command is Q/T. d.qx = d.x * 2 - d.qx; // And make a reflection similar d.qy = d.y * 2 - d.qy; // to case "S". } else { // or something else or nothing d.qx = d.x; d.qy = d.y; } path = ['C'].concat(q2c(d.x, d.y, d.qx, d.qy, path[1], path[2])); break; case 'Q': d.qx = path[1]; d.qy = path[2]; path = ['C'].concat(q2c(d.x, d.y, path[1], path[2], path[3], path[4])); break; case 'L': path = ['C'].concat(l2c(d.x, d.y, path[1], path[2])); break; case 'H': path = ['C'].concat(l2c(d.x, d.y, path[1], d.y)); break; case 'V': path = ['C'].concat(l2c(d.x, d.y, d.x, path[1])); break; case 'Z': path = ['C'].concat(l2c(d.x, d.y, d.X, d.Y)); break; default: break; } return path; }; var fixArc = function fixArc(pp, i) { if (pp[i].length > 7) { pp[i].shift(); var pi = pp[i]; while (pi.length) { pcoms1[i] = 'A'; // if created multiple C:s, their original seg is saved p2 && (pcoms2[i] = 'A'); // the same as above pp.splice(i++, 0, ['C'].concat(pi.splice(0, 6))); } pp.splice(i, 1); ii = Math.max(p.length, p2 && p2.length || 0); } }; var fixM = function fixM(path1, path2, a1, a2, i) { if (path1 && path2 && path1[i][0] === 'M' && path2[i][0] !== 'M') { path2.splice(i, 0, ['M', a2.x, a2.y]); a1.bx = 0; a1.by = 0; a1.x = path1[i][1]; a1.y = path1[i][2]; ii = Math.max(p.length, p2 && p2.length || 0); } }; ii = Math.max(p.length, p2 && p2.length || 0); for (var i = 0; i < ii; i++) { p[i] && (pfirst = p[i][0]); // save current path command if (pfirst !== 'C') { // C is not saved yet, because it may be result of conversion pcoms1[i] = pfirst; // Save current path command i && (pcom = pcoms1[i - 1]); // Get previous path command pcom } p[i] = processPath(p[i], attrs, pcom); // Previous path command is inputted to processPath if (pcoms1[i] !== 'A' && pfirst === 'C') pcoms1[i] = 'C'; // A is the only command // which may produce multiple C:s // so we have to make sure that C is also C in original path fixArc(p, i); // fixArc adds also the right amount of A:s to pcoms1 if (p2) { // the same procedures is done to p2 p2[i] && (pfirst = p2[i][0]); if (pfirst !== 'C') { pcoms2[i] = pfirst; i && (pcom = pcoms2[i - 1]); } p2[i] = processPath(p2[i], attrs2, pcom); if (pcoms2[i] !== 'A' && pfirst === 'C') { pcoms2[i] = 'C'; } fixArc(p2, i); } fixM(p, p2, attrs, attrs2, i); fixM(p2, p, attrs2, attrs, i); var seg = p[i]; var seg2 = p2 && p2[i]; var seglen = seg.length; var seg2len = p2 && seg2.length; attrs.x = seg[seglen - 2]; attrs.y = seg[seglen - 1]; attrs.bx = parseFloat(seg[seglen - 4]) || attrs.x; attrs.by = parseFloat(seg[seglen - 3]) || attrs.y; attrs2.bx = p2 && (parseFloat(seg2[seg2len - 4]) || attrs2.x); attrs2.by = p2 && (parseFloat(seg2[seg2len - 3]) || attrs2.y); attrs2.x = p2 && seg2[seg2len - 2]; attrs2.y = p2 && seg2[seg2len - 1]; } return p2 ? [p, p2] : p; }; /***/ }), /* 155 */ /***/ (function(module, exports, __webpack_require__) { var parsePathString = __webpack_require__(156); var catmullRom2bezier = __webpack_require__(157); function ellipsePath(x, y, rx, ry, a) { var res = []; if (a === null && ry === null) { ry = rx; } x = +x; y = +y; rx = +rx; ry = +ry; if (a !== null) { var rad = Math.PI / 180; var x1 = x + rx * Math.cos(-ry * rad); var x2 = x + rx * Math.cos(-a * rad); var y1 = y + rx * Math.sin(-ry * rad); var y2 = y + rx * Math.sin(-a * rad); res = [['M', x1, y1], ['A', rx, rx, 0, +(a - ry > 180), 0, x2, y2]]; } else { res = [['M', x, y], ['m', 0, -ry], ['a', rx, ry, 0, 1, 1, 0, 2 * ry], ['a', rx, ry, 0, 1, 1, 0, -2 * ry], ['z']]; } return res; } module.exports = function pathToAbsolute(pathArray) { pathArray = parsePathString(pathArray); if (!pathArray || !pathArray.length) { return [['M', 0, 0]]; } var res = []; var x = 0; var y = 0; var mx = 0; var my = 0; var start = 0; var pa0 = void 0; var dots = void 0; if (pathArray[0][0] === 'M') { x = +pathArray[0][1]; y = +pathArray[0][2]; mx = x; my = y; start++; res[0] = ['M', x, y]; } var crz = pathArray.length === 3 && pathArray[0][0] === 'M' && pathArray[1][0].toUpperCase() === 'R' && pathArray[2][0].toUpperCase() === 'Z'; for (var r, pa, i = start, ii = pathArray.length; i < ii; i++) { res.push(r = []); pa = pathArray[i]; pa0 = pa[0]; if (pa0 !== pa0.toUpperCase()) { r[0] = pa0.toUpperCase(); switch (r[0]) { case 'A': r[1] = pa[1]; r[2] = pa[2]; r[3] = pa[3]; r[4] = pa[4]; r[5] = pa[5]; r[6] = +pa[6] + x; r[7] = +pa[7] + y; break; case 'V': r[1] = +pa[1] + y; break; case 'H': r[1] = +pa[1] + x; break; case 'R': dots = [x, y].concat(pa.slice(1)); for (var j = 2, jj = dots.length; j < jj; j++) { dots[j] = +dots[j] + x; dots[++j] = +dots[j] + y; } res.pop(); res = res.concat(catmullRom2bezier(dots, crz)); break; case 'O': res.pop(); dots = ellipsePath(x, y, pa[1], pa[2]); dots.push(dots[0]); res = res.concat(dots); break; case 'U': res.pop(); res = res.concat(ellipsePath(x, y, pa[1], pa[2], pa[3])); r = ['U'].concat(res[res.length - 1].slice(-2)); break; case 'M': mx = +pa[1] + x; my = +pa[2] + y; break; // for lint default: for (var _j = 1, _jj = pa.length; _j < _jj; _j++) { r[_j] = +pa[_j] + (_j % 2 ? x : y); } } } else if (pa0 === 'R') { dots = [x, y].concat(pa.slice(1)); res.pop(); res = res.concat(catmullRom2bezier(dots, crz)); r = ['R'].concat(pa.slice(-2)); } else if (pa0 === 'O') { res.pop(); dots = ellipsePath(x, y, pa[1], pa[2]); dots.push(dots[0]); res = res.concat(dots); } else if (pa0 === 'U') { res.pop(); res = res.concat(ellipsePath(x, y, pa[1], pa[2], pa[3])); r = ['U'].concat(res[res.length - 1].slice(-2)); } else { for (var k = 0, kk = pa.length; k < kk; k++) { r[k] = pa[k]; } } pa0 = pa0.toUpperCase(); if (pa0 !== 'O') { switch (r[0]) { case 'Z': x = +mx; y = +my; break; case 'H': x = r[1]; break; case 'V': y = r[1]; break; case 'M': mx = r[r.length - 2]; my = r[r.length - 1]; break; // for lint default: x = r[r.length - 2]; y = r[r.length - 1]; } } } return res; }; /***/ }), /* 156 */ /***/ (function(module, exports) { var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; var SPACES = '\t\n\x0B\f\r \xA0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028\u2029'; var PATH_COMMAND = new RegExp('([a-z])[' + SPACES + ',]*((-?\\d*\\.?\\d*(?:e[\\-+]?\\d+)?[' + SPACES + ']*,?[' + SPACES + ']*)+)', 'ig'); var PATH_VALUES = new RegExp('(-?\\d*\\.?\\d*(?:e[\\-+]?\\d+)?)[' + SPACES + ']*,?[' + SPACES + ']*', 'ig'); // Parses given path string into an array of arrays of path segments module.exports = function parsePathString(pathString) { if (!pathString) { return null; } if ((typeof pathString === 'undefined' ? 'undefined' : _typeof(pathString)) === _typeof([])) { return pathString; } var paramCounts = { a: 7, c: 6, o: 2, h: 1, l: 2, m: 2, r: 4, q: 4, s: 4, t: 2, v: 1, u: 3, z: 0 }; var data = []; String(pathString).replace(PATH_COMMAND, function (a, b, c) { var params = []; var name = b.toLowerCase(); c.replace(PATH_VALUES, function (a, b) { b && params.push(+b); }); if (name === 'm' && params.length > 2) { data.push([b].concat(params.splice(0, 2))); name = 'l'; b = b === 'm' ? 'l' : 'L'; } if (name === 'o' && params.length === 1) { data.push([b, params[0]]); } if (name === 'r') { data.push([b].concat(params)); } else { while (params.length >= paramCounts[name]) { data.push([b].concat(params.splice(0, paramCounts[name]))); if (!paramCounts[name]) { break; } } } }); return data; }; /***/ }), /* 157 */ /***/ (function(module, exports) { // http://schepers.cc/getting-to-the-point module.exports = function catmullRom2bezier(crp, z) { var d = []; for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { var p = [{ x: +crp[i - 2], y: +crp[i - 1] }, { x: +crp[i], y: +crp[i + 1] }, { x: +crp[i + 2], y: +crp[i + 3] }, { x: +crp[i + 4], y: +crp[i + 5] }]; if (z) { if (!i) { p[0] = { x: +crp[iLen - 2], y: +crp[iLen - 1] }; } else if (iLen - 4 === i) { p[3] = { x: +crp[0], y: +crp[1] }; } else if (iLen - 2 === i) { p[2] = { x: +crp[0], y: +crp[1] }; p[3] = { x: +crp[2], y: +crp[3] }; } } else { if (iLen - 4 === i) { p[3] = p[2]; } else if (!i) { p[0] = { x: +crp[i], y: +crp[i + 1] }; } } d.push(['C', (-p[0].x + 6 * p[1].x + p[2].x) / 6, (-p[0].y + 6 * p[1].y + p[2].y) / 6, (p[1].x + 6 * p[2].x - p[3].x) / 6, (p[1].y + 6 * p[2].y - p[3].y) / 6, p[2].x, p[2].y]); } return d; }; /***/ }), /* 158 */ /***/ (function(module, exports, __webpack_require__) { var toString = __webpack_require__(26); var lowerCase = function lowerCase(str) { return toString(str).toLowerCase(); }; module.exports = lowerCase; /***/ }), /* 159 */ /***/ (function(module, exports, __webpack_require__) { var toString = __webpack_require__(26); var upperCase = function upperCase(str) { return toString(str).toUpperCase(); }; module.exports = upperCase; /***/ }), /* 160 */ /***/ (function(module, exports, __webpack_require__) { var groupToMap = __webpack_require__(161); var group = function group(data, condition) { if (!condition) { return [data]; } var groups = groupToMap(data, condition); var array = []; for (var i in groups) { array.push(groups[i]); } return array; }; module.exports = group; /***/ }), /* 161 */ /***/ (function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(13); var isArray = __webpack_require__(5); var groupBy = __webpack_require__(162); var groupToMap = function groupToMap(data, condition) { if (!condition) { return { 0: data }; } if (!isFunction(condition)) { var paramsCondition = isArray(condition) ? condition : condition.replace(/\s+/g, '').split('*'); condition = function condition(row) { var unique = '_'; // 避免出现数字作为Key的情况,会进行按照数字的排序 for (var i = 0, l = paramsCondition.length; i < l; i++) { unique += row[paramsCondition[i]] && row[paramsCondition[i]].toString(); } return unique; }; } var groups = groupBy(data, condition); return groups; }; module.exports = groupToMap; /***/ }), /* 162 */ /***/ (function(module, exports, __webpack_require__) { var each = __webpack_require__(3); var isArray = __webpack_require__(5); var hasOwnProperty = Object.prototype.hasOwnProperty; var groupBy = function groupBy(data, condition) { if (!condition || !isArray(data)) { return data; } var result = {}; var key = null; each(data, function (item) { key = condition(item); if (hasOwnProperty.call(result, key)) { result[key].push(item); } else { result[key] = [item]; } }); return result; }; module.exports = groupBy; /***/ }), /* 163 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @fileOverview G2 图表的入口文件 * @author dxq613@gmail.com */ var Util = __webpack_require__(0); var View = __webpack_require__(329); var G = __webpack_require__(18); var Canvas = G.Canvas; var DomUtil = Util.DomUtil; var Global = __webpack_require__(8); var Plot = __webpack_require__(414); var Controller = __webpack_require__(200); var mergeBBox = __webpack_require__(202); var bboxOfBackPlot = __webpack_require__(201); var plotRange2BBox = __webpack_require__(203); var AUTO_STR = 'auto'; function _isScaleExist(scales, compareScale) { var flag = false; Util.each(scales, function (scale) { var scaleValues = [].concat(scale.values); var compareScaleValues = [].concat(compareScale.values); if (scale.type === compareScale.type && scale.field === compareScale.field && scaleValues.sort().toString() === compareScaleValues.sort().toString()) { flag = true; return; } }); return flag; } function isEqualArray(arr1, arr2) { return Util.isEqualWith(arr1, arr2, function (v1, v2) { return v1 === v2; }); } /** * 图表的入口 * @class Chart */ var Chart = /*#__PURE__*/function (_View) { _inheritsLoose(Chart, _View); function Chart() { return _View.apply(this, arguments) || this; } var _proto = Chart.prototype; /** * 获取默认的配置属性 * @protected * @return {Object} 默认属性 */ _proto.getDefaultCfg = function getDefaultCfg() { var viewCfg = _View.prototype.getDefaultCfg.call(this); return Util.mix(viewCfg, { id: null, forceFit: false, container: null, wrapperEl: null, canvas: null, width: 500, height: 500, pixelRatio: null, backPlot: null, frontPlot: null, plotBackground: null, padding: Global.plotCfg.padding, background: null, autoPaddingAppend: 5, limitInPlot: false, renderer: Global.renderer, // renderer: 'svg', views: [] }); }; _proto.init = function init() { var self = this; var viewTheme = self.get('viewTheme'); self._initCanvas(); self._initPlot(); self._initEvents(); _View.prototype.init.call(this); var tooltipController = new Controller.Tooltip({ chart: self, viewTheme: viewTheme, options: {} }); self.set('tooltipController', tooltipController); var legendController = new Controller.Legend({ chart: self, viewTheme: viewTheme }); self.set('legendController', legendController); self.set('_id', 'chart'); // 防止同用户设定的 id 同名 self.emit('afterinit'); // 初始化完毕 }; _proto._isAutoPadding = function _isAutoPadding() { var padding = this.get('padding'); if (Util.isArray(padding)) { return padding.includes(AUTO_STR); } return padding === AUTO_STR; }; _proto._getAutoPadding = function _getAutoPadding() { var padding = this.get('padding'); // 图例在最前面的一层 var frontPlot = this.get('frontPlot'); var frontBBox = frontPlot.getBBox(); // 坐标轴在最后面的一层 var backPlot = this.get('backPlot'); // 这段代码临时处理了title 过长的情况,但是是非常不好的代码 var backBBox = bboxOfBackPlot(backPlot, plotRange2BBox(this.get('plotRange'))); var box = mergeBBox(frontBBox, backBBox); var outter = [0 - box.minY, // 上面超出的部分 box.maxX - this.get('width'), // 右边超出的部分 box.maxY - this.get('height'), // 下边超出的部分 0 - box.minX]; // 如果原始的 padding 内部存在 'auto' 则替换对应的边 var autoPadding = Util.toAllPadding(padding); for (var i = 0; i < autoPadding.length; i++) { if (autoPadding[i] === AUTO_STR) { var tmp = Math.max(0, outter[i]); autoPadding[i] = tmp + this.get('autoPaddingAppend'); } } return autoPadding; } // 初始化画布 ; _proto._initCanvas = function _initCanvas() { var container = this.get('container'); var id = this.get('id'); // 如果未设置 container 使用 ID, 兼容 2.x 版本 if (!container && id) { container = id; this.set('container', id); } var width = this.get('width'); var height = this.get('height'); if (Util.isString(container)) { container = document.getElementById(container); if (!container) { throw new Error('Please specify the container for the chart!'); } this.set('container', container); } var wrapperEl = DomUtil.createDom('
'); container.appendChild(wrapperEl); this.set('wrapperEl', wrapperEl); if (this.get('forceFit')) { width = DomUtil.getWidth(container, width); this.set('width', width); } var renderer = this.get('renderer'); var canvas = new Canvas({ containerDOM: wrapperEl, width: width, height: height, // NOTICE: 有问题找青湳 pixelRatio: renderer === 'svg' ? 1 : this.get('pixelRatio'), renderer: renderer }); this.set('canvas', canvas); } // 初始化绘图区间 ; _proto._initPlot = function _initPlot() { var self = this; self._initPlotBack(); // 最底层的是背景相关的 group var canvas = self.get('canvas'); var backPlot = canvas.addGroup({ zIndex: 1 }); // 图表最后面的容器 var plotContainer = canvas.addGroup({ zIndex: 0 }); // 图表所在的容器 var frontPlot = canvas.addGroup({ zIndex: 3 }); // 图表前面的容器 self.set('backPlot', backPlot); self.set('middlePlot', plotContainer); self.set('frontPlot', frontPlot); } // 初始化背景 ; _proto._initPlotBack = function _initPlotBack() { var self = this; var canvas = self.get('canvas'); var viewTheme = self.get('viewTheme'); var plot = canvas.addGroup(Plot, { padding: this.get('padding'), plotBackground: Util.mix({}, viewTheme.plotBackground, self.get('plotBackground')), background: Util.mix({}, viewTheme.background, self.get('background')) }); self.set('plot', plot); self.set('plotRange', plot.get('plotRange')); }; _proto._initEvents = function _initEvents() { if (this.get('forceFit')) { window.addEventListener('resize', Util.wrapBehavior(this, '_initForceFitEvent')); } }; _proto._initForceFitEvent = function _initForceFitEvent() { var timer = setTimeout(Util.wrapBehavior(this, 'forceFit'), 200); clearTimeout(this.get('resizeTimer')); this.set('resizeTimer', timer); } // 绘制图例 ; _proto._renderLegends = function _renderLegends() { var options = this.get('options'); var legendOptions = options.legends; if (Util.isNil(legendOptions) || legendOptions !== false) { // 没有关闭图例 var legendController = this.get('legendController'); legendController.options = legendOptions || {}; legendController.plotRange = this.get('plotRange'); if (legendOptions && legendOptions.custom) { // 用户自定义图例 legendController.addCustomLegend(); } else { var geoms = this.getAllGeoms(); var scales = []; Util.each(geoms, function (geom) { var view = geom.get('view'); var attrs = geom.getAttrsForLegend(); Util.each(attrs, function (attr) { var type = attr.type; var scale = attr.getScale(type); if (scale.field && scale.type !== 'identity' && !_isScaleExist(scales, scale)) { scales.push(scale); var filteredValues = view.getFilteredOutValues(scale.field); legendController.addLegend(scale, attr, geom, filteredValues); } }); }); // 双轴的情况 var yScales = this.getYScales(); if (scales.length === 0 && yScales.length > 1) { legendController.addMixedLegend(yScales, geoms); } } legendController.alignLegends(); } } // 绘制 tooltip ; _proto._renderTooltips = function _renderTooltips() { var options = this.get('options'); if (Util.isNil(options.tooltip) || options.tooltip !== false) { // 用户没有关闭 tooltip var tooltipController = this.get('tooltipController'); tooltipController.options = options.tooltip || {}; tooltipController.renderTooltip(); } } /** * 获取所有的几何标记 * @return {Array} 所有的几何标记 */ ; _proto.getAllGeoms = function getAllGeoms() { var geoms = []; geoms = geoms.concat(this.get('geoms')); var views = this.get('views'); Util.each(views, function (view) { geoms = geoms.concat(view.get('geoms')); }); return geoms; } /** * 自适应宽度 * @chainable * @return {Chart} 图表对象 */ ; _proto.forceFit = function forceFit() { var self = this; if (!self || self.destroyed) { return; } var container = self.get('container'); var oldWidth = self.get('width'); var width = DomUtil.getWidth(container, oldWidth); if (width !== 0 && width !== oldWidth) { var height = self.get('height'); self.changeSize(width, height); } return self; }; _proto.resetPlot = function resetPlot() { var plot = this.get('plot'); var padding = this.get('padding'); if (!isEqualArray(padding, plot.get('padding'))) { // 重置 padding,仅当padding 发生更改 plot.set('padding', padding); plot.repaint(); } } /** * 改变大小 * @param {Number} width 图表宽度 * @param {Number} height 图表高度 * @return {Chart} 图表对象 */ ; _proto.changeSize = function changeSize(width, height) { var self = this; var canvas = self.get('canvas'); canvas.changeSize(width, height); var plot = this.get('plot'); self.set('width', width); self.set('height', height); // change size 时重新计算边框 plot.repaint(); // 保持边框不变,防止自动 padding 时绘制多遍 this.set('keepPadding', true); self.repaint(); this.set('keepPadding', false); this.emit('afterchangesize'); return self; } /** * 改变宽度 * @param {Number} width 图表宽度 * @return {Chart} 图表对象 */ ; _proto.changeWidth = function changeWidth(width) { return this.changeSize(width, this.get('height')); } /** * 改变宽度 * @param {Number} height 图表高度 * @return {Chart} 图表对象 */ ; _proto.changeHeight = function changeHeight(height) { return this.changeSize(this.get('width'), height); } /** * 创建一个视图 * @param {Object} cfg 视图的配置项 * @return {View} 视图对象 */ ; _proto.view = function view(cfg) { cfg = cfg || {}; cfg.theme = this.get('theme'); cfg.parent = this; cfg.backPlot = this.get('backPlot'); cfg.middlePlot = this.get('middlePlot'); cfg.frontPlot = this.get('frontPlot'); cfg.canvas = this.get('canvas'); if (Util.isNil(cfg.animate)) { cfg.animate = this.get('animate'); } cfg.options = Util.mix({}, this._getSharedOptions(), cfg.options); var view = new View(cfg); view.set('_id', 'view' + this.get('views').length); // 标识 ID,防止同用户设定的 id 重名 this.get('views').push(view); this.emit('addview', { view: view }); return view; } // isShapeInView() { // return true; // } ; _proto.removeView = function removeView(view) { var views = this.get('views'); Util.Array.remove(views, view); view.destroy(); }; _proto._getSharedOptions = function _getSharedOptions() { var options = this.get('options'); var sharedOptions = {}; Util.each(['scales', 'coord', 'axes'], function (name) { sharedOptions[name] = Util.cloneDeep(options[name]); }); return sharedOptions; } /** * @override * 当前chart 的范围 */ ; _proto.getViewRegion = function getViewRegion() { var plotRange = this.get('plotRange'); return { start: plotRange.bl, end: plotRange.tr }; } /** * 设置图例配置信息 * @param {String|Object} field 字段名 * @param {Object} [cfg] 图例的配置项 * @return {Chart} 当前的图表对象 */ ; _proto.legend = function legend(field, cfg) { var options = this.get('options'); if (!options.legends) { options.legends = {}; } var legends = {}; if (field === false) { options.legends = false; } else if (Util.isObject(field)) { legends = field; } else if (Util.isString(field)) { legends[field] = cfg; } else { legends = cfg; } Util.mix(options.legends, legends); return this; } /** * 设置提示信息 * @param {String|Object} visible 是否可见 * @param {Object} [cfg] 提示信息的配置项 * @return {Chart} 当前的图表对象 */ ; _proto.tooltip = function tooltip(visible, cfg) { var options = this.get('options'); if (!options.tooltip) { options.tooltip = {}; } if (visible === false) { options.tooltip = false; } else if (Util.isObject(visible)) { Util.mix(options.tooltip, visible); } else { Util.mix(options.tooltip, cfg); } return this; } /** * 清空图表 * @return {Chart} 当前的图表对象 */ ; _proto.clear = function clear() { this.emit('beforeclear'); var views = this.get('views'); while (views.length > 0) { var view = views.shift(); view.destroy(); } _View.prototype.clear.call(this); var canvas = this.get('canvas'); this.resetPlot(); canvas.draw(); this.emit('afterclear'); return this; }; _proto.clearInner = function clearInner() { var views = this.get('views'); Util.each(views, function (view) { view.clearInner(); }); var tooltipController = this.get('tooltipController'); tooltipController && tooltipController.clear(); if (!this.get('keepLegend')) { var legendController = this.get('legendController'); legendController && legendController.clear(); } _View.prototype.clearInner.call(this); } // chart 除了view 上绘制的组件外,还会绘制图例和 tooltip ; _proto.drawComponents = function drawComponents() { _View.prototype.drawComponents.call(this); // 一般是点击图例时,仅仅隐藏某些选项,而不销毁图例 if (!this.get('keepLegend')) { this._renderLegends(); // 渲染图例 } } /** * 绘制图表 * @override */ ; _proto.render = function render() { var self = this; // 需要自动计算边框,则重新设置 if (!self.get('keepPadding') && self._isAutoPadding()) { self.beforeRender(); // 初始化各个 view 和 绘制 self.drawComponents(); var autoPadding = self._getAutoPadding(); var plot = self.get('plot'); // 在计算出来的边框不一致的情况,重新改变边框 if (!isEqualArray(plot.get('padding'), autoPadding)) { plot.set('padding', autoPadding); plot.repaint(); } } var middlePlot = self.get('middlePlot'); if (self.get('limitInPlot') && !middlePlot.attr('clip')) { var clip = Util.getClipByRange(self.get('plotRange')); // TODO Polar coord middlePlot.attr('clip', clip); // clip.attr('fill', 'grey'); // clip.attr('opacity', 0.5); // middlePlot.add(clip); } _View.prototype.render.call(this); self._renderTooltips(); // 渲染 tooltip }; _proto.repaint = function repaint() { // 重绘时需要判定当前的 padding 是否发生过改变,如果发生过改变进行调整 // 需要判定是否使用了自动 padding if (!this.get('keepPadding')) { this.resetPlot(); } _View.prototype.repaint.call(this); } /** * @override * 显示或者隐藏 */ ; _proto.changeVisible = function changeVisible(visible) { var wrapperEl = this.get('wrapperEl'); var visibleStr = visible ? '' : 'none'; wrapperEl.style.display = visibleStr; } /** * 返回图表的 dataUrl 用于生成图片 * @return {String} dataUrl 路径 */ ; _proto.toDataURL = function toDataURL() { var chart = this; var canvas = chart.get('canvas'); var renderer = chart.get('renderer'); var canvasDom = canvas.get('el'); var dataURL = ''; if (renderer === 'svg') { var clone = canvasDom.cloneNode(true); var svgDocType = document.implementation.createDocumentType('svg', '-//W3C//DTD SVG 1.1//EN', 'http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd'); var svgDoc = document.implementation.createDocument('http://www.w3.org/2000/svg', 'svg', svgDocType); svgDoc.replaceChild(clone, svgDoc.documentElement); var svgData = new XMLSerializer().serializeToString(svgDoc); dataURL = 'data:image/svg+xml;charset=utf8,' + encodeURIComponent(svgData); } else if (renderer === 'canvas') { dataURL = canvasDom.toDataURL('image/png'); } return dataURL; } /** * 图表导出功能 * @param {String} [name] 图片的名称,默认为 chart(.png|.svg) */ ; _proto.downloadImage = function downloadImage(name) { var chart = this; var link = document.createElement('a'); var renderer = chart.get('renderer'); var filename = (name || 'chart') + (renderer === 'svg' ? '.svg' : '.png'); var canvas = chart.get('canvas'); canvas.get('timeline').stopAllAnimations(); setTimeout(function () { var dataURL = chart.toDataURL(); if (window.Blob && window.URL && renderer !== 'svg') { var arr = dataURL.split(','); var mime = arr[0].match(/:(.*?);/)[1]; var bstr = atob(arr[1]); var n = bstr.length; var u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } var blobObj = new Blob([u8arr], { type: mime }); if (window.navigator.msSaveBlob) { window.navigator.msSaveBlob(blobObj, filename); } else { link.addEventListener('click', function () { link.download = filename; link.href = window.URL.createObjectURL(blobObj); }); } } else { link.addEventListener('click', function () { link.download = filename; link.href = dataURL; }); } var e = document.createEvent('MouseEvents'); e.initEvent('click', false, false); link.dispatchEvent(e); }, 16); } /** * 根据坐标点显示对应的 tooltip * @param {Object} point 画布上的点 * @return {Chart} 返回 chart 实例 */ ; _proto.showTooltip = function showTooltip(point) { var views = this.getViewsByPoint(point); if (views.length) { var tooltipController = this.get('tooltipController'); tooltipController.showTooltip(point, views); } return this; } /** * 将tooltip 锁定到当前位置不能移动 * @return {Chart} 返回 chart 实例 */ ; _proto.lockTooltip = function lockTooltip() { var tooltipController = this.get('tooltipController'); tooltipController.lockTooltip(); return this; } /** * 将tooltip 锁定解除 * @return {Chart} 返回 chart 实例 */ ; _proto.unlockTooltip = function unlockTooltip() { var tooltipController = this.get('tooltipController'); tooltipController.unlockTooltip(); return this; } /** * 隐藏 tooltip * @return {Chart} 返回 chart 实例 */ ; _proto.hideTooltip = function hideTooltip() { var tooltipController = this.get('tooltipController'); tooltipController.hideTooltip(); return this; } /** * 根据传入的画布坐标,获取该处的 tooltip 上的记录信息 * @param {Object} point 画布坐标点 * @return {Array} 返回结果 */ ; _proto.getTooltipItems = function getTooltipItems(point) { var self = this; var views = self.getViewsByPoint(point); var rst = []; Util.each(views, function (view) { var geoms = view.get('geoms'); Util.each(geoms, function (geom) { var dataArray = geom.get('dataArray'); var items = []; Util.each(dataArray, function (data) { var tmpPoint = geom.findPoint(point, data); if (tmpPoint) { var subItems = geom.getTipItems(tmpPoint); items = items.concat(subItems); } }); rst = rst.concat(items); }); }); return rst; } /** * @override * 销毁图表 */ ; _proto.destroy = function destroy() { this.emit('beforedestroy'); clearTimeout(this.get('resizeTimer')); var canvas = this.get('canvas'); var wrapperEl = this.get('wrapperEl'); wrapperEl.parentNode.removeChild(wrapperEl); _View.prototype.destroy.call(this); canvas.destroy(); window.removeEventListener('resize', Util.getWrapBehavior(this, '_initForceFitEvent')); this.emit('afterdestroy'); }; return Chart; }(View); module.exports = Chart; /***/ }), /* 164 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @fileOverview Chart、View、Geometry 的基类 * @author dxq613@gmail.com */ var EventEmitter = __webpack_require__(90); var Util = __webpack_require__(0); var Base = /*#__PURE__*/function (_EventEmitter) { _inheritsLoose(Base, _EventEmitter); var _proto = Base.prototype; _proto.getDefaultCfg = function getDefaultCfg() { return {}; }; function Base(cfg) { var _this; _this = _EventEmitter.call(this) || this; var attrs = { visible: true }; var defaultCfg = _this.getDefaultCfg(); _this._attrs = attrs; Util.assign(attrs, defaultCfg, cfg); return _this; } _proto.get = function get(name) { return this._attrs[name]; }; _proto.set = function set(name, value) { this._attrs[name] = value; }; _proto.show = function show() { var visible = this.get('visible'); if (!visible) { this.set('visible', true); this.changeVisible(true); } }; _proto.hide = function hide() { var visible = this.get('visible'); if (visible) { this.set('visible', false); this.changeVisible(false); } } /** * @protected * @param {Boolean} visible 是否可见 * 显示、隐藏 */ ; _proto.changeVisible = function changeVisible() {}; _proto.destroy = function destroy() { this._attrs = {}; this.removeAllListeners(); this.destroyed = true; }; return Base; }(EventEmitter); module.exports = Base; /***/ }), /* 165 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview 颜色计算的辅助方法 * @author dxq613@gmail.com */ var isNumber = __webpack_require__(11); var isString = __webpack_require__(12); var each = __webpack_require__(3); // const RGB_REG = /rgb\((\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)/; var RGB_REG = /rgba?\(([\s.,0-9]+)\)/; // 创建辅助 tag 取颜色 function createTmp() { var i = document.createElement('i'); i.title = 'Web Colour Picker'; i.style.display = 'none'; document.body.appendChild(i); return i; } // 获取颜色之间的插值 function getValue(start, end, percent, index) { var value = start[index] + (end[index] - start[index]) * percent; return value; } // 数组转换成颜色 function arr2rgb(arr) { return '#' + toHex(arr[0]) + toHex(arr[1]) + toHex(arr[2]); } // 将数值从 0-255 转换成16进制字符串 function toHex(value) { value = Math.round(value); value = value.toString(16); if (value.length === 1) { value = '0' + value; } return value; } function calColor(colors, percent) { if (isNaN(percent) || !isNumber(percent) || percent < 0) { percent = 0; } if (percent > 1) { percent = 1; } var steps = colors.length - 1; var step = Math.floor(steps * percent); var left = steps * percent - step; var start = colors[step]; var end = step === steps ? start : colors[step + 1]; var rgb = arr2rgb([getValue(start, end, left, 0), getValue(start, end, left, 1), getValue(start, end, left, 2)]); return rgb; } // rgb 颜色转换成数组 function rgb2arr(str) { var arr = []; arr.push(parseInt(str.substr(1, 2), 16)); arr.push(parseInt(str.substr(3, 2), 16)); arr.push(parseInt(str.substr(5, 2), 16)); return arr; } var colorCache = {}; var iEl = null; var ColorUtil = { /** * 将颜色转换到 rgb 的格式 * @param {String} color 颜色 * @return {String} 将颜色转换到 '#ffffff' 的格式 */ toRGB: function toRGB(color) { // 如果已经是 rgb的格式 if (color[0] === '#' && color.length === 7) { return color; } if (!iEl) { // 防止防止在页头报错 iEl = createTmp(); } var rst; if (colorCache[color]) { rst = colorCache[color]; } else { iEl.style.color = color; rst = document.defaultView.getComputedStyle(iEl, '').getPropertyValue('color'); var matchs = RGB_REG.exec(rst); var cArray = matchs[1].split(/\s*,\s*/); rst = arr2rgb(cArray); colorCache[color] = rst; } return rst; }, rgb2arr: rgb2arr, /** * 获取渐变函数 * @param {Array} colors 多个颜色 * @return {String} 颜色值 */ gradient: function gradient(colors) { var points = []; if (isString(colors)) { colors = colors.split('-'); } each(colors, function (color) { if (color.indexOf('#') === -1) { color = ColorUtil.toRGB(color); } points.push(rgb2arr(color)); }); return function (percent) { return calColor(points, percent); }; } }; module.exports = ColorUtil; /***/ }), /* 166 */ /***/ (function(module, exports, __webpack_require__) { var DEFAULT_Y = 0; // 默认的y的值 var each = __webpack_require__(3); var ArrayUtil = { values: __webpack_require__(89) }; module.exports = { /** * 对应的维度是否可以调整 * @protected * @param {String} dimName 可以调整的维度 x,y * @return {Boolean} 是否可以调整 */ isAdjust: function isAdjust(dimName) { return this.adjustNames.indexOf(dimName) >= 0; }, /** * @protected * 获取可调整度量对应的值 * @param {Frame} mergeData 数据 * @return {Object} 值的映射 */ _getDimValues: function _getDimValues(mergeData) { var self = this; var valuesMap = {}; var dims = []; if (self.xField && self.isAdjust('x')) { dims.push(self.xField); } if (self.yField && self.isAdjust('y')) { dims.push(self.yField); } each(dims, function (dim) { var values = ArrayUtil.values(mergeData, dim); values.sort(function (v1, v2) { return v1 - v2; }); valuesMap[dim] = values; }); if (!self.yField && self.isAdjust('y')) { // 只有一维的情况下,同时调整y var dim = 'y'; var values = [DEFAULT_Y, 1]; // 默认分布在y轴的 0.1 与 0.2 之间 valuesMap[dim] = values; } return valuesMap; }, adjustData: function adjustData(dataArray, mergeData) { var self = this; var valuesMap = self._getDimValues(mergeData); each(dataArray, function (data, index) { // 遍历所有数据集合 each(valuesMap, function (values, dim) { // 根据不同的度量分别调整位置 self.adjustDim(dim, values, data, dataArray.length, index); }); }); }, getAdjustRange: function getAdjustRange(dim, key, values) { var self = this; var index = values.indexOf(key); var length = values.length; var pre; var next; if (!self.yField && self.isAdjust('y')) { pre = 0; next = 1; } else if (length > 1) { pre = index === 0 ? values[0] : values[index - 1]; next = index === length - 1 ? values[length - 1] : values[index + 1]; if (index !== 0) { pre += (key - pre) / 2; } else { pre -= (next - key) / 2; } if (index !== length - 1) { next -= (next - key) / 2; } else { next += (key - values[length - 2]) / 2; } } else { pre = key === 0 ? 0 : key - 0.5; next = key === 0 ? 1 : key + 0.5; } return { pre: pre, next: next }; }, /** * 对数据进行分组 * @param {Array} data 数据 * @param {String} dim 分组的字段 * @return {Object} 分组的键值对映射 */ groupData: function groupData(data, dim) { var groups = {}; each(data, function (record) { var value = record[dim]; if (value === undefined) { value = record[dim] = DEFAULT_Y; } if (!groups[value]) { groups[value] = []; } groups[value].push(record); }); return groups; } }; /***/ }), /* 167 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview Theme entry * @author sima.zhang */ var Theme = { default: __webpack_require__(168), dark: __webpack_require__(342) }; module.exports = Theme; /***/ }), /* 168 */ /***/ (function(module, exports) { var _html, _tooltip; /** * @fileOverview G2 3.0 default theme * @author sima.zhang */ var DEFAULT_COLOR = '#1890FF'; var COLOR_PLATE_8 = ['#1890FF', '#2FC25B', '#FACC14', '#223273', '#8543E0', '#13C2C2', '#3436C7', '#F04864']; var COLOR_PLATE_16 = ['#1890FF', '#41D9C7', '#2FC25B', '#FACC14', '#E6965C', '#223273', '#7564CC', '#8543E0', '#5C8EE6', '#13C2C2', '#5CA3E6', '#3436C7', '#B381E6', '#F04864', '#D598D9']; var COLOR_PLATE_24 = ['#1890FF', '#66B5FF', '#41D9C7', '#2FC25B', '#6EDB8F', '#9AE65C', '#FACC14', '#E6965C', '#57AD71', '#223273', '#738AE6', '#7564CC', '#8543E0', '#A877ED', '#5C8EE6', '#13C2C2', '#70E0E0', '#5CA3E6', '#3436C7', '#8082FF', '#DD81E6', '#F04864', '#FA7D92', '#D598D9']; var COLOR_PIE = ['#1890FF', '#13C2C2', '#2FC25B', '#FACC14', '#F04864', '#8543E0', '#3436C7', '#223273']; var COLOR_PIE_16 = ['#1890FF', '#73C9E6', '#13C2C2', '#6CD9B3', '#2FC25B', '#9DD96C', '#FACC14', '#E6965C', '#F04864', '#D66BCA', '#8543E0', '#8E77ED', '#3436C7', '#737EE6', '#223273', '#7EA2E6']; var FONT_FAMILY = 'BlinkMacSystemFont, "Segoe UI", Roboto,"Helvetica Neue", Helvetica, "PingFang SC", "Hiragino Sans GB", "Microsoft YaHei",SimSun, "sans-serif"'; // tooltip 相关 dom 的 css 类名 var TOOLTIP_CONTAINER_CLASS = 'g2-tooltip'; var TOOLTIP_TITLE_CLASS = 'g2-tooltip-title'; var TOOLTIP_LIST_CLASS = 'g2-tooltip-list'; var TOOLTIP_LIST_ITEM_CLASS = 'g2-tooltip-list-item'; var TOOLTIP_MARKER_CLASS = 'g2-tooltip-marker'; var TOOLTIP_VALUE_CLASS = 'g2-tooltip-value'; // html 渲染的 legend 相关 dom 的 css 类型 var LEGEND_CONTAINER_CLASS = 'g2-legend'; var LEGEND_TITLE_CLASS = 'g2-legend-title'; var LEGEND_LIST_CLASS = 'g2-legend-list'; var LEGEND_LIST_ITEM_CLASS = 'g2-legend-list-item'; var LEGEND_MARKER_CLASS = 'g2-legend-marker'; var Theme = { defaultColor: DEFAULT_COLOR, // 默认主题色 plotCfg: { padding: [20, 20, 95, 80] }, fontFamily: FONT_FAMILY, defaultLegendPosition: 'bottom', // 默认图例的展示位置 colors: COLOR_PLATE_8, colors_16: COLOR_PLATE_16, colors_24: COLOR_PLATE_24, colors_pie: COLOR_PIE, colors_pie_16: COLOR_PIE_16, shapes: { point: ['hollowCircle', 'hollowSquare', 'hollowDiamond', 'hollowBowtie', 'hollowTriangle', 'hollowHexagon', 'cross', 'tick', 'plus', 'hyphen', 'line'], line: ['line', 'dash', 'dot'], area: ['area'] }, sizes: [1, 10], opacities: [0.1, 0.9], axis: { top: { // zIndex: 1, // 默认上下方向的坐标轴位于左右坐标轴的上方 position: 'top', title: null, label: { offset: 16, textStyle: { fill: '#545454', fontSize: 12, lineHeight: 16, textBaseline: 'middle', fontFamily: FONT_FAMILY }, autoRotate: true }, line: { lineWidth: 1, stroke: '#BFBFBF' }, tickLine: { lineWidth: 1, stroke: '#BFBFBF', length: 4, alignWithLabel: true } }, bottom: { position: 'bottom', title: null, label: { offset: 16, autoRotate: true, textStyle: { fill: '#545454', fontSize: 12, lineHeight: 16, textBaseline: 'middle', fontFamily: FONT_FAMILY } }, line: { lineWidth: 1, stroke: '#BFBFBF' }, tickLine: { lineWidth: 1, stroke: '#BFBFBF', length: 4, alignWithLabel: true } }, left: { position: 'left', title: null, label: { offset: 8, autoRotate: true, textStyle: { fill: '#545454', fontSize: 12, lineHeight: 16, textBaseline: 'middle', fontFamily: FONT_FAMILY } }, line: null, tickLine: null, grid: { zIndex: -1, lineStyle: { stroke: '#E9E9E9', lineWidth: 1, lineDash: [3, 3] }, hideFirstLine: true } }, right: { position: 'right', title: null, label: { offset: 8, autoRotate: true, textStyle: { fill: '#545454', fontSize: 12, lineHeight: 16, textBaseline: 'middle', fontFamily: FONT_FAMILY } }, line: null, tickLine: null, grid: { lineStyle: { stroke: '#E9E9E9', lineWidth: 1, lineDash: [3, 3] }, hideFirstLine: true } }, circle: { zIndex: 1, title: null, label: { offset: 8, textStyle: { fill: '#545454', fontSize: 12, lineHeight: 16, fontFamily: FONT_FAMILY } }, line: { lineWidth: 1, stroke: '#BFBFBF' }, tickLine: { lineWidth: 1, stroke: '#BFBFBF', length: 4, alignWithLabel: true }, grid: { lineStyle: { stroke: '#E9E9E9', lineWidth: 1, lineDash: [3, 3] }, hideFirstLine: true } }, radius: { zIndex: 0, label: { offset: 12, textStyle: { fill: '#545454', fontSize: 12, textBaseline: 'middle', lineHeight: 16, fontFamily: FONT_FAMILY } }, line: { lineWidth: 1, stroke: '#BFBFBF' }, tickLine: { lineWidth: 1, stroke: '#BFBFBF', length: 4, alignWithLabel: true }, grid: { lineStyle: { stroke: '#E9E9E9', lineWidth: 1, lineDash: [3, 3] }, type: 'circle' } }, helix: { grid: null, label: null, title: null, line: { lineWidth: 1, stroke: '#BFBFBF' }, tickLine: { lineWidth: 1, length: 4, stroke: '#BFBFBF', alignWithLabel: true } } }, label: { offset: 20, textStyle: { fill: '#545454', fontSize: 12, textBaseline: 'middle', fontFamily: FONT_FAMILY } }, treemapLabels: { offset: 10, textStyle: { fill: '#fff', fontSize: 12, textBaseline: 'top', fontStyle: 'bold', fontFamily: FONT_FAMILY } }, innerLabels: { textStyle: { fill: '#fff', fontSize: 12, textBaseline: 'middle', fontFamily: FONT_FAMILY } }, // 在theta坐标系下的饼图文本内部的样式 thetaLabels: { labelHeight: 14, offset: 30 // 在theta坐标系下的饼图文本的样式 }, legend: { right: { position: 'right', layout: 'vertical', itemMarginBottom: 8, // layout 为 vertical 时各个图例项的间距 width: 16, height: 156, title: null, legendStyle: { LIST_CLASS: { textAlign: 'left' } }, textStyle: { fill: '#8C8C8C', fontSize: 12, textAlign: 'start', textBaseline: 'middle', lineHeight: 0, fontFamily: FONT_FAMILY }, // 图例项文本的样式 unCheckColor: '#bfbfbf' }, left: { position: 'left', layout: 'vertical', itemMarginBottom: 8, width: 16, height: 156, title: null, textStyle: { fill: '#8C8C8C', fontSize: 12, textAlign: 'start', textBaseline: 'middle', lineHeight: 20, fontFamily: FONT_FAMILY }, // 图例项文本的样式 unCheckColor: '#bfbfbf' }, top: { position: 'top', offset: [0, 6], layout: 'horizontal', title: null, itemGap: 10, width: 156, height: 16, textStyle: { fill: '#8C8C8C', fontSize: 12, textAlign: 'start', textBaseline: 'middle', lineHeight: 20, fontFamily: FONT_FAMILY }, // 图例项文本的样式 unCheckColor: '#bfbfbf' }, bottom: { position: 'bottom', offset: [0, 6], layout: 'horizontal', title: null, itemGap: 10, width: 156, height: 16, textStyle: { fill: '#8C8C8C', fontSize: 12, textAlign: 'start', textBaseline: 'middle', lineHeight: 20, fontFamily: FONT_FAMILY }, // 图例项文本的样式 unCheckColor: '#bfbfbf' }, // 定义 html 渲染图例的样式 html: (_html = {}, _html["" + LEGEND_CONTAINER_CLASS] = { height: 'auto', width: 'auto', position: 'absolute', overflow: 'auto', fontSize: '12px', fontFamily: FONT_FAMILY, lineHeight: '20px', color: '#8C8C8C' }, _html["" + LEGEND_TITLE_CLASS] = { marginBottom: '4px' }, _html["" + LEGEND_LIST_CLASS] = { listStyleType: 'none', margin: 0, padding: 0 }, _html["" + LEGEND_LIST_ITEM_CLASS] = { listStyleType: 'none', cursor: 'pointer', marginBottom: '5px', marginRight: '24px' }, _html["" + LEGEND_MARKER_CLASS] = { width: '9px', height: '9px', borderRadius: '50%', display: 'inline-block', marginRight: '8px', verticalAlign: 'middle' }, _html), // 不能滑动的连续图例样式 gradient: { textStyle: { fill: '#8C8C8C', fontSize: 12, textAlign: 'center', textBaseline: 'middle', lineHeight: 20, fontFamily: FONT_FAMILY }, // 图例项文本的样式 lineStyle: { lineWidth: 1, stroke: '#fff' }, unCheckColor: '#bfbfbf' }, margin: [0, 5, 24, 5], // 图例跟四个边的坐标轴、绘图区域的间距 legendMargin: 24 // 图例之间的间距 }, tooltip: (_tooltip = { useHtml: true, crosshairs: false, offset: 15, marker: { symbol: 'circle', activeSymbol: 'circle' } }, _tooltip["" + TOOLTIP_CONTAINER_CLASS] = { position: 'absolute', visibility: 'hidden', // @2018-07-25 by blue.lb 这里去掉浮动,火狐上存在样式错位 // whiteSpace: 'nowrap', zIndex: 8, transition: 'visibility 0.2s cubic-bezier(0.23, 1, 0.32, 1), left 0.4s cubic-bezier(0.23, 1, 0.32, 1), top 0.4s cubic-bezier(0.23, 1, 0.32, 1)', backgroundColor: 'rgba(255, 255, 255, 0.9)', boxShadow: '0px 0px 10px #aeaeae', borderRadius: '3px', color: 'rgb(87, 87, 87)', fontSize: '12px', fontFamily: FONT_FAMILY, lineHeight: '20px', padding: '10px 10px 6px 10px' }, _tooltip["" + TOOLTIP_TITLE_CLASS] = { marginBottom: '4px' }, _tooltip["" + TOOLTIP_LIST_CLASS] = { margin: 0, listStyleType: 'none', padding: 0 }, _tooltip["" + TOOLTIP_LIST_ITEM_CLASS] = { listStyleType: 'none', marginBottom: '4px', padding: 0, marginTop: 0, marginLeft: 0, marginRight: 0 }, _tooltip["" + TOOLTIP_MARKER_CLASS] = { width: '5px', height: '5px', display: 'inline-block', marginRight: '8px' }, _tooltip["" + TOOLTIP_VALUE_CLASS] = { display: 'inline-block', float: 'right', marginLeft: '30px' }, _tooltip), tooltipMarker: { symbol: function symbol(x, y, r) { return [['M', x, y], ['m', -r, 0], ['a', r, r, 0, 1, 0, r * 2, 0], ['a', r, r, 0, 1, 0, -r * 2, 0]]; }, stroke: '#fff', shadowBlur: 10, shadowOffsetX: 0, shadowOffSetY: 0, shadowColor: 'rgba(0,0,0,0.09)', lineWidth: 2, radius: 4 }, // 提示信息在折线图、区域图上形成点的样式 tooltipCrosshairsRect: { type: 'rect', rectStyle: { fill: '#CCD6EC', opacity: 0.3 } }, // tooltip 辅助背景框样式 tooltipCrosshairsLine: { lineStyle: { stroke: 'rgba(0, 0, 0, 0.25)', lineWidth: 1 } }, shape: { point: { lineWidth: 1, fill: DEFAULT_COLOR, radius: 4 }, hollowPoint: { fill: '#fff', lineWidth: 1, stroke: DEFAULT_COLOR, radius: 3 }, interval: { lineWidth: 0, fill: DEFAULT_COLOR, fillOpacity: 0.85 }, hollowInterval: { fill: '#fff', stroke: DEFAULT_COLOR, fillOpacity: 0, lineWidth: 2 }, area: { lineWidth: 0, fill: DEFAULT_COLOR, fillOpacity: 0.6 }, polygon: { lineWidth: 0, fill: DEFAULT_COLOR, fillOpacity: 1 }, hollowPolygon: { fill: '#fff', stroke: DEFAULT_COLOR, fillOpacity: 0, lineWidth: 2 }, hollowArea: { fill: '#fff', stroke: DEFAULT_COLOR, fillOpacity: 0, lineWidth: 2 }, line: { stroke: DEFAULT_COLOR, lineWidth: 2, fill: null }, edge: { stroke: DEFAULT_COLOR, lineWidth: 1, fill: null }, schema: { stroke: DEFAULT_COLOR, lineWidth: 1, fill: null } }, guide: { line: { lineStyle: { stroke: 'rgba(0, 0, 0, .65)', lineDash: [2, 2], lineWidth: 1 }, text: { position: 'start', autoRotate: true, style: { fill: 'rgba(0, 0, 0, .45)', fontSize: 12, textAlign: 'start', fontFamily: FONT_FAMILY, textBaseline: 'bottom' } } }, text: { style: { fill: 'rgba(0,0,0,.5)', fontSize: 12, textBaseline: 'middle', textAlign: 'start', fontFamily: FONT_FAMILY } }, region: { style: { lineWidth: 0, // 辅助框的边框宽度 fill: '#000', // 辅助框填充的颜色 fillOpacity: 0.04 // 辅助框的背景透明度 } // 辅助框的图形样式属性 }, html: { alignX: 'middle', alignY: 'middle' }, dataRegion: { style: { region: { lineWidth: 0, fill: '#000000', opacity: 0.04 }, text: { textAlign: 'center', textBaseline: 'bottom', fontSize: 12, fill: 'rgba(0, 0, 0, .65)' } } }, dataMarker: { top: true, style: { point: { r: 3, fill: '#FFFFFF', stroke: '#1890FF', lineWidth: 2 }, line: { stroke: '#A3B1BF', lineWidth: 1 }, text: { fill: 'rgba(0, 0, 0, .65)', opacity: 1, fontSize: 12, textAlign: 'start' } }, display: { point: true, line: true, text: true }, lineLength: 20, direction: 'upward', autoAdjust: true } }, pixelRatio: null }; module.exports = Theme; /***/ }), /* 169 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { isFunction: __webpack_require__(13), isObject: __webpack_require__(22), isBoolean: __webpack_require__(60), isNil: __webpack_require__(6), isString: __webpack_require__(12), isArray: __webpack_require__(5), isNumber: __webpack_require__(11), isEmpty: __webpack_require__(61), // isBlank uniqueId: __webpack_require__(62), clone: __webpack_require__(39), deepMix: __webpack_require__(27), assign: __webpack_require__(10), // simpleMix merge: __webpack_require__(27), // mix upperFirst: __webpack_require__(64), // ucfirst each: __webpack_require__(3), isEqual: __webpack_require__(40), toArray: __webpack_require__(29), extend: __webpack_require__(65), augment: __webpack_require__(66), remove: __webpack_require__(67), isNumberEqual: __webpack_require__(30), toRadian: __webpack_require__(68), toDegree: __webpack_require__(69), mod: __webpack_require__(70), clamp: __webpack_require__(41), createDom: __webpack_require__(71), modifyCSS: __webpack_require__(72), requestAnimationFrame: __webpack_require__(73), getRatio: function getRatio() { return window.devicePixelRatio ? window.devicePixelRatio : 2; }, mat3: __webpack_require__(42), vec2: __webpack_require__(75), vec3: __webpack_require__(76), transform: __webpack_require__(77) }; /***/ }), /* 170 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Event = function Event(type, event, bubbles, cancelable) { this.type = type; // 事件类型 this.target = null; // 目标 this.currentTarget = null; // 当前目标 this.bubbles = bubbles; // 冒泡 this.cancelable = cancelable; // 是否能够阻止 this.timeStamp = new Date().getTime(); // 时间戳 this.defaultPrevented = false; // 阻止默认 this.propagationStopped = false; // 阻止冒泡 this.removed = false; // 是否被移除 this.event = event; // 触发的原生事件 }; Util.augment(Event, { preventDefault: function preventDefault() { this.defaultPrevented = this.cancelable && true; }, stopPropagation: function stopPropagation() { this.propagationStopped = true; }, remove: function remove() { this.remove = true; }, clone: function clone() { return Util.clone(this); }, toString: function toString() { return '[Event (type=' + this.type + ')]'; } }); module.exports = Event; /***/ }), /* 171 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Element = __webpack_require__(172); var Shape = __webpack_require__(349); var SHAPE_MAP = {}; // 缓存图形类型 var INDEX = '_INDEX'; function getComparer(compare) { return function (left, right) { var result = compare(left, right); return result === 0 ? left[INDEX] - right[INDEX] : result; }; } function find(children, x, y) { var rst; for (var i = children.length - 1; i >= 0; i--) { var child = children[i]; if (child._cfg.visible && child._cfg.capture) { if (child.isGroup) { rst = child.getShape(x, y); } else if (child.isHit(x, y)) { rst = child; } } if (rst) { break; } } return rst; } var Group = function Group(cfg) { Group.superclass.constructor.call(this, cfg); this.set('children', []); this.set('tobeRemoved', []); this._beforeRenderUI(); this._renderUI(); this._bindUI(); }; function initClassCfgs(c) { if (c._cfg || c === Group) { return; } var superCon = c.superclass.constructor; if (superCon && !superCon._cfg) { initClassCfgs(superCon); } c._cfg = {}; Util.merge(c._cfg, superCon._cfg); Util.merge(c._cfg, c.CFG); } Util.extend(Group, Element); Util.augment(Group, { isGroup: true, type: 'group', canFill: true, canStroke: true, getDefaultCfg: function getDefaultCfg() { initClassCfgs(this.constructor); return Util.merge({}, this.constructor._cfg); }, _beforeRenderUI: function _beforeRenderUI() {}, _renderUI: function _renderUI() {}, _bindUI: function _bindUI() {}, addShape: function addShape(type, cfg) { var canvas = this.get('canvas'); cfg = cfg || {}; var shapeType = SHAPE_MAP[type]; if (!shapeType) { shapeType = Util.upperFirst(type); SHAPE_MAP[type] = shapeType; } if (cfg.attrs && canvas) { var attrs = cfg.attrs; if (type === 'text') { // 临时解决 var topFontFamily = canvas.get('fontFamily'); if (topFontFamily) { attrs.fontFamily = attrs.fontFamily ? attrs.fontFamily : topFontFamily; } } } cfg.canvas = canvas; cfg.type = type; var rst = new Shape[shapeType](cfg); this.add(rst); return rst; }, /** 添加图组 * @param {Function|Object|undefined} param 图组类 * @param {Object} cfg 配置项 * @return {Object} rst 图组 */ addGroup: function addGroup(param, cfg) { var canvas = this.get('canvas'); var rst; cfg = Util.merge({}, cfg); if (Util.isFunction(param)) { if (cfg) { cfg.canvas = canvas; cfg.parent = this; rst = new param(cfg); } else { rst = new param({ canvas: canvas, parent: this }); } this.add(rst); } else if (Util.isObject(param)) { param.canvas = canvas; rst = new Group(param); this.add(rst); } else if (param === undefined) { rst = new Group(); this.add(rst); } else { return false; } return rst; }, /** 绘制背景 * @param {Array} padding 内边距 * @param {Attrs} attrs 图形属性 * @param {Shape} backShape 背景图形 * @return {Object} 背景层对象 */ renderBack: function renderBack(padding, attrs) { var backShape = this.get('backShape'); var innerBox = this.getBBox(); // const parent = this.get('parent'); // getParent Util.merge(attrs, { x: innerBox.minX - padding[3], y: innerBox.minY - padding[0], width: innerBox.width + padding[1] + padding[3], height: innerBox.height + padding[0] + padding[2] }); if (backShape) { backShape.attr(attrs); } else { backShape = this.addShape('rect', { zIndex: -1, attrs: attrs }); } this.set('backShape', backShape); this.sort(); return backShape; }, removeChild: function removeChild(item, destroy) { if (arguments.length >= 2) { if (this.contain(item)) { item.remove(destroy); } } else { if (arguments.length === 1) { if (Util.isBoolean(item)) { destroy = item; } else { if (this.contain(item)) { item.remove(true); } return this; } } if (arguments.length === 0) { destroy = true; } Group.superclass.remove.call(this, destroy); } return this; }, /** * 向组中添加shape或者group * @param {Object} items 图形或者分组 * @return {Object} group 本尊 */ add: function add(items) { var self = this; var children = self.get('children'); if (Util.isArray(items)) { Util.each(items, function (item) { var parent = item.get('parent'); if (parent) { parent.removeChild(item, false); } self._setCfgProperty(item); }); self._cfg.children = children.concat(items); } else { var item = items; var parent = item.get('parent'); if (parent) { parent.removeChild(item, false); } self._setCfgProperty(item); children.push(item); } return self; }, _setCfgProperty: function _setCfgProperty(item) { var cfg = this._cfg; item.set('parent', this); item.set('canvas', cfg.canvas); if (cfg.timeline) { item.set('timeline', cfg.timeline); } }, contain: function contain(item) { var children = this.get('children'); return children.indexOf(item) > -1; }, getChildByIndex: function getChildByIndex(index) { var children = this.get('children'); return children[index]; }, getFirst: function getFirst() { return this.getChildByIndex(0); }, getLast: function getLast() { var lastIndex = this.get('children').length - 1; return this.getChildByIndex(lastIndex); }, getBBox: function getBBox() { var self = this; var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; var children = self.get('children'); if (children.length > 0) { Util.each(children, function (child) { if (child.get('visible')) { if (child.isGroup && child.get('children').length === 0) { return; } var _box = child.getBBox(); if (!_box) { return true; } var leftTop = [_box.minX, _box.minY, 1]; var leftBottom = [_box.minX, _box.maxY, 1]; var rightTop = [_box.maxX, _box.minY, 1]; var rightBottom = [_box.maxX, _box.maxY, 1]; child.apply(leftTop); child.apply(leftBottom); child.apply(rightTop); child.apply(rightBottom); var boxMinX = Math.min(leftTop[0], leftBottom[0], rightTop[0], rightBottom[0]); var boxMaxX = Math.max(leftTop[0], leftBottom[0], rightTop[0], rightBottom[0]); var boxMinY = Math.min(leftTop[1], leftBottom[1], rightTop[1], rightBottom[1]); var boxMaxY = Math.max(leftTop[1], leftBottom[1], rightTop[1], rightBottom[1]); if (boxMinX < minX) { minX = boxMinX; } if (boxMaxX > maxX) { maxX = boxMaxX; } if (boxMinY < minY) { minY = boxMinY; } if (boxMaxY > maxY) { maxY = boxMaxY; } } }); } else { minX = 0; maxX = 0; minY = 0; maxY = 0; } var box = { minX: minX, minY: minY, maxX: maxX, maxY: maxY }; box.x = box.minX; box.y = box.minY; box.width = box.maxX - box.minX; box.height = box.maxY - box.minY; return box; }, getCount: function getCount() { return this.get('children').length; }, sort: function sort() { var children = this.get('children'); // 稳定排序 Util.each(children, function (child, index) { child[INDEX] = index; return child; }); children.sort(getComparer(function (obj1, obj2) { return obj1.get('zIndex') - obj2.get('zIndex'); })); return this; }, findById: function findById(id) { return this.find(function (item) { return item.get('id') === id; }); }, /** * 根据查找函数查找分组或者图形 * @param {Function} fn 匹配函数 * @return {Canvas.Base} 分组或者图形 */ find: function find(fn) { if (Util.isString(fn)) { return this.findById(fn); } var children = this.get('children'); var rst = null; Util.each(children, function (item) { if (fn(item)) { rst = item; } else if (item.find) { rst = item.find(fn); } if (rst) { return false; } }); return rst; }, /** * @param {Function} fn filter mathod * @return {Array} all the matching shapes and groups */ findAll: function findAll(fn) { var children = this.get('children'); var rst = []; var childRst = []; Util.each(children, function (item) { if (fn(item)) { rst.push(item); } if (item.findAllBy) { childRst = item.findAllBy(fn); rst = rst.concat(childRst); } }); return rst; }, /** * @Deprecated * @param {Function} fn filter method * @return {Object} found shape or group */ findBy: function findBy(fn) { var children = this.get('children'); var rst = null; Util.each(children, function (item) { if (fn(item)) { rst = item; } else if (item.findBy) { rst = item.findBy(fn); } if (rst) { return false; } }); return rst; }, /** * @Deprecated * @param {Function} fn filter mathod * @return {Array} all the matching shapes and groups */ findAllBy: function findAllBy(fn) { var children = this.get('children'); var rst = []; var childRst = []; Util.each(children, function (item) { if (fn(item)) { rst.push(item); } if (item.findAllBy) { childRst = item.findAllBy(fn); rst = rst.concat(childRst); } }); return rst; }, getShape: function getShape(x, y) { var self = this; var clip = self._attrs.clip; var children = self._cfg.children; var rst; if (clip) { var v = [x, y, 1]; clip.invert(v, self.get('canvas')); // 已经在外面转换 if (clip.isPointInPath(v[0], v[1])) { rst = find(children, x, y); } } else { rst = find(children, x, y); } return rst; }, clearTotalMatrix: function clearTotalMatrix() { var m = this.get('totalMatrix'); if (m) { this.setSilent('totalMatrix', null); var children = this._cfg.children; for (var i = 0; i < children.length; i++) { var child = children[i]; child.clearTotalMatrix(); } } }, clear: function clear(delayRemove) { var children = this._cfg.children; for (var i = children.length - 1; i >= 0; i--) { children[i].remove(true, delayRemove); } this._cfg.children = []; return this; }, destroy: function destroy() { if (this.get('destroyed')) { return; } this.clear(); Group.superclass.destroy.call(this); }, clone: function clone() { var self = this; var children = self._cfg.children; var clone = new Group(); Util.each(children, function (child) { clone.add(child.clone()); }); return clone; } }); module.exports = Group; /***/ }), /* 172 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Attribute = __webpack_require__(346); var Transform = __webpack_require__(347); var Animate = __webpack_require__(348); var EventEmitter = __webpack_require__(90); var Element = function Element(cfg) { this._cfg = { zIndex: 0, capture: true, visible: true, destroyed: false }; // 配置存放地 Util.assign(this._cfg, this.getDefaultCfg(), cfg); // Element.CFG不合并,提升性能 合并默认配置,用户配置->继承默认配置->Element默认配置 this.initAttrs(this._cfg.attrs); // 初始化绘图属性 this._cfg.attrs = {}; this.initTransform(); // 初始化变换 this.init(); // 类型初始化 }; Element.CFG = { /** * 唯一标示 * @type {Number} */ id: null, /** * Z轴的层叠关系,Z值越大离用户越近 * @type {Number} */ zIndex: 0, /** * Canvas对象 * @type: {Object} */ canvas: null, /** * 父元素指针 * @type {Object} */ parent: null, /** * 用来设置当前对象是否能被捕捉 * true 能 * false 不能 * 对象默认是都可以被捕捉的, 当capture为false时,group.getShape(x, y)方法无法获得该元素 * 通过将不必要捕捉的元素的该属性设置成false, 来提高捕捉性能 * @type {Boolean} **/ capture: true, /** * 画布的上下文 * @type {Object} */ context: null, /** * 是否显示 * @type {Boolean} */ visible: true, /** * 是否被销毁 * @type: {Boolean} */ destroyed: false }; Util.augment(Element, Attribute, Transform, EventEmitter, Animate, { init: function init() { this.setSilent('animable', true); this.setSilent('animating', false); // 初始时不处于动画状态 }, getParent: function getParent() { return this._cfg.parent; }, /** * 获取默认的配置信息 * @protected * @return {Object} 默认的属性 */ getDefaultCfg: function getDefaultCfg() { return {}; }, set: function set(name, value) { if (name === 'zIndex' && this._beforeSetZIndex) { this._beforeSetZIndex(value); } if (name === 'loading' && this._beforeSetLoading) { this._beforeSetLoading(value); } this._cfg[name] = value; return this; }, // deprecated setSilent: function setSilent(name, value) { this._cfg[name] = value; }, get: function get(name) { return this._cfg[name]; }, show: function show() { this._cfg.visible = true; return this; }, hide: function hide() { this._cfg.visible = false; return this; }, remove: function remove(destroy, delayRemove) { var cfg = this._cfg; var parent = cfg.parent; var el = cfg.el; if (parent) { Util.remove(parent.get('children'), this); } if (el) { if (delayRemove) { parent && parent._cfg.tobeRemoved.push(el); } else { el.parentNode.removeChild(el); } } if (destroy || destroy === undefined) { this.destroy(); } return this; }, destroy: function destroy() { var destroyed = this.get('destroyed'); if (destroyed) { return; } this._attrs = null; this.removeEvent(); // 移除所有的事件 this._cfg = { destroyed: true }; }, toFront: function toFront() { var cfg = this._cfg; var parent = cfg.parent; if (!parent) { return; } var children = parent._cfg.children; var el = cfg.el; var index = children.indexOf(this); children.splice(index, 1); children.push(this); if (el) { el.parentNode.removeChild(el); cfg.el = null; } }, toBack: function toBack() { var cfg = this._cfg; var parent = cfg.parent; if (!parent) { return; } var children = parent._cfg.children; var el = cfg.el; var index = children.indexOf(this); children.splice(index, 1); children.unshift(this); if (el) { var parentNode = el.parentNode; parentNode.removeChild(el); parentNode.insertBefore(el, parentNode.firstChild); } }, _beforeSetZIndex: function _beforeSetZIndex(zIndex) { var parent = this._cfg.parent; this._cfg.zIndex = zIndex; if (!Util.isNil(parent)) { parent.sort(); } var el = this._cfg.el; if (el) { var children = parent._cfg.children; var index = children.indexOf(this); var parentNode = el.parentNode; parentNode.removeChild(el); if (index === children.length - 1) { parentNode.appendChild(el); } else { parentNode.insertBefore(el, parentNode.childNodes[index]); } } return zIndex; }, _setAttrs: function _setAttrs(attrs) { this.attr(attrs); return attrs; }, setZIndex: function setZIndex(zIndex) { this._cfg.zIndex = zIndex; return this._beforeSetZIndex(zIndex); }, clone: function clone() { return Util.clone(this); }, getBBox: function getBBox() {} }); module.exports = Element; /***/ }), /* 173 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var vec2 = Util.vec2; function quadraticAt(p0, p1, p2, t) { var onet = 1 - t; return onet * (onet * p0 + 2 * t * p1) + t * t * p2; } function quadraticProjectPoint(x1, y1, x2, y2, x3, y3, x, y, out) { var t; var interval = 0.005; var d = Infinity; var d1; var v1; var v2; var _t; var d2; var i; var EPSILON = 0.0001; var v0 = [x, y]; for (_t = 0; _t < 1; _t += 0.05) { v1 = [quadraticAt(x1, x2, x3, _t), quadraticAt(y1, y2, y3, _t)]; d1 = vec2.squaredDistance(v0, v1); if (d1 < d) { t = _t; d = d1; } } d = Infinity; for (i = 0; i < 32; i++) { if (interval < EPSILON) { break; } var prev = t - interval; var next = t + interval; v1 = [quadraticAt(x1, x2, x3, prev), quadraticAt(y1, y2, y3, prev)]; d1 = vec2.squaredDistance(v0, v1); if (prev >= 0 && d1 < d) { t = prev; d = d1; } else { v2 = [quadraticAt(x1, x2, x3, next), quadraticAt(y1, y2, y3, next)]; d2 = vec2.squaredDistance(v0, v2); if (next <= 1 && d2 < d) { t = next; d = d2; } else { interval *= 0.5; } } } if (out) { out.x = quadraticAt(x1, x2, x3, t); out.y = quadraticAt(y1, y2, y3, t); } return Math.sqrt(d); } function quadraticExtrema(p0, p1, p2) { var a = p0 + p2 - 2 * p1; if (Util.isNumberEqual(a, 0)) { return [0.5]; } var rst = (p0 - p1) / a; if (rst <= 1 && rst >= 0) { return [rst]; } return []; } module.exports = { at: quadraticAt, projectPoint: function projectPoint(x1, y1, x2, y2, x3, y3, x, y) { var rst = {}; quadraticProjectPoint(x1, y1, x2, y2, x3, y3, x, y, rst); return rst; }, pointDistance: quadraticProjectPoint, extrema: quadraticExtrema }; /***/ }), /* 174 */ /***/ (function(module, exports) { module.exports = { xAt: function xAt(psi, rx, ry, cx, t) { return rx * Math.cos(psi) * Math.cos(t) - ry * Math.sin(psi) * Math.sin(t) + cx; }, yAt: function yAt(psi, rx, ry, cy, t) { return rx * Math.sin(psi) * Math.cos(t) + ry * Math.cos(psi) * Math.sin(t) + cy; }, xExtrema: function xExtrema(psi, rx, ry) { return Math.atan(-ry / rx * Math.tan(psi)); }, yExtrema: function yExtrema(psi, rx, ry) { return Math.atan(ry / (rx * Math.tan(psi))); } }; /***/ }), /* 175 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Shape = __webpack_require__(9); var ArcMath = __webpack_require__(53); var Arrow = __webpack_require__(54); function _getArcX(x, radius, angle) { return x + radius * Math.cos(angle); } function _getArcY(y, radius, angle) { return y + radius * Math.sin(angle); } var Arc = function Arc(cfg) { Arc.superclass.constructor.call(this, cfg); }; Arc.ATTRS = { x: 0, y: 0, r: 0, startAngle: 0, endAngle: 0, clockwise: false, lineWidth: 1, startArrow: false, endArrow: false }; Util.extend(Arc, Shape); Util.augment(Arc, { canStroke: true, type: 'arc', getDefaultAttrs: function getDefaultAttrs() { return { x: 0, y: 0, r: 0, startAngle: 0, endAngle: 0, clockwise: false, lineWidth: 1, startArrow: false, endArrow: false }; }, calculateBox: function calculateBox() { var attrs = this._attrs; var x = attrs.x, y = attrs.y, r = attrs.r, startAngle = attrs.startAngle, endAngle = attrs.endAngle, clockwise = attrs.clockwise; var lineWidth = this.getHitLineWidth(); var halfWidth = lineWidth / 2; var box = ArcMath.box(x, y, r, startAngle, endAngle, clockwise); box.minX -= halfWidth; box.minY -= halfWidth; box.maxX += halfWidth; box.maxY += halfWidth; return box; }, getStartTangent: function getStartTangent() { var attrs = this._attrs; var x = attrs.x, y = attrs.y, startAngle = attrs.startAngle, r = attrs.r, clockwise = attrs.clockwise; var diff = Math.PI / 180; if (clockwise) { diff *= -1; } var result = []; var x1 = _getArcX(x, r, startAngle + diff); var y1 = _getArcY(y, r, startAngle + diff); var x2 = _getArcX(x, r, startAngle); var y2 = _getArcY(y, r, startAngle); result.push([x1, y1]); result.push([x2, y2]); return result; }, getEndTangent: function getEndTangent() { var attrs = this._attrs; var x = attrs.x, y = attrs.y, endAngle = attrs.endAngle, r = attrs.r, clockwise = attrs.clockwise; var diff = Math.PI / 180; var result = []; if (clockwise) { diff *= -1; } var x1 = _getArcX(x, r, endAngle + diff); var y1 = _getArcY(y, r, endAngle + diff); var x2 = _getArcX(x, r, endAngle); var y2 = _getArcY(y, r, endAngle); result.push([x2, y2]); result.push([x1, y1]); return result; }, createPath: function createPath(context) { var attrs = this._attrs; var x = attrs.x, y = attrs.y, r = attrs.r, startAngle = attrs.startAngle, endAngle = attrs.endAngle, clockwise = attrs.clockwise; context = context || self.get('context'); context.beginPath(); context.arc(x, y, r, startAngle, endAngle, clockwise); }, afterPath: function afterPath(context) { var attrs = this._attrs; context = context || this.get('context'); if (attrs.startArrow) { var startPoints = this.getStartTangent(); Arrow.addStartArrow(context, attrs, startPoints[0][0], startPoints[0][1], startPoints[1][0], startPoints[1][1]); } if (attrs.endArrow) { var endPoints = this.getEndTangent(); Arrow.addEndArrow(context, attrs, endPoints[0][0], endPoints[0][1], endPoints[1][0], endPoints[1][1]); } } }); module.exports = Arc; /***/ }), /* 176 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Shape = __webpack_require__(9); var Circle = function Circle(cfg) { Circle.superclass.constructor.call(this, cfg); }; Circle.ATTRS = { x: 0, y: 0, r: 0, lineWidth: 1 }; Util.extend(Circle, Shape); Util.augment(Circle, { canFill: true, canStroke: true, type: 'circle', getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1 }; }, calculateBox: function calculateBox() { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var r = attrs.r; var lineWidth = this.getHitLineWidth(); var halfWidth = lineWidth / 2 + r; return { minX: cx - halfWidth, minY: cy - halfWidth, maxX: cx + halfWidth, maxY: cy + halfWidth }; }, createPath: function createPath(context) { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var r = attrs.r; context.beginPath(); context.arc(cx, cy, r, 0, Math.PI * 2, false); context.closePath(); } }); module.exports = Circle; /***/ }), /* 177 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Shape = __webpack_require__(9); var Dom = function Dom(cfg) { Dom.superclass.constructor.call(this, cfg); }; Util.extend(Dom, Shape); Util.augment(Dom, { canFill: true, canStroke: true, type: 'dom', calculateBox: function calculateBox() { var self = this; var attrs = self._attrs; var x = attrs.x; var y = attrs.y; var width = attrs.width; var height = attrs.height; var lineWidth = this.getHitLineWidth(); var halfWidth = lineWidth / 2; return { minX: x - halfWidth, minY: y - halfWidth, maxX: x + width + halfWidth, maxY: y + height + halfWidth }; } }); module.exports = Dom; /***/ }), /* 178 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Shape = __webpack_require__(9); var Ellipse = function Ellipse(cfg) { Ellipse.superclass.constructor.call(this, cfg); }; Ellipse.ATTRS = { x: 0, y: 0, rx: 1, ry: 1, lineWidth: 1 }; Util.extend(Ellipse, Shape); Util.augment(Ellipse, { canFill: true, canStroke: true, type: 'ellipse', getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1 }; }, calculateBox: function calculateBox() { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var rx = attrs.rx; var ry = attrs.ry; var lineWidth = this.getHitLineWidth(); var halfXWidth = rx + lineWidth / 2; var halfYWidth = ry + lineWidth / 2; return { minX: cx - halfXWidth, minY: cy - halfYWidth, maxX: cx + halfXWidth, maxY: cy + halfYWidth }; }, createPath: function createPath(context) { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var rx = attrs.rx; var ry = attrs.ry; context = context || self.get('context'); var r = rx > ry ? rx : ry; var scaleX = rx > ry ? 1 : rx / ry; var scaleY = rx > ry ? ry / rx : 1; var m = [1, 0, 0, 0, 1, 0, 0, 0, 1]; Util.mat3.scale(m, m, [scaleX, scaleY]); Util.mat3.translate(m, m, [cx, cy]); context.beginPath(); context.save(); context.transform(m[0], m[1], m[3], m[4], m[6], m[7]); context.arc(0, 0, r, 0, Math.PI * 2); context.restore(); context.closePath(); } }); module.exports = Ellipse; /***/ }), /* 179 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Shape = __webpack_require__(9); var ArcMath = __webpack_require__(53); var Fan = function Fan(cfg) { Fan.superclass.constructor.call(this, cfg); }; Fan.ATTRS = { x: 0, y: 0, rs: 0, re: 0, startAngle: 0, endAngle: 0, clockwise: false, lineWidth: 1 }; Util.extend(Fan, Shape); Util.augment(Fan, { canFill: true, canStroke: true, type: 'fan', getDefaultAttrs: function getDefaultAttrs() { return { clockwise: false, lineWidth: 1, rs: 0, re: 0 }; }, calculateBox: function calculateBox() { var self = this; var attrs = self._attrs; var cx = attrs.x; var cy = attrs.y; var rs = attrs.rs; var re = attrs.re; var startAngle = attrs.startAngle; var endAngle = attrs.endAngle; var clockwise = attrs.clockwise; var lineWidth = this.getHitLineWidth(); var boxs = ArcMath.box(cx, cy, rs, startAngle, endAngle, clockwise); var boxe = ArcMath.box(cx, cy, re, startAngle, endAngle, clockwise); var minX = Math.min(boxs.minX, boxe.minX); var minY = Math.min(boxs.minY, boxe.minY); var maxX = Math.max(boxs.maxX, boxe.maxX); var maxY = Math.max(boxs.maxY, boxe.maxY); var halfWidth = lineWidth / 2; return { minX: minX - halfWidth, minY: minY - halfWidth, maxX: maxX + halfWidth, maxY: maxY + halfWidth }; }, createPath: function createPath(context) { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var rs = attrs.rs; var re = attrs.re; var startAngle = attrs.startAngle; var endAngle = attrs.endAngle; var clockwise = attrs.clockwise; var ssp = { x: Math.cos(startAngle) * rs + cx, y: Math.sin(startAngle) * rs + cy }; var sep = { x: Math.cos(startAngle) * re + cx, y: Math.sin(startAngle) * re + cy }; var esp = { x: Math.cos(endAngle) * rs + cx, y: Math.sin(endAngle) * rs + cy }; context = context || self.get('context'); context.beginPath(); context.moveTo(ssp.x, ssp.y); context.lineTo(sep.x, sep.y); context.arc(cx, cy, re, startAngle, endAngle, clockwise); context.lineTo(esp.x, esp.y); context.arc(cx, cy, rs, endAngle, startAngle, !clockwise); context.closePath(); } }); module.exports = Fan; /***/ }), /* 180 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Shape = __webpack_require__(9); var CImage = function CImage(cfg) { CImage.superclass.constructor.call(this, cfg); }; CImage.ATTRS = { x: 0, y: 0, img: undefined, width: 0, height: 0, sx: null, sy: null, swidth: null, sheight: null }; Util.extend(CImage, Shape); Util.augment(CImage, { type: 'image', isHitBox: function isHitBox() { return false; }, calculateBox: function calculateBox() { var attrs = this._attrs; if (!this._cfg.attrs || this._cfg.attrs.img !== attrs.img) { this._setAttrImg(); } var x = attrs.x; var y = attrs.y; var width = attrs.width; var height = attrs.height; return { minX: x, minY: y, maxX: x + width, maxY: y + height }; }, _beforeSetLoading: function _beforeSetLoading(loading) { var canvas = this.get('canvas'); if (loading === false && this.get('toDraw') === true) { this._cfg.loading = false; canvas.draw(); } return loading; }, _setAttrImg: function _setAttrImg() { var self = this; var attrs = self._attrs; var img = attrs.img; if (Util.isString(img)) { var image = new Image(); image.onload = function () { if (self.get('destroyed')) return false; self.attr('imgSrc', img); self.attr('img', image); var callback = self.get('callback'); if (callback) { callback.call(self); } self.set('loading', false); }; image.src = img; image.crossOrigin = 'Anonymous'; self.set('loading', true); } else if (img instanceof Image) { if (!attrs.width) { self.attr('width', img.width); } if (!attrs.height) { self.attr('height', img.height); } return img; } else if (img instanceof HTMLElement && Util.isString(img.nodeName) && img.nodeName.toUpperCase() === 'CANVAS') { if (!attrs.width) { self.attr('width', Number(img.getAttribute('width'))); } if (!attrs.height) { self.attr('height', Number(img.getAttribute('height'))); } return img; } else if (img instanceof ImageData) { if (!attrs.width) { self.attr('width', img.width); } if (!attrs.height) { self.attr('height', img.height); } return img; } else { return null; } }, drawInner: function drawInner(context) { if (this._cfg.hasUpdate) { this._setAttrImg(); } if (this.get('loading')) { this.set('toDraw', true); return; } this._drawImage(context); this._cfg.hasUpdate = false; }, _drawImage: function _drawImage(context) { var attrs = this._attrs; var x = attrs.x; var y = attrs.y; var image = attrs.img; var width = attrs.width; var height = attrs.height; var sx = attrs.sx; var sy = attrs.sy; var swidth = attrs.swidth; var sheight = attrs.sheight; this.set('toDraw', false); var img = image; if (img instanceof ImageData) { img = new Image(); img.src = image; } if (img instanceof Image || img instanceof HTMLElement && Util.isString(img.nodeName) && img.nodeName.toUpperCase() === 'CANVAS') { if (Util.isNil(sx) || Util.isNil(sy) || Util.isNil(swidth) || Util.isNil(sheight)) { context.drawImage(img, x, y, width, height); return; } if (!Util.isNil(sx) && !Util.isNil(sy) && !Util.isNil(swidth) && !Util.isNil(sheight)) { context.drawImage(img, sx, sy, swidth, sheight, x, y, width, height); return; } } return; } }); module.exports = CImage; /***/ }), /* 181 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Shape = __webpack_require__(9); var Arrow = __webpack_require__(54); var LineMath = __webpack_require__(52); var Line = function Line(cfg) { Line.superclass.constructor.call(this, cfg); }; Line.ATTRS = { x1: 0, y1: 0, x2: 0, y2: 0, lineWidth: 1, startArrow: false, endArrow: false }; Util.extend(Line, Shape); Util.augment(Line, { canStroke: true, type: 'line', getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1, startArrow: false, endArrow: false }; }, calculateBox: function calculateBox() { var attrs = this._attrs; var x1 = attrs.x1, y1 = attrs.y1, x2 = attrs.x2, y2 = attrs.y2; var lineWidth = this.getHitLineWidth(); return LineMath.box(x1, y1, x2, y2, lineWidth); }, createPath: function createPath(context) { var attrs = this._attrs; var x1 = attrs.x1, y1 = attrs.y1, x2 = attrs.x2, y2 = attrs.y2; context = context || self.get('context'); context.beginPath(); context.moveTo(x1, y1); context.lineTo(x2, y2); }, afterPath: function afterPath(context) { var attrs = this._attrs; var x1 = attrs.x1, y1 = attrs.y1, x2 = attrs.x2, y2 = attrs.y2; context = context || this.get('context'); if (attrs.startArrow) { Arrow.addStartArrow(context, attrs, x2, y2, x1, y1); } if (attrs.endArrow) { Arrow.addEndArrow(context, attrs, x1, y1, x2, y2); } }, getPoint: function getPoint(t) { var attrs = this._attrs; return { x: LineMath.at(attrs.x1, attrs.x2, t), y: LineMath.at(attrs.y1, attrs.y2, t) }; } }); module.exports = Line; /***/ }), /* 182 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Shape = __webpack_require__(9); var PathSegment = __webpack_require__(55); var Format = __webpack_require__(37); var Arrow = __webpack_require__(54); var PathUtil = __webpack_require__(96); var CubicMath = __webpack_require__(94); var Path = function Path(cfg) { Path.superclass.constructor.call(this, cfg); }; Path.ATTRS = { path: null, lineWidth: 1, startArrow: false, endArrow: false }; Util.extend(Path, Shape); Util.augment(Path, { canFill: true, canStroke: true, type: 'path', getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1, startArrow: false, endArrow: false }; }, _afterSetAttrPath: function _afterSetAttrPath(path) { var self = this; if (Util.isNil(path)) { self.setSilent('segments', null); self.setSilent('box', undefined); return; } var pathArray = Format.parsePath(path); var preSegment; var segments = []; if (!Util.isArray(pathArray) || pathArray.length === 0 || pathArray[0][0] !== 'M' && pathArray[0][0] !== 'm') { return; } var count = pathArray.length; for (var i = 0; i < pathArray.length; i++) { var item = pathArray[i]; preSegment = new PathSegment(item, preSegment, i === count - 1); segments.push(preSegment); } self.setSilent('segments', segments); self.setSilent('tCache', null); self.setSilent('box', null); }, calculateBox: function calculateBox() { var self = this; var segments = self.get('segments'); if (!segments) { return null; } var lineWidth = this.getHitLineWidth(); var minX = Infinity; var maxX = -Infinity; var minY = Infinity; var maxY = -Infinity; Util.each(segments, function (segment) { segment.getBBox(lineWidth); var box = segment.box; if (box) { if (box.minX < minX) { minX = box.minX; } if (box.maxX > maxX) { maxX = box.maxX; } if (box.minY < minY) { minY = box.minY; } if (box.maxY > maxY) { maxY = box.maxY; } } }); if (minX === Infinity || minY === Infinity) { return { minX: 0, minY: 0, maxX: 0, maxY: 0 }; } return { minX: minX, minY: minY, maxX: maxX, maxY: maxY }; }, _setTcache: function _setTcache() { var totalLength = 0; var tempLength = 0; var tCache = []; var segmentT; var segmentL; var segmentN; var l; var curve = this._cfg.curve; if (!curve) { return; } Util.each(curve, function (segment, i) { segmentN = curve[i + 1]; l = segment.length; if (segmentN) { totalLength += CubicMath.len(segment[l - 2], segment[l - 1], segmentN[1], segmentN[2], segmentN[3], segmentN[4], segmentN[5], segmentN[6]); } }); Util.each(curve, function (segment, i) { segmentN = curve[i + 1]; l = segment.length; if (segmentN) { segmentT = []; segmentT[0] = tempLength / totalLength; segmentL = CubicMath.len(segment[l - 2], segment[l - 1], segmentN[1], segmentN[2], segmentN[3], segmentN[4], segmentN[5], segmentN[6]); tempLength += segmentL; segmentT[1] = tempLength / totalLength; tCache.push(segmentT); } }); this._cfg.tCache = tCache; }, _calculateCurve: function _calculateCurve() { var self = this; var attrs = self._attrs; var path = attrs.path; this._cfg.curve = PathUtil.pathTocurve(path); }, getStartTangent: function getStartTangent() { var segments = this.get('segments'); var startPoint, endPoint, tangent, result; if (segments.length > 1) { startPoint = segments[0].endPoint; endPoint = segments[1].endPoint; tangent = segments[1].startTangent; result = []; if (Util.isFunction(tangent)) { var v = tangent(); result.push([startPoint.x - v[0], startPoint.y - v[1]]); result.push([startPoint.x, startPoint.y]); } else { result.push([endPoint.x, endPoint.y]); result.push([startPoint.x, startPoint.y]); } } return result; }, getEndTangent: function getEndTangent() { var segments = this.get('segments'); var segmentsLen = segments.length; var startPoint, endPoint, tangent, result; if (segmentsLen > 1) { startPoint = segments[segmentsLen - 2].endPoint; endPoint = segments[segmentsLen - 1].endPoint; tangent = segments[segmentsLen - 1].endTangent; result = []; if (Util.isFunction(tangent)) { var v = tangent(); result.push([endPoint.x - v[0], endPoint.y - v[1]]); result.push([endPoint.x, endPoint.y]); } else { result.push([startPoint.x, startPoint.y]); result.push([endPoint.x, endPoint.y]); } } return result; }, getPoint: function getPoint(t) { var tCache = this._cfg.tCache; var subt; var index; if (!tCache) { this._calculateCurve(); this._setTcache(); tCache = this._cfg.tCache; } var curve = this._cfg.curve; if (!tCache) { if (curve) { return { x: curve[0][1], y: curve[0][2] }; } return null; } Util.each(tCache, function (v, i) { if (t >= v[0] && t <= v[1]) { subt = (t - v[0]) / (v[1] - v[0]); index = i; } }); var seg = curve[index]; if (Util.isNil(seg) || Util.isNil(index)) { return null; } var l = seg.length; var nextSeg = curve[index + 1]; return { x: CubicMath.at(seg[l - 2], nextSeg[1], nextSeg[3], nextSeg[5], 1 - subt), y: CubicMath.at(seg[l - 1], nextSeg[2], nextSeg[4], nextSeg[6], 1 - subt) }; }, createPath: function createPath(context) { var self = this; var segments = self.get('segments'); if (!Util.isArray(segments)) { return; } context = context || self.get('context'); context.beginPath(); var segmentsLen = segments.length; for (var i = 0; i < segmentsLen; i++) { segments[i].draw(context); } }, afterPath: function afterPath(context) { var self = this; var attrs = self._attrs; var segments = self.get('segments'); var path = attrs.path; context = context || self.get('context'); if (!Util.isArray(segments)) { return; } if (segments.length === 1) { return; } if (!attrs.startArrow && !attrs.endArrow) { return; } if (path[path.length - 1] === 'z' || path[path.length - 1] === 'Z' || attrs.fill) { // 闭合路径不绘制箭头 return; } var startPoints = self.getStartTangent(); Arrow.addStartArrow(context, attrs, startPoints[0][0], startPoints[0][1], startPoints[1][0], startPoints[1][1]); var endPoints = self.getEndTangent(); Arrow.addEndArrow(context, attrs, endPoints[0][0], endPoints[0][1], endPoints[1][0], endPoints[1][1]); } }); module.exports = Path; /***/ }), /* 183 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Shape = __webpack_require__(9); var Polygon = function Polygon(cfg) { Polygon.superclass.constructor.call(this, cfg); }; Polygon.ATTRS = { points: null, lineWidth: 1 }; Util.extend(Polygon, Shape); Util.augment(Polygon, { canFill: true, canStroke: true, type: 'polygon', getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1 }; }, calculateBox: function calculateBox() { var self = this; var attrs = self._attrs; var points = attrs.points; var lineWidth = this.getHitLineWidth(); if (!points || points.length === 0) { return null; } var minX = Infinity; var minY = Infinity; var maxX = -Infinity; var maxY = -Infinity; Util.each(points, function (point) { var x = point[0]; var y = point[1]; if (x < minX) { minX = x; } if (x > maxX) { maxX = x; } if (y < minY) { minY = y; } if (y > maxY) { maxY = y; } }); var halfWidth = lineWidth / 2; return { minX: minX - halfWidth, minY: minY - halfWidth, maxX: maxX + halfWidth, maxY: maxY + halfWidth }; }, createPath: function createPath(context) { var self = this; var attrs = self._attrs; var points = attrs.points; if (points.length < 2) { return; } context = context || self.get('context'); context.beginPath(); Util.each(points, function (point, index) { if (index === 0) { context.moveTo(point[0], point[1]); } else { context.lineTo(point[0], point[1]); } }); context.closePath(); } }); module.exports = Polygon; /***/ }), /* 184 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Shape = __webpack_require__(9); var Arrow = __webpack_require__(54); var LineMath = __webpack_require__(52); var Polyline = function Polyline(cfg) { Polyline.superclass.constructor.call(this, cfg); }; Polyline.ATTRS = { points: null, lineWidth: 1, startArrow: false, endArrow: false, tCache: null }; Util.extend(Polyline, Shape); Util.augment(Polyline, { canStroke: true, type: 'polyline', tCache: null, // 缓存各点的t getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1, startArrow: false, endArrow: false }; }, calculateBox: function calculateBox() { var self = this; var attrs = self._attrs; var lineWidth = this.getHitLineWidth(); var points = attrs.points; if (!points || points.length === 0) { return null; } var minX = Infinity; var minY = Infinity; var maxX = -Infinity; var maxY = -Infinity; Util.each(points, function (point) { var x = point[0]; var y = point[1]; if (x < minX) { minX = x; } if (x > maxX) { maxX = x; } if (y < minY) { minY = y; } if (y > maxY) { maxY = y; } }); var halfWidth = lineWidth / 2; return { minX: minX - halfWidth, minY: minY - halfWidth, maxX: maxX + halfWidth, maxY: maxY + halfWidth }; }, _setTcache: function _setTcache() { var self = this; var attrs = self._attrs; var points = attrs.points; var totalLength = 0; var tempLength = 0; var tCache = []; var segmentT; var segmentL; if (!points || points.length === 0) { return; } Util.each(points, function (p, i) { if (points[i + 1]) { totalLength += LineMath.len(p[0], p[1], points[i + 1][0], points[i + 1][1]); } }); if (totalLength <= 0) { return; } Util.each(points, function (p, i) { if (points[i + 1]) { segmentT = []; segmentT[0] = tempLength / totalLength; segmentL = LineMath.len(p[0], p[1], points[i + 1][0], points[i + 1][1]); tempLength += segmentL; segmentT[1] = tempLength / totalLength; tCache.push(segmentT); } }); this.tCache = tCache; }, createPath: function createPath(context) { var self = this; var attrs = self._attrs; var points = attrs.points; var l; var i; if (points.length < 2) { return; } context = context || self.get('context'); context.beginPath(); context.moveTo(points[0][0], points[0][1]); for (i = 1, l = points.length - 1; i < l; i++) { context.lineTo(points[i][0], points[i][1]); } context.lineTo(points[l][0], points[l][1]); }, getStartTangent: function getStartTangent() { var points = this.__attrs.points; var result = []; result.push([points[1][0], points[1][1]]); result.push([points[0][0], points[0][1]]); return result; }, getEndTangent: function getEndTangent() { var points = this.__attrs.points; var l = points.length - 1; var result = []; result.push([points[l - 1][0], points[l - 1][1]]); result.push([points[l][0], points[l][1]]); return result; }, afterPath: function afterPath(context) { var self = this; var attrs = self._attrs; var points = attrs.points; var l = points.length - 1; context = context || self.get('context'); if (attrs.startArrow) { Arrow.addStartArrow(context, attrs, points[1][0], points[1][1], points[0][0], points[0][1]); } if (attrs.endArrow) { Arrow.addEndArrow(context, attrs, points[l - 1][0], points[l - 1][1], points[l][0], points[l][1]); } }, getPoint: function getPoint(t) { var attrs = this._attrs; var points = attrs.points; var tCache = this.tCache; var subt; var index; if (!tCache) { this._setTcache(); tCache = this.tCache; } Util.each(tCache, function (v, i) { if (t >= v[0] && t <= v[1]) { subt = (t - v[0]) / (v[1] - v[0]); index = i; } }); return { x: LineMath.at(points[index][0], points[index + 1][0], subt), y: LineMath.at(points[index][1], points[index + 1][1], subt) }; } }); module.exports = Polyline; /***/ }), /* 185 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var _require = __webpack_require__(37), parseRadius = _require.parseRadius; var Shape = __webpack_require__(9); var Rect = function Rect(cfg) { Rect.superclass.constructor.call(this, cfg); }; Rect.ATTRS = { x: 0, y: 0, width: 0, height: 0, radius: 0, lineWidth: 1 }; Util.extend(Rect, Shape); Util.augment(Rect, { canFill: true, canStroke: true, type: 'rect', getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1, radius: 0 }; }, calculateBox: function calculateBox() { var self = this; var attrs = self._attrs; var x = attrs.x; var y = attrs.y; var width = attrs.width; var height = attrs.height; var lineWidth = this.getHitLineWidth(); var halfWidth = lineWidth / 2; return { minX: x - halfWidth, minY: y - halfWidth, maxX: x + width + halfWidth, maxY: y + height + halfWidth }; }, createPath: function createPath(context) { var self = this; var attrs = self._attrs; var x = attrs.x; var y = attrs.y; var width = attrs.width; var height = attrs.height; var radius = attrs.radius; context = context || self.get('context'); context.beginPath(); if (radius === 0) { // 改成原生的rect方法 context.rect(x, y, width, height); } else { var r = parseRadius(radius); context.moveTo(x + r.r1, y); context.lineTo(x + width - r.r2, y); r.r2 !== 0 && context.arc(x + width - r.r2, y + r.r2, r.r2, -Math.PI / 2, 0); context.lineTo(x + width, y + height - r.r3); r.r3 !== 0 && context.arc(x + width - r.r3, y + height - r.r3, r.r3, 0, Math.PI / 2); context.lineTo(x + r.r4, y + height); r.r4 !== 0 && context.arc(x + r.r4, y + height - r.r4, r.r4, Math.PI / 2, Math.PI); context.lineTo(x, y + r.r1); r.r1 !== 0 && context.arc(x + r.r1, y + r.r1, r.r1, Math.PI, Math.PI * 1.5); context.closePath(); } } }); module.exports = Rect; /***/ }), /* 186 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Shape = __webpack_require__(9); var CText = function CText(cfg) { CText.superclass.constructor.call(this, cfg); }; CText.ATTRS = { x: 0, y: 0, text: null, fontSize: 12, fontFamily: 'sans-serif', fontStyle: 'normal', fontWeight: 'normal', fontVariant: 'normal', textAlign: 'start', textBaseline: 'bottom', lineHeight: null, textArr: null }; Util.extend(CText, Shape); Util.augment(CText, { canFill: true, canStroke: true, type: 'text', getDefaultAttrs: function getDefaultAttrs() { return { lineWidth: 1, lineCount: 1, fontSize: 12, fontFamily: 'sans-serif', fontStyle: 'normal', fontWeight: 'normal', fontVariant: 'normal', textAlign: 'start', textBaseline: 'bottom' }; }, initTransform: function initTransform() { var fontSize = this._attrs.fontSize; if (fontSize && +fontSize < 12) { // 小于 12 像素的文本进行 scale 处理 this.transform([['t', -1 * this._attrs.x, -1 * this._attrs.y], ['s', +fontSize / 12, +fontSize / 12], ['t', this._attrs.x, this._attrs.y]]); } }, _assembleFont: function _assembleFont() { // var self = this; var attrs = this._attrs; var fontSize = attrs.fontSize; var fontFamily = attrs.fontFamily; var fontWeight = attrs.fontWeight; var fontStyle = attrs.fontStyle; // self.attr('fontStyle'); var fontVariant = attrs.fontVariant; // self.attr('fontVariant'); // self.attr('font', [fontStyle, fontVariant, fontWeight, fontSize + 'px', fontFamily].join(' ')); attrs.font = [fontStyle, fontVariant, fontWeight, fontSize + 'px', fontFamily].join(' '); }, _setAttrText: function _setAttrText() { var attrs = this._attrs; var text = attrs.text; var textArr = null; if (Util.isString(text) && text.indexOf('\n') !== -1) { textArr = text.split('\n'); var lineCount = textArr.length; attrs.lineCount = lineCount; } attrs.textArr = textArr; }, _getTextHeight: function _getTextHeight() { var attrs = this._attrs; var lineCount = attrs.lineCount; var fontSize = attrs.fontSize * 1; if (lineCount > 1) { var spaceingY = this._getSpaceingY(); return fontSize * lineCount + spaceingY * (lineCount - 1); } return fontSize; }, isHitBox: function isHitBox() { return false; }, calculateBox: function calculateBox() { var self = this; var attrs = self._attrs; var cfg = this._cfg; if (!cfg.attrs || cfg.hasUpdate) { this._assembleFont(); this._setAttrText(); } if (!attrs.textArr) { this._setAttrText(); } var x = attrs.x; var y = attrs.y; var width = self.measureText(); // attrs.width if (!width) { // 如果width不存在,四点共其实点 return { minX: x, minY: y, maxX: x, maxY: y }; } var height = self._getTextHeight(); // attrs.height var textAlign = attrs.textAlign; var textBaseline = attrs.textBaseline; var lineWidth = self.getHitLineWidth(); var point = { x: x, y: y - height }; if (textAlign) { if (textAlign === 'end' || textAlign === 'right') { point.x -= width; } else if (textAlign === 'center') { point.x -= width / 2; } } if (textBaseline) { if (textBaseline === 'top') { point.y += height; } else if (textBaseline === 'middle') { point.y += height / 2; } } this.set('startPoint', point); var halfWidth = lineWidth / 2; return { minX: point.x - halfWidth, minY: point.y - halfWidth, maxX: point.x + width + halfWidth, maxY: point.y + height + halfWidth }; }, _getSpaceingY: function _getSpaceingY() { var attrs = this._attrs; var lineHeight = attrs.lineHeight; var fontSize = attrs.fontSize * 1; return lineHeight ? lineHeight - fontSize : fontSize * 0.14; }, drawInner: function drawInner(context) { var self = this; var attrs = self._attrs; var cfg = this._cfg; if (!cfg.attrs || cfg.hasUpdate) { this._assembleFont(); this._setAttrText(); } context.font = attrs.font; var text = attrs.text; if (!text) { return; } var textArr = attrs.textArr; var x = attrs.x; var y = attrs.y; context.beginPath(); if (self.hasStroke()) { var strokeOpacity = attrs.strokeOpacity; if (!Util.isNil(strokeOpacity) && strokeOpacity !== 1) { context.globalAlpha = strokeOpacity; } if (textArr) { self._drawTextArr(context, false); } else { context.strokeText(text, x, y); } context.globalAlpha = 1; } if (self.hasFill()) { var fillOpacity = attrs.fillOpacity; if (!Util.isNil(fillOpacity) && fillOpacity !== 1) { context.globalAlpha = fillOpacity; } if (textArr) { self._drawTextArr(context, true); } else { context.fillText(text, x, y); } } cfg.hasUpdate = false; }, _drawTextArr: function _drawTextArr(context, fill) { var textArr = this._attrs.textArr; var textBaseline = this._attrs.textBaseline; var fontSize = this._attrs.fontSize * 1; var spaceingY = this._getSpaceingY(); var x = this._attrs.x; var y = this._attrs.y; var box = this.getBBox(); var height = box.maxY - box.minY; var subY; Util.each(textArr, function (subText, index) { subY = y + index * (spaceingY + fontSize) - height + fontSize; // bottom; if (textBaseline === 'middle') subY += height - fontSize - (height - fontSize) / 2; if (textBaseline === 'top') subY += height - fontSize; if (fill) { context.fillText(subText, x, subY); } else { context.strokeText(subText, x, subY); } }); }, measureText: function measureText() { var self = this; var attrs = self._attrs; var text = attrs.text; var font = attrs.font; var textArr = attrs.textArr; var measureWidth; var width = 0; if (Util.isNil(text)) return undefined; var context = document.createElement('canvas').getContext('2d'); context.save(); context.font = font; if (textArr) { Util.each(textArr, function (subText) { measureWidth = context.measureText(subText).width; if (width < measureWidth) { width = measureWidth; } context.restore(); }); } else { width = context.measureText(text).width; context.restore(); } return width; } }); module.exports = CText; /***/ }), /* 187 */ /***/ (function(module, exports, __webpack_require__) { var _require = __webpack_require__(51), Group = _require.Group; var Util = __webpack_require__(4); var Grid = function Grid(cfg) { Grid.superclass.constructor.call(this, cfg); }; Util.extend(Grid, Group); Util.augment(Grid, { getDefaultCfg: function getDefaultCfg() { // const cfg = super.getDefaultCfg(); return { zIndex: 1, /** * 栅格线的类型 * - line 不封闭的线 * - polygon 封闭的多边形 * @type {String} */ type: 'line', /** * 线的样式配置 * @type {Object} */ lineStyle: null, /** * 线集合的配置 * @type {Array} */ items: null, /** * 为网格设置交替的背景色,指定一个值则先渲染奇数层,两个值则交替渲染 * @type {String | Array} */ alternateColor: null, matrix: null, /** * 是否隐藏第一条网格线,默认为 false * @type {Boolean} */ hideFirstLine: false, /** * 是否隐藏最后一条网格线,默认为 false * @type {Boolean} */ hideLastLine: false, /** * 0基线不在轴线上时,是否强调0基线 * @type {Boolean} */ hightLightZero: false, /** * 0基线样式 * @type {Object} */ zeroLineStyle: { stroke: '#595959', lineDash: [0, 0] } }; }, _renderUI: function _renderUI() { Grid.superclass._renderUI.call(this); this._drawLines(); }, _drawLines: function _drawLines() { var self = this; var lineStyle = self.get('lineStyle'); var items = self.get('items'); if (items && items.length) { self._precessItems(items); self._drawGridLines(items, lineStyle); } }, _precessItems: function _precessItems(items) { var self = this; var preItem; Util.each(items, function (item, index) { if (preItem && self.get('alternateColor')) { self._drawAlternativeBg(item, preItem, index); } preItem = item; }); }, _drawGridLines: function _drawGridLines(items, lineStyle) { var self = this; var type = this.get('type'); var gridLine; var path; var cfg; var points; var itemsLength = items.length; if (type === 'line' || type === 'polygon') { Util.each(items, function (item, idx) { if (self.get('hideFirstLine') && idx === 0) { // 不展示第一条网格线 return; } if (self.get('hideLastLine') && idx === itemsLength - 1) { // 不展示最后一条网格线 return; } points = item.points; path = []; if (type === 'line') { path.push(['M', points[0].x, points[0].y]); path.push(['L', points[points.length - 1].x, points[points.length - 1].y]); } else { Util.each(points, function (point, index) { if (index === 0) { path.push(['M', point.x, point.y]); } else { path.push(['L', point.x, point.y]); } }); } if (self._drawZeroLine(type, idx)) { cfg = Util.mix({}, self.get('zeroLineStyle'), { path: path }); } else { cfg = Util.mix({}, lineStyle, { path: path }); } gridLine = self.addShape('path', { attrs: cfg }); gridLine.name = 'axis-grid'; gridLine._id = item._id; gridLine.set('coord', self.get('coord')); self.get('appendInfo') && gridLine.setSilent('appendInfo', self.get('appendInfo')); }); } else { Util.each(items, function (item, idx) { if (self.get('hideFirstLine') && idx === 0) { // 不展示第一条网格线 return; } if (self.get('hideLastLine') && idx === itemsLength - 1) { // 不展示最后一条网格线 return; } points = item.points; path = []; Util.each(points, function (point, index) { var radius = point.radius; if (index === 0) { path.push(['M', point.x, point.y]); } else { path.push(['A', radius, radius, 0, 0, point.flag, point.x, point.y]); } }); cfg = Util.mix({}, lineStyle, { path: path }); gridLine = self.addShape('path', { attrs: cfg }); gridLine.name = 'axis-grid'; gridLine._id = item._id; gridLine.set('coord', self.get('coord')); self.get('appendInfo') && gridLine.setSilent('appendInfo', self.get('appendInfo')); }); } }, _drawZeroLine: function _drawZeroLine(type, idx) { var self = this; var tickValues = self.get('tickValues'); if (type === 'line' && tickValues) { if (tickValues[idx] === 0 && self.get('hightLightZero')) { return true; } } return false; }, _drawAlternativeBg: function _drawAlternativeBg(item, preItem, index) { var self = this; var alternateColor = self.get('alternateColor'); var attrs; var oddColor; var evenColor; if (Util.isString(alternateColor)) { oddColor = alternateColor; } else if (Util.isArray(alternateColor)) { oddColor = alternateColor[0]; evenColor = alternateColor[1]; } if (index % 2 === 0) { if (evenColor) { attrs = self._getBackItem(preItem.points, item.points, evenColor); } } else if (oddColor) { attrs = self._getBackItem(preItem.points, item.points, oddColor); } var shape = self.addShape('Path', { attrs: attrs }); shape.name = 'axis-grid-rect'; shape._id = item._id && item._id.replace('grid', 'grid-rect'); shape.set('coord', self.get('coord')); self.get('appendInfo') && shape.setSilent('appendInfo', self.get('appendInfo')); }, _getBackItem: function _getBackItem(start, end, bgColor) { var path = []; var type = this.get('type'); if (type === 'line') { path.push(['M', start[0].x, start[0].y]); path.push(['L', start[start.length - 1].x, start[start.length - 1].y]); path.push(['L', end[end.length - 1].x, end[end.length - 1].y]); path.push(['L', end[0].x, end[0].y]); path.push(['Z']); } else if (type === 'polygon') { Util.each(start, function (subItem, index) { if (index === 0) { path.push(['M', subItem.x, subItem.y]); } else { path.push(['L', subItem.x, subItem.y]); } }); for (var i = end.length - 1; i >= 0; i--) { path.push(['L', end[i].x, end[i].y]); } path.push(['Z']); } else { var flag = start[0].flag; Util.each(start, function (subItem, index) { var radius = subItem.radius; if (index === 0) { path.push(['M', subItem.x, subItem.y]); } else { path.push(['A', radius, radius, 0, 0, subItem.flag, subItem.x, subItem.y]); } }); for (var j = end.length - 1; j >= 0; j--) { var endSubItem = end[j]; var endRadius = endSubItem.radius; if (j === end.length - 1) { path.push(['M', endSubItem.x, endSubItem.y]); } else { path.push(['A', endRadius, endRadius, 0, 0, flag === 1 ? 0 : 1, endSubItem.x, endSubItem.y]); } } } return { fill: bgColor, path: path }; } }); module.exports = Grid; /***/ }), /* 188 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var DomUtil = Util.DomUtil; var Component = __webpack_require__(36); var positionAdjust = __webpack_require__(365); var spirialAdjust = __webpack_require__(366); var bboxAdjust = __webpack_require__(367); var LAYOUTS = { scatter: positionAdjust, map: spirialAdjust, treemap: bboxAdjust }; var Label = /*#__PURE__*/function (_Component) { _inheritsLoose(Label, _Component); function Label() { return _Component.apply(this, arguments) || this; } var _proto = Label.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Component.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { name: 'label', /** * label类型 * @type {(String)} */ type: 'default', /** * 默认文本样式 * @type {Array} */ textStyle: null, /** * 文本显示格式化回调函数 * @type {Function} */ formatter: null, /** * 显示的文本集合 * @type {Array} */ items: null, /** * 是否使用html渲染label * @type {String} */ useHtml: false, /** * html 渲染时用的容器的模板,必须存在 class = "g-labels" * @type {String} */ containerTpl: '
', /** * html 渲染时单个 label 的模板,必须存在 class = "g-label" * @type {String} */ itemTpl: '
{text}
', /** * label牵引线定义 * @type {String || Object} */ labelLine: false, /** * label牵引线容器 * @type Object */ lineGroup: null, /** * 需添加label的shape * @type Object */ shapes: null, /** * 默认为true。为false时指定直接用items渲染文本,不进行config * @type Object */ config: true, /** * 是否进行拾取 * @type Object */ capture: true }); } /* * 清空label容器 */ ; _proto.clear = function clear() { var group = this.get('group'); var container = this.get('container'); if (group && !group.get('destroyed')) { group.clear(); } if (container) { container.innerHTML = ''; } _Component.prototype.clear.call(this); } /** * 销毁group */ ; _proto.destroy = function destroy() { var group = this.get('group'); var container = this.get('container'); if (!group.destroy) { group.destroy(); } if (container) { container.parentNode && container.parentNode.removeChild(container); } _Component.prototype.destroy.call(this); // 要最后调用 super.destroy 否则 get 属性会无效 } /** * label绘制全过程 */ ; _proto.render = function render() { this.clear(); this._init(); this.beforeDraw(); this.draw(); this.afterDraw(); }; _proto._dryDraw = function _dryDraw() { var self = this; var items = self.get('items'); var children = self.getLabels(); var count = children.length; Util.each(items, function (item, index) { if (index < count) { var label = children[index]; self.changeLabel(label, item); } else { var labelShape = self._addLabel(item, index); if (labelShape) { labelShape._id = item._id; labelShape.set('coord', item.coord); } } }); for (var i = count - 1; i >= items.length; i--) { children[i].remove(); } self._adjustLabels(); if (self.get('labelLine') || !self.get('config')) { self.drawLines(); } } /** * 更新label * 1. 将items与group中的children对比,更新/新增/删除labels * 2. labels布局优化 * 3. 画label连接线 * 4. 绘制到画布 */ ; _proto.draw = function draw() { this._dryDraw(); this.get('canvas').draw(); } /* * 更新label * oldLabel shape或label dom * newLabel label data * index items中的下标 */ ; _proto.changeLabel = function changeLabel(oldLabel, newLabel) { if (!oldLabel) { return; } if (oldLabel.tagName) { var node = this._createDom(newLabel); oldLabel.innerHTML = node.innerHTML; this._setCustomPosition(newLabel, oldLabel); } else { oldLabel._id = newLabel._id; oldLabel.attr('text', newLabel.text); if (oldLabel.attr('x') !== newLabel.x || oldLabel.attr('y') !== newLabel.y) { oldLabel.resetMatrix(); if (newLabel.textStyle.rotate) { oldLabel.rotateAtStart(newLabel.textStyle.rotate); delete newLabel.textStyle.rotate; } oldLabel.attr(newLabel); } } } /** * 显示label */ ; _proto.show = function show() { var group = this.get('group'); var container = this.get('container'); if (group) { group.show(); } if (container) { container.style.opacity = 1; } } /** * 隐藏label */ ; _proto.hide = function hide() { var group = this.get('group'); var container = this.get('container'); if (group) { group.hide(); } if (container) { container.style.opacity = 0; } } /** * 画label连接线 */ ; _proto.drawLines = function drawLines() { var self = this; var lineStyle = self.get('labelLine'); if (typeof lineStyle === 'boolean') { self.set('labelLine', {}); } var lineGroup = self.get('lineGroup'); if (!lineGroup || lineGroup.get('destroyed')) { lineGroup = self.get('group').addGroup({ elCls: 'x-line-group' }); self.set('lineGroup', lineGroup); } else { lineGroup.clear(); } Util.each(self.get('items'), function (label) { self.lineToLabel(label, lineGroup); }); }; _proto.lineToLabel = function lineToLabel(label, lineGroup) { var self = this; if (!self.get('config') && !label.labelLine) { return; } var lineStyle = label.labelLine || self.get('labelLine'); var capture = typeof label.capture === 'undefined' ? self.get('capture') : label.capture; var path = lineStyle.path; if (path && Util.isFunction(lineStyle.path)) { path = lineStyle.path(label); } if (!path) { var start = label.start || { x: label.x - label._offset.x, y: label.y - label._offset.y }; path = [['M', start.x, start.y], ['L', label.x, label.y]]; } var stroke = label.color; if (!stroke) { if (label.textStyle && label.textStyle.fill) { stroke = label.textStyle.fill; } else { stroke = '#000'; } } var lineShape = lineGroup.addShape('path', { attrs: Util.mix({ path: path, fill: null, stroke: stroke }, lineStyle), capture: capture }); // label 对应线的动画关闭 lineShape.name = self.get('name'); // generate labelLine id according to label id lineShape._id = label._id && label._id.replace('glabel', 'glabelline'); lineShape.set('coord', self.get('coord')); } // 根据type对label布局 ; _proto._adjustLabels = function _adjustLabels() { var self = this; var type = self.get('type'); var labels = self.getLabels(); var shapes = self.get('shapes'); var layout = LAYOUTS[type]; if (type === 'default' || !layout) { return; } layout(labels, shapes); } /** * 获取当前所有label实例 * @return {Array} 当前label实例 */ ; _proto.getLabels = function getLabels() { var container = this.get('container'); if (container) { return Util.toArray(container.childNodes); } return this.get('group').get('children'); } // 先计算label的所有配置项,然后生成label实例 ; _proto._addLabel = function _addLabel(item, index) { var cfg = item; if (this.get('config')) { cfg = this._getLabelCfg(item, index); } return this._createText(cfg); }; _proto._getLabelCfg = function _getLabelCfg(item, index) { var textStyle = this.get('textStyle') || {}; var formatter = this.get('formatter'); var htmlTemplate = this.get('htmlTemplate'); if (!Util.isObject(item)) { var tmp = item; item = {}; item.text = tmp; } if (Util.isFunction(textStyle)) { textStyle = textStyle(item.text, item, index); } if (formatter) { item.text = formatter(item.text, item, index); } if (htmlTemplate) { item.useHtml = true; if (Util.isFunction(htmlTemplate)) { item.text = htmlTemplate(item.text, item, index); } } if (Util.isNil(item.text)) { item.text = ''; } item.text = item.text + ''; // ? 为什么转换为字符串 var cfg = Util.mix({}, item, { textStyle: textStyle }, { x: item.x || 0, y: item.y || 0 }); return cfg; } /** * label初始化,主要针对html容器 */ ; _proto._init = function _init() { if (!this.get('group')) { var group = this.get('canvas').addGroup({ id: 'label-group' }); this.set('group', group); } }; _proto.initHtmlContainer = function initHtmlContainer() { var container = this.get('container'); if (!container) { var containerTpl = this.get('containerTpl'); var wrapper = this.get('canvas').get('el').parentNode; container = DomUtil.createDom(containerTpl); wrapper.style.position = 'relative'; wrapper.appendChild(container); this.set('container', container); } else if (Util.isString(container)) { container = document.getElementById(container); if (container) { this.set('container', container); } } return container; } // 分html dom和G shape两种情况生成label实例 ; _proto._createText = function _createText(config) { // @2018-11-29 by blue.lb 这里由于使用delete导致之后的配置无法获取到point和rotate,出现问题,深拷贝一次比较好 var cfg = Util.deepMix({}, config); var container = this.get('container'); var capture = typeof cfg.capture === 'undefined' ? this.get('capture') : cfg.capture; var labelShape; if (cfg.useHtml || cfg.htmlTemplate) { if (!container) { container = this.initHtmlContainer(); } var node = this._createDom(cfg); container.appendChild(node); this._setCustomPosition(cfg, node); } else { var name = this.get('name'); var origin = cfg.point; var group = this.get('group'); delete cfg.point; // 临时解决,否则影响动画 var rotate = cfg.rotate; // textStyle中的rotate虽然可以正常画出,但是在做动画的时候可能会导致动画异常。移出,在定义好shape后通过transform实现效果。 if (cfg.textStyle) { if (cfg.textStyle.rotate) { rotate = cfg.textStyle.rotate; delete cfg.textStyle.rotate; } cfg = Util.mix({ x: cfg.x, y: cfg.y, textAlign: cfg.textAlign, text: cfg.text }, cfg.textStyle); } labelShape = group.addShape('text', { attrs: cfg, capture: capture }); if (rotate) { // rotate是用角度定义的,转换为弧度 if (Math.abs(rotate) > Math.PI * 2) { rotate = rotate / 180 * Math.PI; } labelShape.transform([['t', -cfg.x, -cfg.y], ['r', rotate], ['t', cfg.x, cfg.y]]); } labelShape.setSilent('origin', origin || cfg); labelShape.name = name; // 用于事件标注 this.get('appendInfo') && labelShape.setSilent('appendInfo', this.get('appendInfo')); return labelShape; } }; _proto._createDom = function _createDom(cfg) { var itemTpl = this.get('itemTpl'); var str = Util.substitute(itemTpl, { text: cfg.text }); return DomUtil.createDom(str); } // 根据文本对齐方式确定dom位置 ; _proto._setCustomPosition = function _setCustomPosition(cfg, htmlDom) { var textAlign = cfg.textAlign || 'left'; var top = cfg.y; var left = cfg.x; var width = DomUtil.getOuterWidth(htmlDom); var height = DomUtil.getOuterHeight(htmlDom); top = top - height / 2; if (textAlign === 'center') { left = left - width / 2; } else if (textAlign === 'right') { left = left - width; } htmlDom.style.top = parseInt(top, 10) + 'px'; htmlDom.style.left = parseInt(left, 10) + 'px'; }; return Label; }(Component); module.exports = Label; /***/ }), /* 189 */ /***/ (function(module, exports) { var Greedy = /*#__PURE__*/function () { function Greedy() { this.bitmap = []; } var _proto = Greedy.prototype; _proto.hasGap = function hasGap(bbox) { var hasGap = true; var bitmap = this.bitmap; var minX = Math.floor(bbox.minX); var maxX = Math.ceil(bbox.maxX); var minY = Math.floor(bbox.minY); var maxY = Math.ceil(bbox.maxY) - 1; for (var i = minX; i < maxX; i++) { if (!bitmap[i]) { bitmap[i] = []; continue; } if (i === minX || i === maxX - 1) { for (var j = minY; j <= maxY; j++) { if (bitmap[i][j]) { hasGap = false; break; } } } else { if (bitmap[i][minY] || bitmap[i][maxY]) { hasGap = false; break; } } } return hasGap; }; _proto.fillGap = function fillGap(bbox) { var bitmap = this.bitmap; var minX = Math.floor(bbox.minX); var maxX = Math.ceil(bbox.maxX) - 1; var minY = Math.floor(bbox.minY); var maxY = Math.ceil(bbox.maxY) - 1; for (var i = minX; i <= maxX; i++) { for (var j = minY; j < maxY; j += 8) { if (!bitmap[i]) { bitmap[i] = []; } bitmap[i][j] = true; } bitmap[i][maxY] = true; } for (var _i = minY; _i <= maxY; _i++) { bitmap[minX][_i] = true; bitmap[maxX][_i] = true; } }; return Greedy; }(); module.exports = Greedy; /***/ }), /* 190 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(4); module.exports = { getFirstScale: function getFirstScale(scales) { var firstScale; Util.each(scales, function (scale) { if (scale) { firstScale = scale; return false; } }); return firstScale; } }; /***/ }), /* 191 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var Legend = __webpack_require__(192); var _require = __webpack_require__(16), FONT_FAMILY = _require.FONT_FAMILY; // const DomUtil = Util.DomUtil; var Event = Util.Event; var Group = Util.Group; // const Global = require('../../global'); // const CONTAINER_CLASS = 'g2-legend'; function findItem(items, refer) { var rst = null; var value = refer instanceof Group || refer.name === 'legendGroup' ? refer.get('value') : refer; Util.each(items, function (item) { if (item.value === value) { rst = item; return false; } }); return rst; } function findShapeByName(group, name) { return group.findBy(function (node) { return node.name === name; }); } var Category = /*#__PURE__*/function (_Legend) { _inheritsLoose(Category, _Legend); function Category() { return _Legend.apply(this, arguments) || this; } var _proto = Category.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Legend.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * type标识 * @type {String} */ type: 'category-legend', /** * 子项集合 * @type {Array} */ items: null, /** * TODO:rename * 图例项水平方向的间距 * @type {Number} */ itemGap: 5, /** * TODO:rename * 图例项垂直方向的间距 * @type {Number} */ itemMarginBottom: 8, /** * 图例项图组 * @type {Group} */ itemsGroup: null, /** * 布局方式: horizontal,vertical * @type {String} */ layout: 'horizontal', /** * 是否允许全部取消,默认 false,即必须保留一个被选中 * @type {Boolean} */ allowAllCanceled: false, /** * 边框内边距 * @type {Array} */ backPadding: [0, 0, 0, 0], /** * 图例项取消选中的颜色 * @type {String} */ unCheckColor: '#ccc', /** * 图例背景层属性设置 * @type {Obejct} */ background: { fill: '#fff', fillOpacity: 0 }, /** * 图例项的宽度,当图例有很多图例项,并且用户想要这些图例项在同一平面内垂直对齐,此时这个属性可帮用户实现此效果 * @type {Number} */ itemWidth: null, /** * 图例文字样式 * @type {ATTRS} */ textStyle: { fill: '#333', fontSize: 12, textAlign: 'start', textBaseline: 'middle', fontFamily: FONT_FAMILY }, /** * marker 和文字的距离 * @type {Number} */ _wordSpaceing: 8, /** * 图例项是否可点击,默认为 true * @type {Boolean} */ clickable: true, /** * TODO: rename * 图例项的选择模式,多选和单选 multiple、single * @type {String} */ selectedMode: 'multiple', /** * 图例项的顺序是否要逆序,默认为 false * @type {Boolean} */ reversed: false, /** * 是否自动换行 * @type {Boolean} */ autoWrap: true, /** * 是否以增加 border 的方式高亮 hover 的 item。若为 false ,则降低其他 item 的透明度。 * @type {Boolean} */ highlight: false, /** * 非highlight方式下,鼠标hover到legend样式 * @type {Number} */ activeOpacity: 0.7, /** * 非highlight方式下,非鼠标hover到的legend样式 * @type {Number} */ inactiveOpacity: 1 }); } // rendering ; _proto.render = function render() { _Legend.prototype.render.call(this); this._renderItems(); this.get('autoWrap') && this._adjustItems(); // 默认自动换行 } // user iteraction ; _proto._bindEvents = function _bindEvents() { if (this.get('hoverable')) { this.get('group').on('mousemove', Util.wrapBehavior(this, '_onMousemove')); this.get('group').on('mouseleave', Util.wrapBehavior(this, '_onMouseleave')); } if (this.get('clickable')) { this.get('group').on('click', Util.wrapBehavior(this, '_onClick')); } } // return the target's parent legend object ; _proto._getLegendItem = function _getLegendItem(target) { var item = target.get('parent'); if (item && item.name === 'legendGroup') { return item; } return null; } // activate an item by reduce the opacity of other items. // it is reserved for bi-direction interaction between charts / graph and legend ; _proto.activate = function activate(value) { var _this = this; var self = this; var itemsGroup = self.get('itemsGroup'); var children = itemsGroup.get('children'); var markerItem = void 0; children.forEach(function (child) { markerItem = findShapeByName(child, 'legend-marker'); if (!markerItem) return; var checked = child.get('checked'); if (_this.get('highlight')) { // change stroke color if (child.get('value') === value && checked) { markerItem.attr('stroke', '#333'); } else { markerItem.attr('stroke', null); } } else { // change opacity if (child.get('value') === value) { markerItem.attr('fillOpacity', self.get('activeOpacity')); } } }); this.get('canvas').draw(); return; } // restore the opacity of items // it is reserved for bi-direction interaction between charts / graph and legend ; _proto.deactivate = function deactivate() { var _this2 = this; var self = this; var itemsGroup = self.get('itemsGroup'); var children = itemsGroup.get('children'); var markerItem = void 0; var unCheckColor = this.get('unCheckColor'); children.forEach(function (child) { markerItem = findShapeByName(child, 'legend-marker'); if (!markerItem) return; if (_this2.get('highlight')) { var oriStroke = markerItem.get('oriStroke'); var checked = child.get('checked'); if (oriStroke && !checked) oriStroke = unCheckColor;else oriStroke = ''; markerItem.attr('stroke', oriStroke); } else { markerItem.attr('fillOpacity', self.get('inactiveOpacity')); } }); this.get('canvas').draw(); return; } // mouse move listener of an item // when mouse over an item, reduce the opacity of the other items. ; _proto._onMousemove = function _onMousemove(ev) { var item = this._getLegendItem(ev.currentTarget); if (item && item.get('checked')) { var items = this.get('items'); var itemhover = new Event('itemhover', ev, true, true); itemhover.item = findItem(items, item); itemhover.checked = item.get('checked'); itemhover.currentTarget = ev.currentTarget; // change the opacity of other items this.deactivate(); this.activate(item.get('value')); this.emit('itemhover', itemhover); } else { this.deactivate(); this.emit('itemunhover', ev); } this.get('canvas').draw(); return; } // mouse leave listener of an item ; _proto._onMouseleave = function _onMouseleave(ev) { this.deactivate(); this.get('canvas').draw(); this.emit('itemunhover', ev); return; } // the click listener of an item ; _proto._onClick = function _onClick(ev) { var clickedItem = this._getLegendItem(ev.currentTarget); var items = this.get('items'); if (clickedItem && !clickedItem.get('destroyed')) { var checked = clickedItem.get('checked'); var mode = this.get('selectedMode'); var item = findItem(items, clickedItem); var itemclick = new Event('itemclick', ev, true, true); itemclick.item = item; itemclick.currentTarget = clickedItem; itemclick.appendInfo = ev.currentTarget.get('appendInfo'); itemclick.checked = mode === 'single' ? true : !checked; if (!this.get('allowAllCanceled') && checked && this.getCheckedCount() === 1) { this.emit('clicklastitem', itemclick); return; } var unCheckColor = this.get('unCheckColor'); var checkColor = this.get('textStyle').fill; var markerItem = void 0; var textItem = void 0; var legendItem = void 0; if (mode === 'single') { var itemsGroup = this.get('itemsGroup'); var children = itemsGroup.get('children'); Util.each(children, function (child) { markerItem = findShapeByName(child, 'legend-marker'); textItem = findShapeByName(child, 'legend-text'); legendItem = findShapeByName(child, 'legend-item'); if (child !== clickedItem) { if (markerItem.attr('fill')) { markerItem.attr('fill', unCheckColor); } if (markerItem.attr('stroke')) { markerItem.attr('stroke', unCheckColor); } textItem.attr('fill', unCheckColor); markerItem.setSilent('checked', false); textItem.setSilent('checked', false); legendItem.setSilent('checked', false); child.setSilent('checked', false); } else { if (markerItem.attr('fill')) { item && item.marker && markerItem.attr('fill', item.marker.fill); } if (markerItem.attr('stroke')) { item && item.marker && markerItem.attr('stroke', item.marker.stroke); } textItem.attr('fill', checkColor); markerItem.setSilent('checked', true); textItem.setSilent('checked', true); legendItem.setSilent('checked', true); child.setSilent('checked', true); } }); } else { markerItem = findShapeByName(clickedItem, 'legend-marker'); textItem = findShapeByName(clickedItem, 'legend-text'); legendItem = findShapeByName(clickedItem, 'legend-item'); if (markerItem.attr('fill')) { item && item.marker && markerItem.attr('fill', checked ? unCheckColor : item.marker.fill); } if (markerItem.attr('stroke')) { item && item.marker && markerItem.attr('stroke', checked ? unCheckColor : item.marker.stroke); } textItem.attr('fill', checked ? unCheckColor : checkColor); clickedItem.setSilent('checked', !checked); markerItem.setSilent('checked', !checked); textItem.setSilent('checked', !checked); legendItem.setSilent('checked', !checked); } this.emit('itemclick', itemclick); } this.get('canvas').draw(); return; } // render the items ; _proto._renderItems = function _renderItems() { var _this3 = this; var items = this.get('items'); if (this.get('reversed')) { items.reverse(); } Util.each(items, function (item, index) { _this3._addItem(item, index); }); if (this.get('highlight')) { var itemsGroup = this.get('itemsGroup'); var children = itemsGroup.get('children'); var markerItem = void 0; children.forEach(function (child) { markerItem = findShapeByName(child, 'legend-marker'); var oriStroke = markerItem.get('oriStroke'); if (!oriStroke) { if (markerItem.attr('stroke')) markerItem.set('oriStroke', markerItem.attr('stroke'));else markerItem.set('oriStroke', ''); } }); } } // format the item value ; _proto._formatItemValue = function _formatItemValue(value) { var formatter = this.get('formatter') || this.get('itemFormatter'); if (formatter) { value = formatter.call(this, value); } return value; } // find x of next item ; _proto._getNextX = function _getNextX() { var layout = this.get('layout'); var itemGap = this.get('itemGap'); var itemsGroup = this.get('itemsGroup'); var itemWidth = this.get('itemWidth'); var children = itemsGroup.get('children'); var nextX = 0; if (layout === 'horizontal') { // 水平布局 Util.each(children, function (v) { nextX += (itemWidth ? itemWidth : v.getBBox().width) + itemGap; }); } return nextX; } // find y of next item ; _proto._getNextY = function _getNextY() { var itemMarginBottom = this.get('itemMarginBottom'); var titleGap = this.get('titleShape') ? this.get('titleGap') : 0; var layout = this.get('layout'); var itemsGroup = this.get('itemsGroup'); var titleShape = this.get('titleShape'); var children = itemsGroup.get('children'); var nextY = titleGap; if (titleShape) { nextY += titleShape.getBBox().height; } if (layout === 'vertical') { // 竖直布局 Util.each(children, function (v) { nextY += v.getBBox().height + itemMarginBottom; }); } return nextY; } // add an item to the canvas ; _proto._addItem = function _addItem(item) { var itemsGroup = this.get('itemsGroup'); var x = this._getNextX(); var y = this._getNextY(); var unCheckColor = this.get('unCheckColor'); var itemGroup = itemsGroup.addGroup({ x: x, y: y, value: item.value, checked: item.checked }); // @2018-10-20 by blue.lb 需要设置viewId,否则在emit的时候,parent获取不到viewId itemGroup.set('viewId', this.get('viewId')); var textStyle = this.get('textStyle'); var wordSpace = this.get('_wordSpaceing'); var startX = 0; if (item.marker) { // 如果有marker添加marker var markerAttrs = Util.mix({}, item.marker, { x: item.marker.radius + x, y: y }); if (!item.checked) { if (markerAttrs.fill) { markerAttrs.fill = unCheckColor; } if (markerAttrs.stroke) { markerAttrs.stroke = unCheckColor; } } var markerShape = itemGroup.addShape('marker', { type: 'marker', attrs: markerAttrs }); markerShape.attr('cursor', 'pointer'); markerShape.name = 'legend-marker'; startX += markerShape.getBBox().width + wordSpace; } var textAttrs = Util.mix({}, { fill: '#333', fontSize: 12, textAlign: 'start', textBaseline: 'middle', fontFamily: FONT_FAMILY }, textStyle, { x: startX + x, y: y, text: this._formatItemValue(item.value) }); if (!item.checked) { Util.mix(textAttrs, { fill: unCheckColor }); } var textShape = itemGroup.addShape('text', { attrs: textAttrs }); textShape.attr('cursor', 'pointer'); textShape.name = 'legend-text'; this.get('appendInfo') && textShape.setSilent('appendInfo', this.get('appendInfo')); // 添加一个包围矩形,用于事件支持 var bbox = itemGroup.getBBox(); var itemWidth = this.get('itemWidth'); var wrapperShape = itemGroup.addShape('rect', { attrs: { x: x, y: y - bbox.height / 2, fill: '#fff', fillOpacity: 0, width: itemWidth || bbox.width, height: bbox.height } }); wrapperShape.attr('cursor', 'pointer'); wrapperShape.setSilent('origin', item); // 保存图例项相关的数据,便于事件操作 wrapperShape.name = 'legend-item'; this.get('appendInfo') && wrapperShape.setSilent('appendInfo', this.get('appendInfo')); itemGroup.name = 'legendGroup'; return itemGroup; } // auto break the line for horizontal layout ; _proto._adjustHorizontal = function _adjustHorizontal() { var itemsGroup = this.get('itemsGroup'); var children = itemsGroup.get('children'); var maxLength = this.get('maxLength'); var itemGap = this.get('itemGap'); var itemMarginBottom = this.get('itemMarginBottom'); var titleGap = this.get('titleShape') ? this.get('titleGap') : 0; var row = 0; var rowLength = 0; var width = void 0; var height = void 0; var box = void 0; var itemWidth = this.get('itemWidth'); if (itemsGroup.getBBox().width > maxLength) { Util.each(children, function (child) { box = child.getBBox(); width = itemWidth || box.width; height = box.height + itemMarginBottom; if (maxLength - rowLength < width) { row++; rowLength = 0; } child.move(rowLength, row * height + titleGap); rowLength += width + itemGap; }); } return; } // auto break the column for vertical layout ; _proto._adjustVertical = function _adjustVertical() { var itemsGroup = this.get('itemsGroup'); var titleShape = this.get('titleShape'); var children = itemsGroup.get('children'); var maxLength = this.get('maxLength'); // 垂直布局,则 maxLength 代表容器的高度 var itemGap = this.get('itemGap'); var itemMarginBottom = this.get('itemMarginBottom'); var titleGap = this.get('titleGap'); var titleHeight = titleShape ? titleShape.getBBox().height + titleGap : 0; var itemWidth = this.get('itemWidth'); var colLength = titleHeight; var width = void 0; var height = void 0; var box = void 0; var maxItemWidth = 0; var totalLength = 0; if (itemsGroup.getBBox().height > maxLength) { Util.each(children, function (v) { box = v.getBBox(); width = box.width; height = box.height; if (itemWidth) { maxItemWidth = itemWidth + itemGap; } else if (width > maxItemWidth) { maxItemWidth = width + itemGap; } if (maxLength - colLength < height) { colLength = titleHeight; totalLength += maxItemWidth; v.move(totalLength, titleHeight); } else { v.move(totalLength, colLength); } colLength += height + itemMarginBottom; }); } return; } // automatically break the line / column while the width / height exceeds maxLength ; _proto._adjustItems = function _adjustItems() { var layout = this.get('layout'); if (layout === 'horizontal') { this._adjustHorizontal(); } else { this._adjustVertical(); } }; _proto.getWidth = function getWidth() { return _Legend.prototype.getWidth.call(this); }; _proto.getHeight = function getHeight() { return _Legend.prototype.getHeight.call(this); }; _proto.move = function move(x, y) { _Legend.prototype.move.call(this, x, y); }; return Category; }(Legend); module.exports = Category; /***/ }), /* 192 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var Component = __webpack_require__(36); var _require = __webpack_require__(16), FONT_FAMILY = _require.FONT_FAMILY; var Legend = /*#__PURE__*/function (_Component) { _inheritsLoose(Legend, _Component); var _proto = Legend.prototype; _proto.getDefaultCfg = function getDefaultCfg() { return { /** * Group 容器 * @type {Object} */ container: null, /** * 图例标题配置 * @type {Object} */ title: null, /** * 图例项文本格式化 * @type {Function} */ formatter: null, /** * 鼠标 hover 到图例上的默认交互是否开启 * @type {Boolean} */ hoverable: true, /** * TODO:rename * 图例标题距离图例项的距离 * @type {Number} */ titleGap: 15, /** * legend 相对于 container 的位置 * @type {Array} */ position: [0, 0], /** * legend 在 position 位置上的偏移量 * @type {Array} */ offset: [0, 0], /** * legend 在 position 位置上沿 x 轴的偏移量。若同时设置了 offset 和 offsetX, 以 offsetX 为准 * @type {Number} */ offsetX: null, /** * legend 在 position 位置上沿 y 轴的偏移量。若同时设置了 offset 和 offsetY, 以 offsetY 为准 * @type {Number} */ offsetY: null }; }; function Legend(cfg) { var _this; _this = _Component.call(this, cfg) || this; _this._init(); _this.beforeRender(); _this.render(); _this._adjustPositionOffset(); _this._bindEvents(); return _this; } _proto._init = function _init() { var group = this.get('group'); var container = this.get('container'); this.set('canvas', container.get('canvas')); var position = this.get('position'); if (!group) group = container.addGroup({ x: 0 - position[0], y: 0 - position[1] }); this.set('group', group); }; _proto._adjustPositionOffset = function _adjustPositionOffset() { var position = this.get('position'); var offset = this.get('offset'); var offsetX = this.get('offsetX'); var offsetY = this.get('offsetY'); if (!Util.isArray(offset)) { var layout = this.get('layout'); offset = layout === 'vertical' ? [offset, 0] : [0, offset]; } if (offsetX) offset[0] = offsetX; if (offsetY) offset[1] = offsetY; var bbox = this.get('group').getBBox(); this.move(-bbox.minX + position[0] + offset[0], -bbox.minY + position[1] + offset[1]); }; _proto.beforeRender = function beforeRender() { var group = this.get('group'); var itemsGroup = group.addGroup(); this.set('itemsGroup', itemsGroup); }; _proto.render = function render() { this._renderTitle(); } // render the title of the legend ; _proto._renderTitle = function _renderTitle() { var title = this.get('title'); var titleGap = this.get('titleGap'); titleGap = titleGap || 0; if (title && title.text) { var group = this.get('group'); var titleShape = group.addShape('text', { attrs: Util.mix({ x: 0, y: 0 - titleGap, fill: '#333', textBaseline: 'middle', fontFamily: FONT_FAMILY }, title) }); titleShape.name = 'legend-title'; this.get('appendInfo') && titleShape.setSilent('appendInfo', this.get('appendInfo')); this.set('titleShape', titleShape); } } // return the count of checked items ; _proto.getCheckedCount = function getCheckedCount() { var itemsGroup = this.get('itemsGroup'); var items = itemsGroup.get('children'); var checkedArr = Util.filter(items, function (item) { return item.get('checked'); }); return checkedArr.length; } // set items for the legend ; _proto.setItems = function setItems(items) { this.set('items', items); this.clear(); this.render(); } // add an item into the legend ; _proto.addItem = function addItem(item) { var items = this.get('items'); items.push(item); this.clear(); this.render(); } // clear all the items of the legend ; _proto.clear = function clear() { var itemsGroup = this.get('itemsGroup'); itemsGroup.clear(); var group = this.get('group'); group.clear(); this.beforeRender(); } // destroy the legend ; _proto.destroy = function destroy() { var group = this.get('group'); group && group.destroy(); this._attrs = {}; this.removeAllListeners(); _Component.prototype.destroy.call(this); // 要最后调用 super.destroy 否则 get 属性会无效 } // return the width of the legend ; _proto.getWidth = function getWidth() { var bbox = this.get('group').getBBox(); return bbox.width; } // return the height of the legend ; _proto.getHeight = function getHeight() { var bbox = this.get('group').getBBox(); return bbox.height; }; _proto.move = function move(x, y) { this.get('group').move(x, y); }; _proto.draw = function draw() { this.get('canvas').draw(); }; return Legend; }(Component); module.exports = Legend; /***/ }), /* 193 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var Category = __webpack_require__(191); var _require = __webpack_require__(16), FONT_FAMILY = _require.FONT_FAMILY; var DomUtil = Util.DomUtil; var Group = Util.Group; var CONTAINER_CLASS = 'g2-legend'; var TITLE_CLASS = 'g2-legend-title'; var LIST_CLASS = 'g2-legend-list'; var ITEM_CLASS = 'g2-legend-list-item'; var TEXT_CLASS = 'g2-legend-text'; var MARKER_CLASS = 'g2-legend-marker'; // find a dom node from the chidren of the node with className. function findNodeByClass(node, className) { return node.getElementsByClassName(className)[0]; } function getParentNode(node, className) { var nodeClass = node.className; if (Util.isNil(nodeClass)) { return node; } nodeClass = nodeClass.split(' '); if (nodeClass.indexOf(className) > -1) { return node; } if (node.parentNode) { if (node.parentNode.className === CONTAINER_CLASS) { return node.parentNode; } return getParentNode(node.parentNode, className); } return null; } function findItem(items, refer) { var rst = null; var value = refer instanceof Group ? refer.get('value') : refer; Util.each(items, function (item) { if (item.value === value) { rst = item; return false; } }); return rst; } var CatHtml = /*#__PURE__*/function (_Category) { _inheritsLoose(CatHtml, _Category); function CatHtml() { return _Category.apply(this, arguments) || this; } var _proto = CatHtml.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Category.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * type 标识 * @type {String} */ type: 'category-legend', /** * html 容器 * @type {DOM} */ container: null, /** * 使用html时的外层模板 * @type {String} */ containerTpl: '
' + '

' + '' + '
', /** * html 模板 * @type {String|Function} */ itemTpl: '
  • ' + '' + '{value}
  • ', /** * html style * @type {Attrs} */ legendStyle: {}, /** * 图例文字样式 * @type {ATTRS} */ textStyle: { fill: '#333', fontSize: 12, textAlign: 'middle', textBaseline: 'top', fontFamily: FONT_FAMILY }, /** * 当文本太长时是否进行缩略 * @type {Boolean} */ abridgeText: false, /** * abridgeText 为 true 时,鼠标放置在 item 上时显示全称的悬浮 div 的 html 模板 * @type {String} */ tipTpl: '
    ', /** * abridgeText 为 true 时,鼠标放置在 item 上时显示全称的悬浮 div 的样式 * @type {Attrs} */ tipStyle: { display: 'none', fontSize: '12px', backgroundColor: '#fff', position: 'absolute', width: 'auto', height: 'auto', padding: '3px', boxShadow: '2px 2px 5px #888' }, /** * useHtml 为 true 时生效,用于自动定位 * @type {[type]} */ autoPosition: true }); }; _proto._init = function _init() { return; }; _proto.beforeRender = function beforeRender() { return; }; _proto.render = function render() { this._renderHTML(); } // user interaction ; _proto._bindEvents = function _bindEvents() { var _this = this; var legendWrapper = this.get('legendWrapper'); var itemListDom = findNodeByClass(legendWrapper, LIST_CLASS); if (this.get('hoverable')) { itemListDom.onmousemove = function (ev) { return _this._onMousemove(ev); }; itemListDom.onmouseout = function (ev) { return _this._onMouseleave(ev); }; } if (this.get('clickable')) { itemListDom.onclick = function (ev) { return _this._onClick(ev); }; } } // mouse move listener of an item // when mouse over an item, reduce the opacity of the other items. ; _proto._onMousemove = function _onMousemove(ev) { var items = this.get('items'); var target = ev.target; var targetClass = target.className; targetClass = targetClass.split(' '); if (targetClass.indexOf(CONTAINER_CLASS) > -1 || targetClass.indexOf(LIST_CLASS) > -1) { return; } var parentDom = getParentNode(target, ITEM_CLASS); var hoveredItem = findItem(items, parentDom.getAttribute('data-value')); if (hoveredItem) { // change the opacity of other items this.deactivate(); this.activate(parentDom.getAttribute('data-value')); this.emit('itemhover', { item: hoveredItem, currentTarget: parentDom, checked: hoveredItem.checked }); } else if (!hoveredItem) { // restore the opacity of all the items this.deactivate(); this.emit('itemunhover', ev); } return; } // mouse leave listener of an item ; _proto._onMouseleave = function _onMouseleave(ev) { // restore the opacity of all the items when mouse leave this.deactivate(); this.emit('itemunhover', ev); return; } // the click listener of an item ; _proto._onClick = function _onClick(ev) { var _this2 = this; var legendWrapper = this.get('legendWrapper'); var itemListDom = findNodeByClass(legendWrapper, LIST_CLASS); var unCheckedColor = this.get('unCheckColor'); var items = this.get('items'); var mode = this.get('selectedMode'); var childNodes = itemListDom.childNodes; var target = ev.target; var targetClass = target.className; targetClass = targetClass.split(' '); if (targetClass.indexOf(CONTAINER_CLASS) > -1 || targetClass.indexOf(LIST_CLASS) > -1) { return; } var parentDom = getParentNode(target, ITEM_CLASS); var textDom = findNodeByClass(parentDom, TEXT_CLASS); var markerDom = findNodeByClass(parentDom, MARKER_CLASS); var clickedItem = findItem(items, parentDom.getAttribute('data-value')); if (!clickedItem) { return; } var domClass = parentDom.className; var originColor = parentDom.getAttribute('data-color'); if (mode === 'single') { // 单选模式 // update checked status clickedItem.checked = true; // 其他图例项全部置灰 Util.each(childNodes, function (child) { if (child !== parentDom) { var childMarkerDom = findNodeByClass(child, MARKER_CLASS); childMarkerDom.style.backgroundColor = unCheckedColor; child.className = child.className.replace('checked', 'unChecked'); child.style.color = unCheckedColor; var childItem = findItem(items, child.getAttribute('data-value')); childItem.checked = false; } else { if (textDom) { textDom.style.color = _this2.get('textStyle').fill; } if (markerDom) { markerDom.style.backgroundColor = originColor; } parentDom.className = domClass.replace('unChecked', 'checked'); } }); } else { // 混合模式 var clickedItemChecked = domClass.indexOf('checked') !== -1; // domClass.includes('checked'); var count = 0; Util.each(childNodes, function (child) { if (child.className.indexOf('checked') !== -1) { // .includes('checked') count++; } }); if (!this.get('allowAllCanceled') && clickedItemChecked && count === 1) { this.emit('clicklastitem', { item: clickedItem, currentTarget: parentDom, checked: mode === 'single' ? true : clickedItem.checked }); return; } // 在判断最后一个图例后再更新checked状态,防止点击最后一个图例item时图例样式没有变化但是checked状态改变了 fix #422 clickedItem.checked = !clickedItem.checked; if (clickedItemChecked) { if (markerDom) { markerDom.style.backgroundColor = unCheckedColor; } parentDom.className = domClass.replace('checked', 'unChecked'); parentDom.style.color = unCheckedColor; } else { if (markerDom) { markerDom.style.backgroundColor = originColor; } parentDom.className = domClass.replace('unChecked', 'checked'); parentDom.style.color = this.get('textStyle').fill; } } this.emit('itemclick', { item: clickedItem, currentTarget: parentDom, checked: mode === 'single' ? true : clickedItem.checked }); return; } // activate an item by reduce the opacity of other items. // it is reserved for bi-direction interaction between charts / graph and legend ; _proto.activate = function activate(value) { var _this3 = this; var self = this; var items = self.get('items'); var item = findItem(items, value); var legendWrapper = self.get('legendWrapper'); var itemListDom = findNodeByClass(legendWrapper, LIST_CLASS); var childNodes = itemListDom.childNodes; childNodes.forEach(function (child) { var childMarkerDom = findNodeByClass(child, MARKER_CLASS); var childItem = findItem(items, child.getAttribute('data-value')); if (_this3.get('highlight')) { if (childItem === item && childItem.checked) { childMarkerDom.style.border = '1px solid #333'; return; } } else { if (childItem === item) { childMarkerDom.style.opacity = self.get('activeOpacity'); } else { if (childItem.checked) childMarkerDom.style.opacity = self.get('inactiveOpacity'); } } // if (childItem !== item && childItem.checked) { // if (this.get('highlight')) { // childMarkerDom.style.border = '1px solid #fff'; // } else childMarkerDom.style.opacity = 0.5; // } else { // if (this.get('highlight')) { // childMarkerDom.style.border = '1px solid #333'; // } else childMarkerDom.style.opacity = 1; // } }); return; } // restore the opacity of items // it is reserved for bi-direction interaction between charts / graph and legend ; _proto.deactivate = function deactivate() { var _this4 = this; var self = this; var legendWrapper = self.get('legendWrapper'); var itemListDom = findNodeByClass(legendWrapper, LIST_CLASS); var childNodes = itemListDom.childNodes; childNodes.forEach(function (child) { var childMarkerDom = findNodeByClass(child, MARKER_CLASS); if (_this4.get('highlight')) { childMarkerDom.style.border = '1px solid #fff'; } else { childMarkerDom.style.opacity = self.get('inactiveOpacity'); } }); return; }; _proto._renderHTML = function _renderHTML() { var _this5 = this; // const canvas = this.get('canvas'); var container = this.get('container'); // const outterNode = container.parentNode; var title = this.get('title'); var containerTpl = this.get('containerTpl'); var legendWrapper = DomUtil.createDom(containerTpl); var titleDom = findNodeByClass(legendWrapper, TITLE_CLASS); var itemListDom = findNodeByClass(legendWrapper, LIST_CLASS); // ul var unCheckedColor = this.get('unCheckColor'); var LEGEND_STYLE = Util.deepMix({}, { CONTAINER_CLASS: { height: 'auto', width: 'auto', position: 'absolute', overflowY: 'auto', fontSize: '12px', fontFamily: FONT_FAMILY, lineHeight: '20px', color: '#8C8C8C' }, TITLE_CLASS: { marginBottom: this.get('titleGap') + 'px', fontSize: '12px', color: '#333', // 默认样式 textBaseline: 'middle', fontFamily: FONT_FAMILY }, LIST_CLASS: { listStyleType: 'none', margin: 0, padding: 0, textAlign: 'center' }, LIST_ITEM_CLASS: { cursor: 'pointer', marginBottom: '5px', marginRight: '24px' }, MARKER_CLASS: { width: '9px', height: '9px', borderRadius: '50%', display: 'inline-block', marginRight: '4px', verticalAlign: 'middle' } }, this.get('legendStyle')); // fix:IE 9 兼容问题,先加入 legendWrapper // let container = this.get('container'); if (/^\#/.test(container) || typeof container === 'string' && container.constructor === String) { // 如果传入 dom 节点的 id var id = container.replace('#', ''); container = document.getElementById(id); container.appendChild(legendWrapper); } else { var _position = this.get('position'); var rangeStyle = {}; if (_position === 'left' || _position === 'right') { rangeStyle = { maxHeight: (this.get('maxLength') || container.offsetHeight) + 'px' }; } else { rangeStyle = { maxWidth: (this.get('maxLength') || container.offsetWidth) + 'px' }; } DomUtil.modifyCSS(legendWrapper, Util.mix({}, LEGEND_STYLE.CONTAINER_CLASS, rangeStyle, this.get(CONTAINER_CLASS))); container.appendChild(legendWrapper); } DomUtil.modifyCSS(itemListDom, Util.mix({}, LEGEND_STYLE.LIST_CLASS, this.get(LIST_CLASS))); // render title if (titleDom) { if (title && title.text) { titleDom.innerHTML = title.text; DomUtil.modifyCSS(titleDom, Util.mix({}, LEGEND_STYLE.TITLE_CLASS, this.get(TITLE_CLASS), title)); } else { legendWrapper.removeChild(titleDom); } } // 开始渲染图例项 var items = this.get('items'); var itemTpl = this.get('itemTpl'); var position = this.get('position'); var layout = this.get('layout'); var itemDisplay = position === 'right' || position === 'left' || layout === 'vertical' ? 'block' : 'inline-block'; var itemStyle = Util.mix({}, LEGEND_STYLE.LIST_ITEM_CLASS, { display: itemDisplay }, this.get(ITEM_CLASS)); var markerStyle = Util.mix({}, LEGEND_STYLE.MARKER_CLASS, this.get(MARKER_CLASS)); Util.each(items, function (item, index) { var checked = item.checked; var value = _this5._formatItemValue(item.value); var markerColor = item.marker.fill || item.marker.stroke; var color = checked ? markerColor : unCheckedColor; var domStr; if (Util.isFunction(itemTpl)) { domStr = itemTpl(value, color, checked, index); } else { domStr = itemTpl; } var itemDiv = Util.substitute(domStr, Util.mix({}, item, { index: index, checked: checked ? 'checked' : 'unChecked', value: value, color: color, originColor: markerColor, // @2018-07-09 by blue.lb 修复如果legend值中存在双引号"时, 导致的无法点击触发legend正常操作bug originValue: item.value.replace(/\"/g, '"') })); // li var itemDom = DomUtil.createDom(itemDiv); itemDom.style.color = _this5.get('textStyle').fill; var markerDom = findNodeByClass(itemDom, MARKER_CLASS); var textDom = findNodeByClass(itemDom, TEXT_CLASS); DomUtil.modifyCSS(itemDom, itemStyle); markerDom && DomUtil.modifyCSS(markerDom, markerStyle); // textDom && DomUtil.modifyCSS(textDom, this.get('textStyle')); if (!checked) { itemDom.style.color = unCheckedColor; if (markerDom) { markerDom.style.backgroundColor = unCheckedColor; } } itemListDom.appendChild(itemDom); // abridge the text if the width of the text exceeds the width of the item if (_this5.get('abridgeText')) { var text = value; // const itemWidth = parseFloat(this.get(ITEM_CLASS).width.substr(0, this.get(ITEM_CLASS).width.length - 2)); var itemWidth = itemDom.offsetWidth; var fs = _this5.get('textStyle').fontSize; if (isNaN(fs)) { // 6.5pt = 6.5 * 1/72 * 96 = 8.6px if (fs.indexOf('pt') !== -1) fs = parseFloat(fs.substr(0, fs.length - 2)) * 1 / 72 * 96;else if (fs.indexOf('px') !== -1) fs = parseFloat(fs.substr(0, fs.length - 2)); } var textWidth = fs * text.length; var letterNum = Math.floor(itemWidth / fs); if (itemWidth < 2 * fs) { // unable to contain '...' text = ''; } else if (itemWidth < textWidth) { // replace the tail as '... if (letterNum > 1) text = text.substr(0, letterNum - 1) + '...'; } textDom.innerText = text; // show the text tip while mouse hovering an item itemDom.addEventListener('mouseover', function () { var tipDom = findNodeByClass(legendWrapper.parentNode, 'textTip'); tipDom.style.display = 'block'; tipDom.style.left = itemDom.offsetLeft + itemDom.offsetWidth + 'px'; tipDom.style.top = itemDom.offsetTop + 15 + 'px'; tipDom.innerText = value; }); // hide the text tip while mouse leave the item itemDom.addEventListener('mouseout', function () { var tipDom = findNodeByClass(legendWrapper.parentNode, 'textTip'); tipDom.style.display = 'none'; }); } }); // append the tip div as a brother node of legend dom if (this.get('abridgeText')) { var tipTpl = this.get('tipTpl'); var tipDom = DomUtil.createDom(tipTpl); var tipDomStyle = this.get('tipStyle'); DomUtil.modifyCSS(tipDom, tipDomStyle); legendWrapper.parentNode.appendChild(tipDom); // hide the tip while mouse entering the tip dom tipDom.addEventListener('mouseover', function () { tipDom.style.display = 'none'; }); } this.set('legendWrapper', legendWrapper); }; _proto._adjustPositionOffset = function _adjustPositionOffset() { var autoPosition = this.get('autoPosition'); // @2018-12-29 by maplor. if autoPosition is false, don't set inline-style if (autoPosition === false) { return; } var position = this.get('position'); var offset = this.get('offset'); var offsetX = this.get('offsetX'); var offsetY = this.get('offsetY'); if (offsetX) offset[0] = offsetX; if (offsetY) offset[1] = offsetY; var legendWrapper = this.get('legendWrapper'); legendWrapper.style.left = position[0] + 'px'; legendWrapper.style.top = position[1] + 'px'; legendWrapper.style.marginLeft = offset[0] + 'px'; legendWrapper.style.marginTop = offset[1] + 'px'; }; _proto.getWidth = function getWidth() { return DomUtil.getOuterWidth(this.get('legendWrapper')); }; _proto.getHeight = function getHeight() { return DomUtil.getOuterHeight(this.get('legendWrapper')); }; _proto.move = function move(x, y) { if (!/^\#/.test(this.get('container'))) { DomUtil.modifyCSS(this.get('legendWrapper'), { left: x + 'px', top: y + 'px' }); this.set('x', x); this.set('y', y); } else { _Category.prototype.move.call(this, x, y); } }; _proto.destroy = function destroy() { var legendWrapper = this.get('legendWrapper'); if (legendWrapper && legendWrapper.parentNode) { legendWrapper.parentNode.removeChild(legendWrapper); } _Category.prototype.destroy.call(this); }; return CatHtml; }(Category); module.exports = CatHtml; /***/ }), /* 194 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Component = __webpack_require__(36); var Util = __webpack_require__(4); var Crosshair = /*#__PURE__*/function (_Component) { _inheritsLoose(Crosshair, _Component); var _proto = Crosshair.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Component.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * crosshair的类型 * @type {String} */ type: null, /** * 画在哪层视图 * @type {G-Element} */ plot: null, /** * x轴上,移动到位置的偏移量 * @type {Number} */ plotRange: null, /** * 默认rect crosshair样式 * @type {Object} */ rectStyle: { fill: '#CCD6EC', opacity: 0.3 }, /** * 默认line crosshair样式 * @type {Object} */ lineStyle: { stroke: 'rgba(0, 0, 0, 0.25)', lineWidth: 1 }, isTransposed: false }); }; function Crosshair(cfg) { var _this; _this = _Component.call(this, cfg) || this; _this._init_(); _this.render(); return _this; } _proto._init_ = function _init_() { var self = this; var plot = self.get('plot'); var group; if (self.type === 'rect') { group = plot.addGroup({ zIndex: 0 }); } else { group = plot.addGroup(); } this.set('container', group); }; _proto._addLineShape = function _addLineShape(attrs, type) { var container = this.get('container'); var shape = container.addShape('line', { capture: false, attrs: attrs }); // shape.hide(); this.set('crossLineShape' + type, shape); return shape; }; _proto._renderHorizontalLine = function _renderHorizontalLine(canvas, plotRange) { var style = Util.mix(this.get('lineStyle'), this.get('style')); var attrs = Util.mix({ x1: plotRange ? plotRange.bl.x : canvas.get('width'), y1: 0, x2: plotRange ? plotRange.br.x : 0, y2: 0 }, style); this._addLineShape(attrs, 'X'); }; _proto._renderVerticalLine = function _renderVerticalLine(canvas, plotRange) { var style = Util.mix(this.get('lineStyle'), this.get('style')); var attrs = Util.mix({ x1: 0, y1: plotRange ? plotRange.bl.y : canvas.get('height'), x2: 0, y2: plotRange ? plotRange.tl.y : 0 }, style); this._addLineShape(attrs, 'Y'); }; _proto._renderBackground = function _renderBackground(canvas, plotRange) { var style = Util.mix(this.get('rectStyle'), this.get('style')); var container = this.get('container'); var attrs = Util.mix({ x: plotRange ? plotRange.tl.x : 0, y: plotRange ? plotRange.tl.y : canvas.get('height'), width: plotRange ? plotRange.br.x - plotRange.bl.x : canvas.get('width'), height: plotRange ? Math.abs(plotRange.tl.y - plotRange.bl.y) : canvas.get('height') }, style); var shape = container.addShape('rect', { attrs: attrs, capture: false }); // shape.hide(); this.set('crosshairsRectShape', shape); return shape; }; _proto._updateRectShape = function _updateRectShape(items) { var offset; var crosshairsRectShape = this.get('crosshairsRectShape'); var isTransposed = this.get('isTransposed'); var firstItem = items[0]; var lastItem = items[items.length - 1]; var dim = isTransposed ? 'y' : 'x'; var attr = isTransposed ? 'height' : 'width'; var startDim = firstItem[dim]; if (items.length > 1 && firstItem[dim] > lastItem[dim]) { startDim = lastItem[dim]; } if (this.get('width')) { // 用户定义了 width crosshairsRectShape.attr(dim, startDim - this.get('crosshairs').width / 2); crosshairsRectShape.attr(attr, this.get('width')); } else { if (Util.isArray(firstItem.point[dim]) && !firstItem.size) { // 直方图 var width = firstItem.point[dim][1] - firstItem.point[dim][0]; crosshairsRectShape.attr(dim, firstItem.point[dim][0]); crosshairsRectShape.attr(attr, width); } else { offset = 3 * firstItem.size / 4; crosshairsRectShape.attr(dim, startDim - offset); if (items.length === 1) { crosshairsRectShape.attr(attr, 3 * firstItem.size / 2); } else { crosshairsRectShape.attr(attr, Math.abs(lastItem[dim] - firstItem[dim]) + 2 * offset); } } } }; _proto.render = function render() { var canvas = this.get('canvas'); var plotRange = this.get('plotRange'); var isTransposed = this.get('isTransposed'); this.clear(); switch (this.get('type')) { case 'x': this._renderHorizontalLine(canvas, plotRange); break; case 'y': this._renderVerticalLine(canvas, plotRange); break; case 'cross': this._renderHorizontalLine(canvas, plotRange); this._renderVerticalLine(canvas, plotRange); break; case 'rect': this._renderBackground(canvas, plotRange); break; default: isTransposed ? this._renderHorizontalLine(canvas, plotRange) : this._renderVerticalLine(canvas, plotRange); } }; _proto.show = function show() { var container = this.get('container'); _Component.prototype.show.call(this); container.show(); }; _proto.hide = function hide() { var container = this.get('container'); _Component.prototype.hide.call(this); container.hide(); }; _proto.clear = function clear() { var container = this.get('container'); this.set('crossLineShapeX', null); this.set('crossLineShapeY', null); this.set('crosshairsRectShape', null); _Component.prototype.clear.call(this); container.clear(); }; _proto.destroy = function destroy() { var container = this.get('container'); _Component.prototype.destroy.call(this); container.remove(); }; _proto.setPosition = function setPosition(x, y, items) { var crossLineShapeX = this.get('crossLineShapeX'); var crossLineShapeY = this.get('crossLineShapeY'); var crosshairsRectShape = this.get('crosshairsRectShape'); if (crossLineShapeY && !crossLineShapeY.get('destroyed')) { // 第一次进入时,画布需要单独绘制,所以需要先设定corss的位置 crossLineShapeY.move(x, 0); } if (crossLineShapeX && !crossLineShapeX.get('destroyed')) { crossLineShapeX.move(0, y); } if (crosshairsRectShape && !crosshairsRectShape.get('destroyed')) { this._updateRectShape(items); } }; return Crosshair; }(Component); module.exports = Crosshair; /***/ }), /* 195 */ /***/ (function(module, exports) { var GAP = 20; var PositionMixin = { _calcTooltipPosition: function _calcTooltipPosition(x, y, position, containerWidth, containerHeight, target) { var rectWidth = 0; var rectHeight = 0; var gap = 20; if (target) { var rect = target.getBBox(); rectWidth = rect.width; rectHeight = rect.height; x = rect.x; y = rect.y; gap = 5; } switch (position) { case 'inside': x = x + rectWidth / 2 - containerWidth / 2; y = y + rectHeight / 2 - containerHeight / 2; break; case 'top': x = x + rectWidth / 2 - containerWidth / 2; y = y - containerHeight - gap; break; case 'left': x = x - containerWidth - gap; y = y + rectHeight / 2 - containerHeight / 2; break; case 'right': x = x + rectWidth + gap; y = y + rectHeight / 2 - containerHeight / 2; break; case 'bottom': default: x = x + rectWidth / 2 - containerWidth / 2; y = y + rectHeight + gap; break; } return [x, y]; }, _constraintPositionInBoundary: function _constraintPositionInBoundary(x, y, width, height, viewWidth, viewHeight) { if (x + width + GAP > viewWidth) { x -= width + GAP; x = x < 0 ? 0 : x; } else if (x + GAP < 0) { x = GAP; } else { x += GAP; } if (y + height + GAP > viewHeight) { y -= height + GAP; y = y < 0 ? 0 : y; } else if (y + GAP < 0) { y = GAP; } else { y += GAP; } return [x, y]; }, _constraintPositionInPlot: function _constraintPositionInPlot(x, y, width, height, plotRange, enterable) { if (x + width > plotRange.tr.x) { if (enterable) { // fix: https://github.com/antvis/g2/issues/1414 // 当 enterable 开启时,如果设置 tooltip 与鼠标的间距过大根本就追逐不上 tooltip x -= width + 1; } else { x -= width + 2 * GAP; } } if (x < plotRange.tl.x) { x = plotRange.tl.x; } if (!enterable) { if (y + height > plotRange.bl.y) { y -= height + 2 * GAP; } if (y < plotRange.tl.y) { y = plotRange.tl.y; } } return [x, y]; } }; module.exports = PositionMixin; /***/ }), /* 196 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(4); var MarkerGroupMixin = { setMarkers: function setMarkers(markerItems, markerCfg) { var self = this; var markerGroup = self.get('markerGroup'); var frontPlot = self.get('frontPlot'); if (!markerGroup) { markerGroup = frontPlot.addGroup({ zIndex: 1, capture: false // 不进行拾取 }); self.set('markerGroup', markerGroup); } else { markerGroup.clear(); } Util.each(markerItems, function (item) { var attrs = Util.mix({ fill: item.color, symbol: 'circle', shadowColor: item.color }, markerCfg, { x: item.x, y: item.y }); if (item.marker && item.marker.activeSymbol) { attrs.symbol = item.marker.activeSymbol; } markerGroup.addShape('marker', { color: item.color, attrs: attrs }); }); this.set('markerItems', markerItems); }, clearMarkers: function clearMarkers() { var markerGroup = this.get('markerGroup'); markerGroup && markerGroup.clear(); } }; module.exports = MarkerGroupMixin; /***/ }), /* 197 */ /***/ (function(module, exports, __webpack_require__) { function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var G = __webpack_require__(51); var Crosshair = __webpack_require__(194); var MarkerGroupMixin = __webpack_require__(196); var PositionMixin = __webpack_require__(195); var Tooltip = __webpack_require__(98); var Util = __webpack_require__(4); var _require = __webpack_require__(16), FONT_FAMILY = _require.FONT_FAMILY; var DomUtil = Util.DomUtil; var MatrixUtil = Util.MatrixUtil; var CanvasTooltip = /*#__PURE__*/function (_Tooltip) { _inheritsLoose(CanvasTooltip, _Tooltip); var _proto = CanvasTooltip.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Tooltip.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * 默认背景板样式 * @type {Object} */ boardStyle: { x: 0, y: 0, width: 100, height: 100, fill: 'rgba(255, 255, 255, 0.9)', radius: 4, stroke: '#e2e2e2', lineWidth: 1 }, /** * 默认title样式 * @type {Object} */ titleStyle: { fontFamily: FONT_FAMILY, text: '', textBaseline: 'top', fontSize: 12, fill: 'rgb(87, 87, 87)', lineHeight: 20, padding: 20 }, /** * 默认marker样式 * @type {Object} */ markerStyle: { radius: 4 }, /** * 默认name样式 * @type {Object} */ nameStyle: { fontFamily: FONT_FAMILY, fontSize: 12, fill: 'rgb(87, 87, 87)', textBaseline: 'middle', textAlign: 'start', padding: 8 }, /** * 默认value样式 * @type {Object} */ valueStyle: { fontFamily: FONT_FAMILY, fontSize: 12, fill: 'rgb(87, 87, 87)', textBaseline: 'middle', textAlign: 'start', padding: 30 }, /** * 默认padding值 * @type {Object} */ padding: { top: 20, right: 20, bottom: 20, left: 20 }, /** * 默认item之间的gap * @type {Number} */ itemGap: 10, /** * 默认tooltip位置移动动画的时长 * @type {Number} */ animationDuration: 200 }); }; function CanvasTooltip(cfg) { var _this; _this = _Tooltip.call(this, cfg) || this; Util.assign(_assertThisInitialized(_this), PositionMixin); Util.assign(_assertThisInitialized(_this), MarkerGroupMixin); // crosshair var crosshair = _this.get('crosshairs'); if (crosshair) { var plot = crosshair.type === 'rect' ? _this.get('backPlot') : _this.get('frontPlot'); var crosshairGroup = new Crosshair(Util.mix({ plot: plot, plotRange: _this.get('plotRange'), canvas: _this.get('canvas') }, _this.get('crosshairs'))); crosshairGroup.hide(); _this.set('crosshairGroup', crosshairGroup); } _this._init_(); if (_this.get('items')) { _this.render(); } return _this; } _proto._init_ = function _init_() { var self = this; var padding = self.get('padding'); var parent = self.get('frontPlot'); // marker group var markerGroup = parent.addGroup({ capture: false }); self.set('markerGroup', markerGroup); // container var container = parent.addGroup(); container.hide(); self.set('container', container); // board var board = container.addShape('rect', { attrs: Util.mix({}, self.get('boardStyle')) }); self.set('board', board); // title var titleStyle = self.get('titleStyle'); if (self.get('showTitle')) { var titleShape = container.addShape('text', { attrs: Util.mix({ x: padding.left, y: padding.top }, titleStyle) }); self.set('titleShape', titleShape); titleShape.name = 'tooltip-title'; } // items var itemsGroup = container.addGroup(); itemsGroup.move(padding.left, padding.top + titleStyle.lineHeight + titleStyle.padding); self.set('itemsGroup', itemsGroup); }; _proto.render = function render() { var self = this; self.clear(); var container = self.get('container'); var board = self.get('board'); var showTitle = self.get('showTitle'); var titleContent = self.get('titleContent'); var titleShape = this.get('titleShape'); var itemsGroup = this.get('itemsGroup'); var items = self.get('items'); var padding = self.get('padding'); if (titleShape && showTitle) { titleShape.attr('text', titleContent); } if (itemsGroup) { var itemGap = self.get('itemGap'); var x = 0; var y = 0; Util.each(items, function (item) { var itemGroup = self._addItem(item); itemGroup.move(x, y); itemsGroup.add(itemGroup); var itemHeight = itemGroup.getBBox().height; y += itemHeight + itemGap; }); } // update board based on bbox var bbox = container.getBBox(); var width = bbox.width + padding.right; var height = bbox.height + padding.bottom; board.attr('width', width); board.attr('height', height); // align value text to right self._alignToRight(width); }; _proto.clear = function clear() { var titleShape = this.get('titleShape'); var itemsGroup = this.get('itemsGroup'); var board = this.get('board'); titleShape.text = ''; itemsGroup.clear(); board.attr('width', 0); board.attr('height', 0); }; _proto.show = function show() { var container = this.get('container'); container.show(); var crosshairGroup = this.get('crosshairGroup'); crosshairGroup && crosshairGroup.show(); var markerGroup = this.get('markerGroup'); markerGroup && markerGroup.show(); _Tooltip.prototype.show.call(this); this.get('canvas').draw(); }; _proto.hide = function hide() { var container = this.get('container'); container.hide(); var crosshairGroup = this.get('crosshairGroup'); crosshairGroup && crosshairGroup.hide(); var markerGroup = this.get('markerGroup'); markerGroup && markerGroup.hide(); _Tooltip.prototype.hide.call(this); this.get('canvas').draw(); }; _proto.destroy = function destroy() { var container = this.get('container'); var crosshairGroup = this.get('crosshairGroup'); crosshairGroup && crosshairGroup.destroy(); var markerGroup = this.get('markerGroup'); markerGroup && markerGroup.remove(); _Tooltip.prototype.destroy.call(this); container.remove(); }; _proto.setPosition = function setPosition(x, y, target) { var container = this.get('container'); var outterNode = this.get('canvas').get('el'); var viewWidth = DomUtil.getWidth(outterNode); var viewHeight = DomUtil.getHeight(outterNode); var bbox = container.getBBox(); var containerWidth = bbox.width; var containerHeight = bbox.height; var endx = x; var endy = y; var position; if (this.get('position')) { var _containerWidth = bbox.width; var _containerHeight = bbox.height; position = this._calcTooltipPosition(x, y, this.get('position'), _containerWidth, _containerHeight, target); x = position[0]; y = position[1]; } else { position = this._constraintPositionInBoundary(x, y, containerWidth, containerHeight, viewWidth, viewHeight); x = position[0]; y = position[1]; } if (this.get('inPlot')) { // tooltip 必须限制在绘图区域内 var plotRange = this.get('plotRange'); position = this._constraintPositionInPlot(x, y, containerWidth, containerHeight, plotRange, this.get('enterable')); x = position[0]; y = position[1]; } var markerItems = this.get('markerItems'); if (!Util.isEmpty(markerItems)) { endx = markerItems[0].x; endy = markerItems[0].y; } var ulMatrix = [1, 0, 0, 0, 1, 0, 0, 0, 1]; var mat = MatrixUtil.transform(ulMatrix, [['t', x, y]]); container.stopAnimate(); container.animate({ matrix: mat }, this.get('animationDuration')); var crosshairGroup = this.get('crosshairGroup'); if (crosshairGroup) { var items = this.get('items'); crosshairGroup.setPosition(endx, endy, items); } _Tooltip.prototype.setPosition.call(this, x, y); }; _proto._addItem = function _addItem(item) { var group = new G.Group(); var markerRadius = this.get('markerStyle').radius; // marker if (item.marker) { var markerAttrs = Util.mix({}, item.marker, { x: item.marker.radius / 2, y: 0, symbol: item.marker.activeSymbol || item.marker.symbol }); group.addShape('marker', { attrs: markerAttrs }); markerRadius = item.marker.radius; } // name var nameStyle = this.get('nameStyle'); group.addShape('text', { attrs: Util.mix({ x: markerRadius + nameStyle.padding, y: 0, text: item.name }, nameStyle) }); // value var valueStyle = this.get('valueStyle'); group.addShape('text', { attrs: Util.mix({ x: group.getBBox().width + valueStyle.padding, y: 0, text: item.value }, valueStyle) }); return group; }; _proto._alignToRight = function _alignToRight(width) { var _this2 = this; var itemsGroup = this.get('itemsGroup'); var groups = itemsGroup.get('children'); Util.each(groups, function (g) { var children = g.get('children'); var valueText = children[2]; var w = valueText.getBBox().width; var x = width - w - _this2.get('padding').right * 2; valueText.attr('x', x); }); }; return CanvasTooltip; }(Tooltip); module.exports = CanvasTooltip; /***/ }), /* 198 */ /***/ (function(module, exports, __webpack_require__) { var Labels = __webpack_require__(91); var PathUtil = __webpack_require__(25); var Util = __webpack_require__(0); var PolarLabels = function PolarLabels(cfg) { PolarLabels.superclass.constructor.call(this, cfg); }; Util.extend(PolarLabels, Labels); Util.augment(PolarLabels, { getPointRauis: function getPointRauis(coord, point) { return PathUtil.getPointRadius(coord, point); }, getCirclePoint: function getCirclePoint(angle, offset, point) { var self = this; var coord = self.get('coord'); var center = coord.getCenter(); var labelEmit = self._isEmitLabels(); var r = self.getPointRauis(coord, point); if (r === 0) { return null; } if (coord.isTransposed && r > offset && !labelEmit) { var appendAngle = Math.asin(offset / (2 * r)); angle = angle + appendAngle * 2; } else { r = r + offset; } return { x: center.x + r * Math.cos(angle), y: center.y + r * Math.sin(angle), angle: angle, r: r }; }, getArcPoint: function getArcPoint(point, index) { var self = this; var outerPoint; // 圆弧上的中点 // var coord = self.get('coord'); index = index || 0; if (Util.isArray(point.x) || Util.isArray(point.y)) { outerPoint = { x: Util.isArray(point.x) ? point.x[index] : point.x, y: Util.isArray(point.y) ? point.y[index] : point.y }; } else { outerPoint = point; } self.transLabelPoint(outerPoint); return outerPoint; }, // 获取点所在的角度 getPointAngle: function getPointAngle(point) { var self = this; var coord = self.get('coord'); return PathUtil.getPointAngle(coord, point); }, // 获取中心的位置 getMiddlePoint: function getMiddlePoint(points) { var self = this; var coord = self.get('coord'); var count = points.length; var middlePoint = { x: 0, y: 0 }; Util.each(points, function (point) { middlePoint.x += point.x; middlePoint.y += point.y; }); middlePoint.x /= count; middlePoint.y /= count; middlePoint = coord.convert(middlePoint); return middlePoint; }, // 是否居中 _isToMiddle: function _isToMiddle(point) { return point.x.length > 2; }, /** * @protected * 获取文本的位置信息 * @param {Array} label labels * @param {Object} point point * @param {Number} index index * @return {Object} point */ getLabelPoint: function getLabelPoint(label, point, index) { // if (Util.isNil(point.x)) return; var self = this; var text = label.text[index]; var factor = 1; var arcPoint; if (self._isToMiddle(point)) { arcPoint = self.getMiddlePoint(point.points); } else { if (label.text.length === 1 && index === 0) { index = 1; } else if (index === 0) { factor = -1; } arcPoint = self.getArcPoint(point, index); } var offset = self.getDefaultOffset(label); offset = offset * factor; var middleAngle = self.getPointAngle(arcPoint); var labelPoint = self.getCirclePoint(middleAngle, offset, arcPoint); if (!labelPoint) { labelPoint = { text: '' }; } else { labelPoint.text = text; labelPoint.angle = middleAngle; labelPoint.color = point.color; } if (label.autoRotate || typeof label.autoRotate === 'undefined') { var rotate = labelPoint.textStyle ? labelPoint.textStyle.rotate : null; if (!rotate) { rotate = labelPoint.rotate || self.getLabelRotate(middleAngle, offset, point); } labelPoint.rotate = rotate; } labelPoint.start = { x: arcPoint.x, y: arcPoint.y }; return labelPoint; }, _isEmitLabels: function _isEmitLabels() { var labels = this.get('label'); return labels.labelEmit; }, /** * @protected * 获取文本旋转的方向 * @param {Number} angle angle * @return {Number} angle */ getLabelRotate: function getLabelRotate(angle) { var self = this; var rotate; rotate = angle * 180 / Math.PI; rotate += 90; if (self._isEmitLabels()) { rotate -= 90; } if (rotate) { if (rotate > 90) { rotate = rotate - 180; } else if (rotate < -90) { rotate = rotate + 180; } } return rotate / 180 * Math.PI; }, // override getLabelAlign: function getLabelAlign(point) { var self = this; var coord = self.get('coord'); var align; if (self._isEmitLabels()) { if (point.angle <= Math.PI / 2 && point.angle > -Math.PI / 2) { align = 'left'; } else { align = 'right'; } } else if (!coord.isTransposed) { align = 'center'; } else { var center = coord.getCenter(); var offset = self.getDefaultOffset(point); if (Math.abs(point.x - center.x) < 1) { align = 'center'; } else if (point.angle > Math.PI || point.angle <= 0) { if (offset > 0) { align = 'left'; } else { align = 'right'; } } else { if (offset > 0) { align = 'right'; } else { align = 'left'; } } } return align; } }); module.exports = PolarLabels; /***/ }), /* 199 */ /***/ (function(module, exports) { module.exports = { toFront: function toFront(shape) { var parent = shape.get('parent'); var originIndex = parent.get('children').indexOf(shape); shape.set('_originIndex', originIndex); shape.toFront(); // 移动到最上面 }, resetZIndex: function resetZIndex(shape) { var parent = shape.get('parent'); var originIndex = shape.get('_originIndex'); var siblings = parent.get('children'); var currentIndex = siblings.indexOf(shape); if (originIndex >= 0 && originIndex !== currentIndex) { siblings.splice(currentIndex, 1); // 从数组中移除 siblings.splice(originIndex, 0, shape); // 重新加入数组,返回原先的位置 } } }; /***/ }), /* 200 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { Scale: __webpack_require__(399), Coord: __webpack_require__(400), Axis: __webpack_require__(405), Guide: __webpack_require__(406), Legend: __webpack_require__(409), Tooltip: __webpack_require__(411), Event: __webpack_require__(412) }; /***/ }), /* 201 */ /***/ (function(module, exports, __webpack_require__) { var G = __webpack_require__(18); var Util = __webpack_require__(0); var mergeBBox = __webpack_require__(202); function applyMatrix(point, matrix, tag) { if (tag === void 0) { tag = 1; } var vector = [point.x, point.y, tag]; Util.vec3.transformMat3(vector, vector, matrix); return { x: vector[0], y: vector[1] }; } function getTitleBBox(title) { var bbox = title.getBBox(); var leftTop = { x: bbox.minX, y: bbox.minY }; var rightBottom = { x: bbox.maxX, y: bbox.maxY }; var matrix = title.attr('matrix'); leftTop = applyMatrix(leftTop, matrix); rightBottom = applyMatrix(rightBottom, matrix); return { minX: leftTop.x, minY: leftTop.y, maxX: rightBottom.x, maxY: rightBottom.y }; } module.exports = function BBoxOfBackPlot(backPlot, defaultBBox) { var bbox = defaultBBox; Util.each(backPlot.get('children'), function (group) { // 这段代码假设了子元素是 axis,同时 title 超出长度, // 这种临时代码需要在 4.0 中修复掉 if (group instanceof G.Group) { Util.each(group.get('children'), function (element) { if (element instanceof G.Group && element.get('children').length || element instanceof G.Path) { bbox = mergeBBox(bbox, element.getBBox()); } else if (element instanceof G.Text) { // title var elementBBox = getTitleBBox(element); bbox = mergeBBox(bbox, elementBBox); } }); } }); return bbox; }; /***/ }), /* 202 */ /***/ (function(module, exports) { module.exports = function mergeBBox(box1, box2) { return { minX: Math.min(box1.minX, box2.minX), minY: Math.min(box1.minY, box2.minY), maxX: Math.max(box1.maxX, box2.maxX), maxY: Math.max(box1.maxY, box2.maxY) }; }; /***/ }), /* 203 */ /***/ (function(module, exports) { module.exports = function plotRange2BBox(plotRange) { return { minX: plotRange.tl.x, minY: plotRange.tl.y, maxX: plotRange.br.x, maxY: plotRange.br.y }; }; /***/ }), /* 204 */, /* 205 */, /* 206 */ /***/ (function(module, exports, __webpack_require__) { var Scale = __webpack_require__(105); var G = __webpack_require__(18); var Animate = __webpack_require__(142); var Chart = __webpack_require__(163); var Global = __webpack_require__(8); var Shape = __webpack_require__(21); var Util = __webpack_require__(0); var G2 = { // version version: Global.version, // visual encoding Animate: Animate, Chart: Chart, Global: Global, Scale: Scale, Shape: Shape, Util: Util, // render engine G: G, DomUtil: Util.DomUtil, MatrixUtil: Util.MatrixUtil, PathUtil: Util.PathUtil }; // G2.track = function(enable) { // Global.trackable = enable; // }; // require('./track'); G2.track = function () { console.warn('G2 tracks nothing ;-)'); }; // 保证两个版本共存 if (typeof window !== 'undefined') { if (window.G2) { console.warn("There are multiple versions of G2. Version " + G2.version + "'s reference is 'window.G2_3'"); } else { window.G2 = G2; } } module.exports = G2; /***/ }), /* 207 */, /* 208 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview 自动计算数字坐标轴 * @author dxq613@gmail.com */ var isNil = __webpack_require__(6); var isNumber = __webpack_require__(11); var AutoUtil = __webpack_require__(107); var MIN_COUNT = 5; var MAX_COUNT = 7; var SNAP_COUNT_ARRAY = [1, 1.2, 1.5, 1.6, 2, 2.2, 2.4, 2.5, 3, 4, 5, 6, 7.5, 8, 10]; var SNAP_ARRAY = [1, 2, 4, 5, 10]; var EPS = 1e-12; module.exports = function (info) { var min = info.min; var max = info.max; var interval = info.interval; var minTickInterval = info.minTickInterval; var ticks = []; var minCount = info.minCount || MIN_COUNT; var maxCount = info.maxCount || MAX_COUNT; var isFixedCount = minCount === maxCount; // 是否限定死了个数 var minLimit = isNil(info.minLimit) ? -Infinity : info.minLimit; // 限定的最小值 var maxLimit = isNil(info.maxLimit) ? Infinity : info.maxLimit; // 限定最大值 var avgCount = (minCount + maxCount) / 2; var count = avgCount; // 用户传入的逼近数组 var snapArray = info.snapArray ? info.snapArray : isFixedCount ? SNAP_COUNT_ARRAY : SNAP_ARRAY; // 如果限定大小范围,同时大小范围等于用户传入的范围,同时限定了个数,interval 按照个数均分 if (min === minLimit && max === maxLimit && isFixedCount) { interval = (max - min) / (count - 1); } if (isNil(min)) { min = 0; } if (isNil(max)) { max = 0; } if (Math.abs(max - min) < EPS) { if (min === 0) { max = 1; } else { if (min > 0) { min = 0; } else { max = 0; } } if (max - min < 5 && !interval && max - min >= 1) { interval = 1; } } if (isNil(interval)) { // 计算间距 var temp = (max - min) / (avgCount - 1); interval = AutoUtil.snapFactorTo(temp, snapArray, 'ceil'); if (maxCount !== minCount) { count = parseInt((max - min) / interval, 10); if (count > maxCount) { count = maxCount; } if (count < minCount) { count = minCount; } // 不确定tick的个数时,使得tick偏小 interval = AutoUtil.snapFactorTo((max - min) / (count - 1), snapArray); } } // interval should not be less than minTickInterval if (isNumber(minTickInterval) && interval < minTickInterval) { interval = minTickInterval; } if (info.interval || maxCount !== minCount) { // 校正 max 和 min max = Math.min(AutoUtil.snapMultiple(max, interval, 'ceil'), maxLimit); // 向上逼近 min = Math.max(AutoUtil.snapMultiple(min, interval, 'floor'), minLimit); // 向下逼近 count = Math.round((max - min) / interval); min = AutoUtil.fixedBase(min, interval); // 当min为负数的时候,fixedBase后,min可能会大于minLimit,导致最终产出的tick是大于minLimit的,所以必须进行修正 max = AutoUtil.fixedBase(max, interval); var prevMin = null; while (min > minLimit && minLimit > -Infinity && (prevMin === null || min < prevMin)) { // 保证计算出来的刻度最小值 min, 不大于数据最小值 min prevMin = min; min = AutoUtil.fixedBase(min - interval, interval); } } else { avgCount = parseInt(avgCount, 10); // 取整 var avg = (max + min) / 2; var avgTick = AutoUtil.snapMultiple(avg, interval, 'ceil'); var sideCount = Math.floor((avgCount - 2) / 2); var maxTick = avgTick + sideCount * interval; var minTick; if (avgCount % 2 === 0) { minTick = avgTick - sideCount * interval; } else { minTick = avgTick - (sideCount + 1) * interval; } var prevMaxTick = null; // 如果减去intervl, fixBase后,新的minTick没有大于之前的值,就退出,防止死循环 while (maxTick < max && (prevMaxTick === null || maxTick > prevMaxTick)) { // 保证计算出来的刻度最大值 maxTick 不小于数据最大值 max prevMaxTick = maxTick; maxTick = AutoUtil.fixedBase(maxTick + interval, interval); } var prevMinTick = null; // 如果减去intervl, fixBase后,新的minTick没有小于之前的值,就退出,防止死循环 while (minTick > min && (prevMinTick === null || minTick < prevMinTick)) { // 保证计算出来的刻度最小值 minTick 不大于数据最小值 min prevMinTick = minTick; minTick = AutoUtil.fixedBase(minTick - interval, interval); // 防止超常浮点数计算问题 } max = maxTick; min = minTick; } max = Math.min(max, maxLimit); min = Math.max(min, minLimit); ticks.push(min); for (var i = 1; i < count; i++) { var tickValue = AutoUtil.fixedBase(interval * i + min, interval); if (tickValue < max) { ticks.push(tickValue); } } if (ticks[ticks.length - 1] < max) { ticks.push(max); } return { min: min, max: max, interval: interval, count: count, ticks: ticks }; }; /***/ }), /* 209 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var Base = __webpack_require__(20); var isNumber = __webpack_require__(11); var Identity = /*#__PURE__*/function (_Base) { _inheritsLoose(Identity, _Base); function Identity() { return _Base.apply(this, arguments) || this; } var _proto = Identity.prototype; _proto._initDefaultCfg = function _initDefaultCfg() { _Base.prototype._initDefaultCfg.call(this); this.isIdentity = true; this.type = 'identity'; /** * 常量值 * @type {*} */ this.value = null; } /** * @override */ ; _proto.getText = function getText() { return this.value.toString(); } /** * @override */ ; _proto.scale = function scale(value) { if (this.value !== value && isNumber(value)) { return value; } return this.range[0]; } /** * @override */ ; _proto.invert = function invert() { return this.value; }; return Identity; }(Base); Base.Identity = Identity; module.exports = Identity; /***/ }), /* 210 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * @fileOverview The measurement of linear data scale function * @author dxq613@gmail.com */ var fecha = __webpack_require__(110); var each = __webpack_require__(3); var isNil = __webpack_require__(6); var isString = __webpack_require__(12); var Base = __webpack_require__(20); var Linear = __webpack_require__(38); var timeAuto = __webpack_require__(211); var TimeUtil = __webpack_require__(100); /** * 时间度量的构造函数 * @class Scale.Time */ var Time = /*#__PURE__*/function (_Linear) { _inheritsLoose(Time, _Linear); function Time() { return _Linear.apply(this, arguments) || this; } var _proto = Time.prototype; _proto._initDefaultCfg = function _initDefaultCfg() { _Linear.prototype._initDefaultCfg.call(this); this.type = 'time'; this.mask = 'YYYY-MM-DD'; } /** * @override */ ; _proto.init = function init() { var self = this; var values = self.values; if (values && values.length) { // 重新计算最大最小值 var timeStamps = []; var min = Infinity; // 最小值 var secondMin = min; // 次小值 var max = 0; // 使用一个循环,计算min,max,secondMin each(values, function (v) { var timeStamp = self._toTimeStamp(v); if (isNaN(timeStamp)) { throw new TypeError("Invalid Time: " + v); } if (min > timeStamp) { secondMin = min; min = timeStamp; } else if (secondMin > timeStamp) { secondMin = timeStamp; } if (max < timeStamp) { max = timeStamp; } timeStamps.push(timeStamp); }); // 存在多个值时,设置最小间距 if (values.length > 1) { self.minTickInterval = secondMin - min; } if (isNil(self.min) || self._toTimeStamp(self.min) > min) { self.min = min; } if (isNil(self.max) || self._toTimeStamp(self.max) < max) { self.max = max; } } _Linear.prototype.init.call(this); }; _proto.calculateTicks = function calculateTicks() { var self = this; var min = self.min; var max = self.max; var count = self.tickCount; var interval = self.tickInterval; var tmp = timeAuto({ min: min, max: max, minCount: count, maxCount: count, interval: interval, minInterval: self.minTickInterval }); return tmp.ticks; } /** * @override */ ; _proto.getText = function getText(value) { var formatter = this.formatter; value = this.translate(value); value = formatter ? formatter(value) : fecha.format(value, this.mask); return value; } /** * @override */ ; _proto.scale = function scale(value) { if (isString(value)) { value = this.translate(value); } return _Linear.prototype.scale.call(this, value); } /** * @override */ ; _proto.translate = function translate(value) { return this._toTimeStamp(value); } // 将时间转换为时间戳 ; _proto._toTimeStamp = function _toTimeStamp(value) { return TimeUtil.toTimeStamp(value); }; return Time; }(Linear); Base.Time = Time; module.exports = Time; /***/ }), /* 211 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview 计算时间坐标轴 * @author dxq613@gmail.com */ var AutoUtil = __webpack_require__(107); var isNil = __webpack_require__(6); var MAX_COUNT = 6; var SNAP_ARRAY = [1, 2, 4, 6, 8, 12]; var MINUTE_MS = 60 * 1000; var HOUR_MS = 3600 * 1000; var DAY_MS = 24 * 3600 * 1000; function getYear(date) { return new Date(date).getFullYear(); } function createYear(year) { return new Date(year, 0, 1).getTime(); } function getMonth(date) { return new Date(date).getMonth(); } function diffMonth(min, max) { var minYear = getYear(min); var maxYear = getYear(max); var minMonth = getMonth(min); var maxMonth = getMonth(max); return (maxYear - minYear) * 12 + (maxMonth - minMonth) % 12; } function creatMonth(year, month) { return new Date(year, month, 1).getTime(); } function diffDay(min, max) { return Math.ceil((max - min) / DAY_MS); } function diffHour(min, max) { return Math.ceil((max - min) / HOUR_MS); } function diffMinus(min, max) { return Math.ceil((max - min) / (60 * 1000)); } module.exports = function (info) { var minInterval = info.minInterval; var ticks = []; var min = info.min; var max = info.max; var interval = info.interval; var count; // 如果最大值和最小值相等,则设置最大值大于最小值一天 if (max === min) { max = min + DAY_MS; } // 计算间距 if (isNil(interval)) { var innerTime = max - min; var dms = DAY_MS; // 天代表的秒 var yms = 365 * dms; // 年代表的秒 interval = parseInt(innerTime / (info.maxCount || MAX_COUNT), 10); if (minInterval && minInterval > interval) { interval = minInterval; } var yfactor = interval / yms; var minYear = getYear(min); // 大于半年 if (yfactor > 0.51) { var year = Math.ceil(yfactor); // interval = year * yms; var maxYear = getYear(max); for (var i = minYear; i <= maxYear + year; i = i + year) { ticks.push(createYear(i)); } interval = null; } else if (yfactor > 0.0834) { // 大于一个月 var month = Math.ceil(yfactor / 0.0834); var mmMoth = getMonth(min); var dMonths = diffMonth(min, max); for (var _i = 0; _i <= dMonths + month; _i = _i + month) { ticks.push(creatMonth(minYear, _i + mmMoth)); } interval = null; } else if (interval > dms * 0.5) { // 大于一天 var date = new Date(min); var _year = date.getFullYear(); var _month = date.getMonth(min); var mday = date.getDate(); var day = Math.ceil(interval / dms); var ddays = diffDay(min, max); interval = day * dms; for (var _i2 = 0; _i2 < ddays + day; _i2 = _i2 + day) { ticks.push(new Date(_year, _month, mday + _i2).getTime()); } } else if (interval > HOUR_MS) { // 大于一个小时 var _date = new Date(min); var _year2 = _date.getFullYear(); var _month2 = _date.getMonth(min); var _day = _date.getDate(); var hour = _date.getHours(); var hours = AutoUtil.snapTo(SNAP_ARRAY, Math.ceil(interval / HOUR_MS)); var dHours = diffHour(min, max); interval = hours * HOUR_MS; for (var _i3 = 0; _i3 <= dHours + hours; _i3 = _i3 + hours) { ticks.push(new Date(_year2, _month2, _day, hour + _i3).getTime()); } } else if (interval > MINUTE_MS) { // 最小单位是分钟 var dMinus = diffMinus(min, max); var minutes = Math.ceil(interval / MINUTE_MS); interval = minutes * MINUTE_MS; for (var _i4 = 0; _i4 <= dMinus + minutes; _i4 = _i4 + minutes) { ticks.push(min + _i4 * MINUTE_MS); } } else { if (interval < 1000) { interval = 1000; } min = Math.floor(min / 1000) * 1000; var dSeconds = Math.ceil((max - min) / 1000); var seconds = Math.ceil(interval / 1000); interval = seconds * 1000; for (var _i5 = 0; _i5 < dSeconds + seconds; _i5 = _i5 + seconds) { ticks.push(min + _i5 * 1000); } } } if (!ticks.length) { min = Math.floor(min / 1000) * 1000; max = Math.ceil(max / 1000) * 1000; count = (max - min) / interval; for (var _i6 = 0; _i6 <= count; _i6++) { ticks.push(AutoUtil.fixedBase(interval * _i6 + min, interval)); } } return { max: max, min: min, interval: interval, ticks: ticks, count: ticks.length }; }; /***/ }), /* 212 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * @fileOverview 时间数据作为分类类型 * @author dxq613@gmail.com */ var Base = __webpack_require__(20); var Category = __webpack_require__(108); var fecha = __webpack_require__(110); var catAuto = __webpack_require__(109); var TimeUtil = __webpack_require__(100); var each = __webpack_require__(3); var isNumber = __webpack_require__(11); var isObject = __webpack_require__(22); var isString = __webpack_require__(12); /** * 度量的构造函数 * @class Scale.TimeCategory */ var TimeCategory = /*#__PURE__*/function (_Category) { _inheritsLoose(TimeCategory, _Category); function TimeCategory() { return _Category.apply(this, arguments) || this; } var _proto = TimeCategory.prototype; _proto._initDefaultCfg = function _initDefaultCfg() { _Category.prototype._initDefaultCfg.call(this); this.type = 'timeCat'; /** * 是否需要排序,默认进行排序 * @type {Boolean} */ this.sortable = true; this.tickCount = 5; /** * 时间格式化 * @type {String} */ this.mask = 'YYYY-MM-DD'; }; _proto.init = function init() { var self = this; var values = this.values; // 针对时间分类类型,会将时间统一转换为时间戳 each(values, function (v, i) { values[i] = self._toTimeStamp(v); }); if (this.sortable) { // 允许排序 values.sort(function (v1, v2) { return v1 - v2; }); } if (!self.ticks) { self.ticks = this.calculateTicks(); } } /** * 计算 ticks * @return {array} 返回 ticks 数组 */ ; _proto.calculateTicks = function calculateTicks() { var self = this; var count = self.tickCount; var ticks; if (count) { var temp = catAuto({ maxCount: count, data: self.values, isRounding: self.isRounding }); ticks = temp.ticks; } else { ticks = self.values; } return ticks; } /** * @override */ ; _proto.translate = function translate(value) { value = this._toTimeStamp(value); var index = this.values.indexOf(value); if (index === -1) { if (isNumber(value) && value < this.values.length) { index = value; } else { index = NaN; } } return index; } /** * @override */ ; _proto.scale = function scale(value) { var rangeMin = this.rangeMin(); var rangeMax = this.rangeMax(); var index = this.translate(value); var percent; if (this.values.length === 1 || isNaN(index)) { // is index is NAN should not be set as 0 percent = index; } else if (index > -1) { percent = index / (this.values.length - 1); } else { percent = 0; } return rangeMin + percent * (rangeMax - rangeMin); } /** * @override */ ; _proto.getText = function getText(value) { var result = ''; var index = this.translate(value); if (index > -1) { result = this.values[index]; } else { result = value; } var formatter = this.formatter; result = parseInt(result, 10); result = formatter ? formatter(result) : fecha.format(result, this.mask); return result; } /** * @override */ ; _proto.getTicks = function getTicks() { var self = this; var ticks = this.ticks; var rst = []; each(ticks, function (tick) { var obj; if (isObject(tick)) { obj = tick; } else { obj = { text: isString(tick) ? tick : self.getText(tick), value: self.scale(tick), tickValue: tick // 用于坐标轴上文本动画时确定前后帧的对应关系 }; } rst.push(obj); }); return rst; } // 将时间转换为时间戳 ; _proto._toTimeStamp = function _toTimeStamp(value) { return TimeUtil.toTimeStamp(value); }; return TimeCategory; }(Category); Base.TimeCat = TimeCategory; module.exports = TimeCategory; /***/ }), /* 213 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * @fileOverview 使用度量,进行log转换 * @author dxq613@gmail.com */ var each = __webpack_require__(3); var Base = __webpack_require__(20); var Linear = __webpack_require__(38); // 计算log function log(a, b) { if (a === 1) { return 1; } return Math.log(b) / Math.log(a); } /** * 度量的log计算 * @class Scale.Log */ var Log = /*#__PURE__*/function (_Linear) { _inheritsLoose(Log, _Linear); function Log() { return _Linear.apply(this, arguments) || this; } var _proto = Log.prototype; _proto._initDefaultCfg = function _initDefaultCfg() { _Linear.prototype._initDefaultCfg.call(this); this.type = 'log'; /** * @override * log 的坐标点的个数控制在10个以下 * @type {Number} */ this.tickCount = 10; /** * 进行log计算的基数 * @type {Number} */ this.base = 2; // 最小的tick,仅内部使用 this._minTick = null; } /** * @override */ ; _proto.calculateTicks = function calculateTicks() { var self = this; var base = self.base; var minTick; if (self.min < 0) { throw new Error('The minimum value must be greater than zero!'); } var maxTick = log(base, self.max); if (self.min > 0) { minTick = Math.floor(log(base, self.min)); } else { var values = self.values; var positiveMin = self.max; // 查找大于0的第一个值, 如果都小于0,默认为1 each(values, function (value) { if (value > 0 && value < positiveMin) { positiveMin = value; } }); if (positiveMin === self.max) { positiveMin = self.max / base; } if (positiveMin > 1) { positiveMin = 1; } minTick = Math.floor(log(base, positiveMin)); self._minTick = minTick; self.positiveMin = positiveMin; } var count = maxTick - minTick; var tickCount = self.tickCount; var avg = Math.ceil(count / tickCount); var ticks = []; for (var i = minTick; i < maxTick + avg; i = i + avg) { ticks.push(Math.pow(base, i)); } if (self.min === 0) { ticks.unshift(0); } return ticks; } // 获取度量计算时,value占的定义域百分比 ; _proto._getScalePercent = function _getScalePercent(value) { var max = this.max; var min = this.min; if (max === min) { return 0; } // 如果值小于等于0,则按照0处理 if (value <= 0) { return 0; } var base = this.base; var positiveMin = this.positiveMin; // 如果min == 0, 则根据比0大的最小值,计算比例关系。这个最小值作为坐标轴上的第二个tick,第一个是0但是不显示 if (positiveMin) { min = positiveMin * 1 / base; } var percent; // 如果数值小于次小值,那么就计算 value / 次小值 占整体的比例 if (value < positiveMin) { percent = value / positiveMin / (log(base, max) - log(base, min)); } else { percent = (log(base, value) - log(base, min)) / (log(base, max) - log(base, min)); } return percent; } /** * @override */ ; _proto.scale = function scale(value) { var percent = this._getScalePercent(value); var rangeMin = this.rangeMin(); var rangeMax = this.rangeMax(); return rangeMin + percent * (rangeMax - rangeMin); } /** * @override */ ; _proto.invert = function invert(value) { var base = this.base; var max = log(base, this.max); var rangeMin = this.rangeMin(); var range = this.rangeMax() - rangeMin; var min; var positiveMin = this.positiveMin; if (positiveMin) { if (value === 0) { return 0; } min = log(base, positiveMin / base); var appendPercent = 1 / (max - min) * range; // 0 到 positiveMin的占比 if (value < appendPercent) { // 落到 0 - positiveMin 之间 return value / appendPercent * positiveMin; } } else { min = log(base, this.min); } var percent = (value - rangeMin) / range; var tmp = percent * (max - min) + min; return Math.pow(base, tmp); }; return Log; }(Linear); Base.Log = Log; module.exports = Log; /***/ }), /* 214 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } /** * @fileOverview 使用pow进行度量计算 * @author dxq613@gmail.com */ var Base = __webpack_require__(20); var Linear = __webpack_require__(38); // 求以a为次幂,结果为b的基数,如 x^^a = b;求x function calBase(a, b) { var e = Math.E; var value = Math.pow(e, Math.log(b) / a); // 使用换底公式求底 return value; } /** * 度量的Pow计算 * @class Scale.Log */ var Pow = /*#__PURE__*/function (_Linear) { _inheritsLoose(Pow, _Linear); function Pow() { return _Linear.apply(this, arguments) || this; } var _proto = Pow.prototype; _proto._initDefaultCfg = function _initDefaultCfg() { _Linear.prototype._initDefaultCfg.call(this); this.type = 'pow'; /** * @override * pow 的坐标点的个数控制在10个以下 * @type {Number} */ this.tickCount = 10; /** * 进行pow计算的基数 * @type {Number} */ this.exponent = 2; } /** * @override */ ; _proto.calculateTicks = function calculateTicks() { var self = this; var exponent = self.exponent; var min; var max = Math.ceil(calBase(exponent, self.max)); if (self.min >= 0) { min = Math.floor(calBase(exponent, self.min)); } else { min = 0; } if (min > max) { var tmp = max; max = min; min = tmp; } var count = max - min; var tickCount = self.tickCount; var avg = Math.ceil(count / tickCount); var ticks = []; for (var i = min; i < max + avg; i = i + avg) { ticks.push(Math.pow(i, exponent)); } return ticks; } // 获取度量计算时,value占的定义域百分比 ; _proto._getScalePercent = function _getScalePercent(value) { var max = this.max; var min = this.min; if (max === min) { return 0; } var exponent = this.exponent; var percent = (calBase(exponent, value) - calBase(exponent, min)) / (calBase(exponent, max) - calBase(exponent, min)); return percent; } /** * @override */ ; _proto.scale = function scale(value) { var percent = this._getScalePercent(value); var rangeMin = this.rangeMin(); var rangeMax = this.rangeMax(); return rangeMin + percent * (rangeMax - rangeMin); } /** * @override */ ; _proto.invert = function invert(value) { var percent = (value - this.rangeMin()) / (this.rangeMax() - this.rangeMin()); var exponent = this.exponent; var max = calBase(exponent, this.max); var min = calBase(exponent, this.min); var tmp = percent * (max - min) + min; return Math.pow(tmp, exponent); }; return Pow; }(Linear); Base.Pow = Pow; module.exports = Pow; /***/ }), /* 215 */ /***/ (function(module, exports, __webpack_require__) { var _require = __webpack_require__(216), detect = _require.detect; var Util = __webpack_require__(1); var Event = __webpack_require__(221); var Group = __webpack_require__(115); var Timeline = __webpack_require__(228); var renderers = __webpack_require__(253); var browser = detect(); var isFirefox = browser && browser.name === 'firefox'; var Canvas = function Canvas(cfg) { Canvas.superclass.constructor.call(this, cfg); }; Canvas.CFG = { eventEnable: true, /** * 像素宽度 * @type {Number} */ width: null, /** * 像素高度 * @type {Number} */ height: null, /** * 画布宽度 * @type {Number} */ widthCanvas: null, /** * 画布高度 * @type {Number} */ heightCanvas: null, /** * CSS宽 * @type {String} */ widthStyle: null, /** * CSS高 * @type {String} */ heightStyle: null, /** * 容器DOM * @type {Object} */ containerDOM: null, /** * 当前Canvas的DOM * @type {Object} */ canvasDOM: null, /** * 屏幕像素比 * @type {Number} */ pixelRatio: null, /** * 渲染器,默认是canvas * @type {String} */ renderer: 'canvas', /** * 是否支持 CSS Transform * CSS transform 目前尚未经过长时间验证,为了避免影响上层业务,默认关闭,上层按需开启 */ supportCSSTransform: false }; Util.extend(Canvas, Group); Util.augment(Canvas, Event, { init: function init() { Canvas.superclass.init.call(this); this._setGlobalParam(); this._setContainer(); this._initPainter(); this._scale(); if (this.get('eventEnable')) { this.registerEvent(this); } }, _scale: function _scale() { if (this._cfg.renderType !== 'svg') { var pixelRatio = this.get('pixelRatio'); this.scale(pixelRatio, pixelRatio); } }, _setGlobalParam: function _setGlobalParam() { var renderType = this.get('renderer') || 'canvas'; if (renderType === 'svg') { this.set('pixelRatio', 1); } else if (!this.get('pixelRatio')) { this.set('pixelRatio', Util.getRatio()); } this._cfg.renderType = renderType; var renderer = renderers[renderType]; this._cfg.renderer = renderer; this._cfg.canvas = this; var timeline = new Timeline(this); this._cfg.timeline = timeline; }, _setContainer: function _setContainer() { var containerId = this.get('containerId'); var containerDOM = this.get('containerDOM'); if (!containerDOM) { containerDOM = document.getElementById(containerId); this.set('containerDOM', containerDOM); } Util.modifyCSS(containerDOM, { position: 'relative' }); }, _initPainter: function _initPainter() { var containerDOM = this.get('containerDOM'); var painter = new this._cfg.renderer.painter(containerDOM); this._cfg.painter = painter; this._cfg.canvasDOM = this._cfg.el = painter.canvas; this.changeSize(this.get('width'), this.get('height')); }, _resize: function _resize() { var canvasDOM = this.get('canvasDOM'); var widthCanvas = this.get('widthCanvas'); var heightCanvas = this.get('heightCanvas'); var widthStyle = this.get('widthStyle'); var heightStyle = this.get('heightStyle'); canvasDOM.style.width = widthStyle; canvasDOM.style.height = heightStyle; canvasDOM.setAttribute('width', widthCanvas); canvasDOM.setAttribute('height', heightCanvas); }, getWidth: function getWidth() { var pixelRatio = this.get('pixelRatio'); var width = this.get('width'); return width * pixelRatio; }, getHeight: function getHeight() { var pixelRatio = this.get('pixelRatio'); var height = this.get('height'); return height * pixelRatio; }, changeSize: function changeSize(width, height) { var pixelRatio = this.get('pixelRatio'); var widthCanvas = width * pixelRatio; var heightCanvas = height * pixelRatio; this.set('widthCanvas', widthCanvas); this.set('heightCanvas', heightCanvas); this.set('widthStyle', width + 'px'); this.set('heightStyle', height + 'px'); this.set('width', width); this.set('height', height); this._resize(); }, getPointByEvent: function getPointByEvent(ev) { var supportCSSTransform = this.get('supportCSSTransform'); if (supportCSSTransform) { var pixelRatio = this.get('pixelRatio') || 1; // For Firefox <= 38 if (isFirefox && !Util.isNil(ev.layerX) && ev.layerX !== ev.offsetX) { return { x: ev.layerX * pixelRatio, y: ev.layerY * pixelRatio }; } if (!Util.isNil(ev.offsetX)) { // For IE6+, Firefox >= 39, Chrome, Safari, Opera return { x: ev.offsetX * pixelRatio, y: ev.offsetY * pixelRatio }; } } // should calculate by self for other cases, like Safari in ios // TODO: support CSS transform var _this$getClientByEven = this.getClientByEvent(ev), clientX = _this$getClientByEven.x, clientY = _this$getClientByEven.y; return this.getPointByClient(clientX, clientY); }, // 获取 touch 事件的 clientX 和 clientY 需要单独处理 getClientByEvent: function getClientByEvent(ev) { var clientInfo = ev; if (ev.touches) { if (ev.type === 'touchend') { clientInfo = ev.changedTouches[0]; } else { clientInfo = ev.touches[0]; } } return { x: clientInfo.clientX, y: clientInfo.clientY }; }, /** * 将窗口坐标转变成 canvas 坐标 * @param {Number} clientX 窗口x坐标 * @param {Number} clientY 窗口y坐标 * @return {Object} canvas坐标 */ getPointByClient: function getPointByClient(clientX, clientY) { var el = this.get('el'); var pixelRatio = this.get('pixelRatio') || 1; var bbox = el.getBoundingClientRect(); return { x: (clientX - bbox.left) * pixelRatio, y: (clientY - bbox.top) * pixelRatio }; }, getClientByPoint: function getClientByPoint(x, y) { var el = this.get('el'); var bbox = el.getBoundingClientRect(); var pixelRatio = this.get('pixelRatio') || 1; return { clientX: x / pixelRatio + bbox.left, clientY: y / pixelRatio + bbox.top }; }, draw: function draw() { this._cfg.painter.draw(this); }, getShape: function getShape(x, y, e) { if (arguments.length === 3 && this._cfg.renderer.getShape) { return this._cfg.renderer.getShape.call(this, x, y, e); } return Canvas.superclass.getShape.call(this, x, y); }, getRenderer: function getRenderer() { return this._cfg.renderType; }, _drawSync: function _drawSync() { this._cfg.painter.drawSync(this); }, destroy: function destroy() { var cfg = this._cfg; var containerDOM = cfg.containerDOM; var canvasDOM = cfg.canvasDOM; if (canvasDOM && containerDOM) { containerDOM.removeChild(canvasDOM); } cfg.timeline.stop(); Canvas.superclass.destroy.call(this); } }); module.exports = Canvas; /***/ }), /* 216 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; Object.defineProperty(__webpack_exports__, "__esModule", { value: true }); /* WEBPACK VAR INJECTION */(function(process) {/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BrowserInfo", function() { return BrowserInfo; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "NodeInfo", function() { return NodeInfo; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "SearchBotDeviceInfo", function() { return SearchBotDeviceInfo; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "BotInfo", function() { return BotInfo; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "ReactNativeInfo", function() { return ReactNativeInfo; }); /* harmony export (immutable) */ __webpack_exports__["detect"] = detect; /* harmony export (immutable) */ __webpack_exports__["browserName"] = browserName; /* harmony export (immutable) */ __webpack_exports__["parseUserAgent"] = parseUserAgent; /* harmony export (immutable) */ __webpack_exports__["detectOS"] = detectOS; /* harmony export (immutable) */ __webpack_exports__["getNodeVersion"] = getNodeVersion; var __spreadArray = this && this.__spreadArray || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; var BrowserInfo = /** @class */ function () { function BrowserInfo(name, version, os) { this.name = name; this.version = version; this.os = os; this.type = 'browser'; } return BrowserInfo; }(); var NodeInfo = /** @class */ function () { function NodeInfo(version) { this.version = version; this.type = 'node'; this.name = 'node'; this.os = process.platform; } return NodeInfo; }(); var SearchBotDeviceInfo = /** @class */ function () { function SearchBotDeviceInfo(name, version, os, bot) { this.name = name; this.version = version; this.os = os; this.bot = bot; this.type = 'bot-device'; } return SearchBotDeviceInfo; }(); var BotInfo = /** @class */ function () { function BotInfo() { this.type = 'bot'; this.bot = true; // NOTE: deprecated test name instead this.name = 'bot'; this.version = null; this.os = null; } return BotInfo; }(); var ReactNativeInfo = /** @class */ function () { function ReactNativeInfo() { this.type = 'react-native'; this.name = 'react-native'; this.version = null; this.os = null; } return ReactNativeInfo; }(); // tslint:disable-next-line:max-line-length var SEARCHBOX_UA_REGEX = /alexa|bot|crawl(er|ing)|facebookexternalhit|feedburner|google web preview|nagios|postrank|pingdom|slurp|spider|yahoo!|yandex/; var SEARCHBOT_OS_REGEX = /(nuhk|curl|Googlebot|Yammybot|Openbot|Slurp|MSNBot|Ask\ Jeeves\/Teoma|ia_archiver)/; var REQUIRED_VERSION_PARTS = 3; var userAgentRules = [['aol', /AOLShield\/([0-9\._]+)/], ['edge', /Edge\/([0-9\._]+)/], ['edge-ios', /EdgiOS\/([0-9\._]+)/], ['yandexbrowser', /YaBrowser\/([0-9\._]+)/], ['kakaotalk', /KAKAOTALK\s([0-9\.]+)/], ['samsung', /SamsungBrowser\/([0-9\.]+)/], ['silk', /\bSilk\/([0-9._-]+)\b/], ['miui', /MiuiBrowser\/([0-9\.]+)$/], ['beaker', /BeakerBrowser\/([0-9\.]+)/], ['edge-chromium', /EdgA?\/([0-9\.]+)/], ['chromium-webview', /(?!Chrom.*OPR)wv\).*Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/], ['chrome', /(?!Chrom.*OPR)Chrom(?:e|ium)\/([0-9\.]+)(:?\s|$)/], ['phantomjs', /PhantomJS\/([0-9\.]+)(:?\s|$)/], ['crios', /CriOS\/([0-9\.]+)(:?\s|$)/], ['firefox', /Firefox\/([0-9\.]+)(?:\s|$)/], ['fxios', /FxiOS\/([0-9\.]+)/], ['opera-mini', /Opera Mini.*Version\/([0-9\.]+)/], ['opera', /Opera\/([0-9\.]+)(?:\s|$)/], ['opera', /OPR\/([0-9\.]+)(:?\s|$)/], ['ie', /Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/], ['ie', /MSIE\s([0-9\.]+);.*Trident\/[4-7].0/], ['ie', /MSIE\s(7\.0)/], ['bb10', /BB10;\sTouch.*Version\/([0-9\.]+)/], ['android', /Android\s([0-9\.]+)/], ['ios', /Version\/([0-9\._]+).*Mobile.*Safari.*/], ['safari', /Version\/([0-9\._]+).*Safari/], ['facebook', /FB[AS]V\/([0-9\.]+)/], ['instagram', /Instagram\s([0-9\.]+)/], ['ios-webview', /AppleWebKit\/([0-9\.]+).*Mobile/], ['ios-webview', /AppleWebKit\/([0-9\.]+).*Gecko\)$/], ['curl', /^curl\/([0-9\.]+)$/], ['searchbot', SEARCHBOX_UA_REGEX]]; var operatingSystemRules = [['iOS', /iP(hone|od|ad)/], ['Android OS', /Android/], ['BlackBerry OS', /BlackBerry|BB10/], ['Windows Mobile', /IEMobile/], ['Amazon OS', /Kindle/], ['Windows 3.11', /Win16/], ['Windows 95', /(Windows 95)|(Win95)|(Windows_95)/], ['Windows 98', /(Windows 98)|(Win98)/], ['Windows 2000', /(Windows NT 5.0)|(Windows 2000)/], ['Windows XP', /(Windows NT 5.1)|(Windows XP)/], ['Windows Server 2003', /(Windows NT 5.2)/], ['Windows Vista', /(Windows NT 6.0)/], ['Windows 7', /(Windows NT 6.1)/], ['Windows 8', /(Windows NT 6.2)/], ['Windows 8.1', /(Windows NT 6.3)/], ['Windows 10', /(Windows NT 10.0)/], ['Windows ME', /Windows ME/], ['Open BSD', /OpenBSD/], ['Sun OS', /SunOS/], ['Chrome OS', /CrOS/], ['Linux', /(Linux)|(X11)/], ['Mac OS', /(Mac_PowerPC)|(Macintosh)/], ['QNX', /QNX/], ['BeOS', /BeOS/], ['OS/2', /OS\/2/]]; function detect(userAgent) { if (!!userAgent) { return parseUserAgent(userAgent); } if (typeof document === 'undefined' && typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { return new ReactNativeInfo(); } if (typeof navigator !== 'undefined') { return parseUserAgent(navigator.userAgent); } return getNodeVersion(); } function matchUserAgent(ua) { // opted for using reduce here rather than Array#first with a regex.test call // this is primarily because using the reduce we only perform the regex // execution once rather than once for the test and for the exec again below // probably something that needs to be benchmarked though return ua !== '' && userAgentRules.reduce(function (matched, _a) { var browser = _a[0], regex = _a[1]; if (matched) { return matched; } var uaMatch = regex.exec(ua); return !!uaMatch && [browser, uaMatch]; }, false); } function browserName(ua) { var data = matchUserAgent(ua); return data ? data[0] : null; } function parseUserAgent(ua) { var matchedRule = matchUserAgent(ua); if (!matchedRule) { return null; } var name = matchedRule[0], match = matchedRule[1]; if (name === 'searchbot') { return new BotInfo(); } // Do not use RegExp for split operation as some browser do not support it (See: http://blog.stevenlevithan.com/archives/cross-browser-split) var versionParts = match[1] && match[1].split('.').join('_').split('_').slice(0, 3); if (versionParts) { if (versionParts.length < REQUIRED_VERSION_PARTS) { versionParts = __spreadArray(__spreadArray([], versionParts, true), createVersionParts(REQUIRED_VERSION_PARTS - versionParts.length), true); } } else { versionParts = []; } var version = versionParts.join('.'); var os = detectOS(ua); var searchBotMatch = SEARCHBOT_OS_REGEX.exec(ua); if (searchBotMatch && searchBotMatch[1]) { return new SearchBotDeviceInfo(name, version, os, searchBotMatch[1]); } return new BrowserInfo(name, version, os); } function detectOS(ua) { for (var ii = 0, count = operatingSystemRules.length; ii < count; ii++) { var _a = operatingSystemRules[ii], os = _a[0], regex = _a[1]; var match = regex.exec(ua); if (match) { return os; } } return null; } function getNodeVersion() { var isNode = typeof process !== 'undefined' && process.version; return isNode ? new NodeInfo(process.version.slice(1)) : null; } function createVersionParts(count) { var output = []; for (var ii = 0; ii < count; ii++) { output.push('0'); } return output; } /* WEBPACK VAR INJECTION */}.call(__webpack_exports__, __webpack_require__(217))) /***/ }), /* 217 */ /***/ (function(module, exports) { // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout() { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } })(); function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e) { try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e) { // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while (len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return []; }; process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/'; }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function () { return 0; }; /***/ }), /* 218 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.sub = exports.mul = undefined; exports.create = create; exports.fromMat4 = fromMat4; exports.clone = clone; exports.copy = copy; exports.fromValues = fromValues; exports.set = set; exports.identity = identity; exports.transpose = transpose; exports.invert = invert; exports.adjoint = adjoint; exports.determinant = determinant; exports.multiply = multiply; exports.translate = translate; exports.rotate = rotate; exports.scale = scale; exports.fromTranslation = fromTranslation; exports.fromRotation = fromRotation; exports.fromScaling = fromScaling; exports.fromMat2d = fromMat2d; exports.fromQuat = fromQuat; exports.normalFromMat4 = normalFromMat4; exports.projection = projection; exports.str = str; exports.frob = frob; exports.add = add; exports.subtract = subtract; exports.multiplyScalar = multiplyScalar; exports.multiplyScalarAndAdd = multiplyScalarAndAdd; exports.exactEquals = exactEquals; exports.equals = equals; var _common = __webpack_require__(74); var glMatrix = _interopRequireWildcard(_common); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * 3x3 Matrix * @module mat3 */ /** * Creates a new identity mat3 * * @returns {mat3} a new 3x3 matrix */ function create() { var out = new glMatrix.ARRAY_TYPE(9); if (glMatrix.ARRAY_TYPE != Float32Array) { out[1] = 0; out[2] = 0; out[3] = 0; out[5] = 0; out[6] = 0; out[7] = 0; } out[0] = 1; out[4] = 1; out[8] = 1; return out; } /** * Copies the upper-left 3x3 values into the given mat3. * * @param {mat3} out the receiving 3x3 matrix * @param {mat4} a the source 4x4 matrix * @returns {mat3} out */ function fromMat4(out, a) { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[4]; out[4] = a[5]; out[5] = a[6]; out[6] = a[8]; out[7] = a[9]; out[8] = a[10]; return out; } /** * Creates a new mat3 initialized with values from an existing matrix * * @param {mat3} a matrix to clone * @returns {mat3} a new 3x3 matrix */ function clone(a) { var out = new glMatrix.ARRAY_TYPE(9); out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4]; out[5] = a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; return out; } /** * Copy the values from one mat3 to another * * @param {mat3} out the receiving matrix * @param {mat3} a the source matrix * @returns {mat3} out */ function copy(out, a) { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4]; out[5] = a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; return out; } /** * Create a new mat3 with the given values * * @param {Number} m00 Component in column 0, row 0 position (index 0) * @param {Number} m01 Component in column 0, row 1 position (index 1) * @param {Number} m02 Component in column 0, row 2 position (index 2) * @param {Number} m10 Component in column 1, row 0 position (index 3) * @param {Number} m11 Component in column 1, row 1 position (index 4) * @param {Number} m12 Component in column 1, row 2 position (index 5) * @param {Number} m20 Component in column 2, row 0 position (index 6) * @param {Number} m21 Component in column 2, row 1 position (index 7) * @param {Number} m22 Component in column 2, row 2 position (index 8) * @returns {mat3} A new mat3 */ function fromValues(m00, m01, m02, m10, m11, m12, m20, m21, m22) { var out = new glMatrix.ARRAY_TYPE(9); out[0] = m00; out[1] = m01; out[2] = m02; out[3] = m10; out[4] = m11; out[5] = m12; out[6] = m20; out[7] = m21; out[8] = m22; return out; } /** * Set the components of a mat3 to the given values * * @param {mat3} out the receiving matrix * @param {Number} m00 Component in column 0, row 0 position (index 0) * @param {Number} m01 Component in column 0, row 1 position (index 1) * @param {Number} m02 Component in column 0, row 2 position (index 2) * @param {Number} m10 Component in column 1, row 0 position (index 3) * @param {Number} m11 Component in column 1, row 1 position (index 4) * @param {Number} m12 Component in column 1, row 2 position (index 5) * @param {Number} m20 Component in column 2, row 0 position (index 6) * @param {Number} m21 Component in column 2, row 1 position (index 7) * @param {Number} m22 Component in column 2, row 2 position (index 8) * @returns {mat3} out */ function set(out, m00, m01, m02, m10, m11, m12, m20, m21, m22) { out[0] = m00; out[1] = m01; out[2] = m02; out[3] = m10; out[4] = m11; out[5] = m12; out[6] = m20; out[7] = m21; out[8] = m22; return out; } /** * Set a mat3 to the identity matrix * * @param {mat3} out the receiving matrix * @returns {mat3} out */ function identity(out) { out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 1; out[5] = 0; out[6] = 0; out[7] = 0; out[8] = 1; return out; } /** * Transpose the values of a mat3 * * @param {mat3} out the receiving matrix * @param {mat3} a the source matrix * @returns {mat3} out */ function transpose(out, a) { // If we are transposing ourselves we can skip a few steps but have to cache some values if (out === a) { var a01 = a[1], a02 = a[2], a12 = a[5]; out[1] = a[3]; out[2] = a[6]; out[3] = a01; out[5] = a[7]; out[6] = a02; out[7] = a12; } else { out[0] = a[0]; out[1] = a[3]; out[2] = a[6]; out[3] = a[1]; out[4] = a[4]; out[5] = a[7]; out[6] = a[2]; out[7] = a[5]; out[8] = a[8]; } return out; } /** * Inverts a mat3 * * @param {mat3} out the receiving matrix * @param {mat3} a the source matrix * @returns {mat3} out */ function invert(out, a) { var a00 = a[0], a01 = a[1], a02 = a[2]; var a10 = a[3], a11 = a[4], a12 = a[5]; var a20 = a[6], a21 = a[7], a22 = a[8]; var b01 = a22 * a11 - a12 * a21; var b11 = -a22 * a10 + a12 * a20; var b21 = a21 * a10 - a11 * a20; // Calculate the determinant var det = a00 * b01 + a01 * b11 + a02 * b21; if (!det) { return null; } det = 1.0 / det; out[0] = b01 * det; out[1] = (-a22 * a01 + a02 * a21) * det; out[2] = (a12 * a01 - a02 * a11) * det; out[3] = b11 * det; out[4] = (a22 * a00 - a02 * a20) * det; out[5] = (-a12 * a00 + a02 * a10) * det; out[6] = b21 * det; out[7] = (-a21 * a00 + a01 * a20) * det; out[8] = (a11 * a00 - a01 * a10) * det; return out; } /** * Calculates the adjugate of a mat3 * * @param {mat3} out the receiving matrix * @param {mat3} a the source matrix * @returns {mat3} out */ function adjoint(out, a) { var a00 = a[0], a01 = a[1], a02 = a[2]; var a10 = a[3], a11 = a[4], a12 = a[5]; var a20 = a[6], a21 = a[7], a22 = a[8]; out[0] = a11 * a22 - a12 * a21; out[1] = a02 * a21 - a01 * a22; out[2] = a01 * a12 - a02 * a11; out[3] = a12 * a20 - a10 * a22; out[4] = a00 * a22 - a02 * a20; out[5] = a02 * a10 - a00 * a12; out[6] = a10 * a21 - a11 * a20; out[7] = a01 * a20 - a00 * a21; out[8] = a00 * a11 - a01 * a10; return out; } /** * Calculates the determinant of a mat3 * * @param {mat3} a the source matrix * @returns {Number} determinant of a */ function determinant(a) { var a00 = a[0], a01 = a[1], a02 = a[2]; var a10 = a[3], a11 = a[4], a12 = a[5]; var a20 = a[6], a21 = a[7], a22 = a[8]; return a00 * (a22 * a11 - a12 * a21) + a01 * (-a22 * a10 + a12 * a20) + a02 * (a21 * a10 - a11 * a20); } /** * Multiplies two mat3's * * @param {mat3} out the receiving matrix * @param {mat3} a the first operand * @param {mat3} b the second operand * @returns {mat3} out */ function multiply(out, a, b) { var a00 = a[0], a01 = a[1], a02 = a[2]; var a10 = a[3], a11 = a[4], a12 = a[5]; var a20 = a[6], a21 = a[7], a22 = a[8]; var b00 = b[0], b01 = b[1], b02 = b[2]; var b10 = b[3], b11 = b[4], b12 = b[5]; var b20 = b[6], b21 = b[7], b22 = b[8]; out[0] = b00 * a00 + b01 * a10 + b02 * a20; out[1] = b00 * a01 + b01 * a11 + b02 * a21; out[2] = b00 * a02 + b01 * a12 + b02 * a22; out[3] = b10 * a00 + b11 * a10 + b12 * a20; out[4] = b10 * a01 + b11 * a11 + b12 * a21; out[5] = b10 * a02 + b11 * a12 + b12 * a22; out[6] = b20 * a00 + b21 * a10 + b22 * a20; out[7] = b20 * a01 + b21 * a11 + b22 * a21; out[8] = b20 * a02 + b21 * a12 + b22 * a22; return out; } /** * Translate a mat3 by the given vector * * @param {mat3} out the receiving matrix * @param {mat3} a the matrix to translate * @param {vec2} v vector to translate by * @returns {mat3} out */ function translate(out, a, v) { var a00 = a[0], a01 = a[1], a02 = a[2], a10 = a[3], a11 = a[4], a12 = a[5], a20 = a[6], a21 = a[7], a22 = a[8], x = v[0], y = v[1]; out[0] = a00; out[1] = a01; out[2] = a02; out[3] = a10; out[4] = a11; out[5] = a12; out[6] = x * a00 + y * a10 + a20; out[7] = x * a01 + y * a11 + a21; out[8] = x * a02 + y * a12 + a22; return out; } /** * Rotates a mat3 by the given angle * * @param {mat3} out the receiving matrix * @param {mat3} a the matrix to rotate * @param {Number} rad the angle to rotate the matrix by * @returns {mat3} out */ function rotate(out, a, rad) { var a00 = a[0], a01 = a[1], a02 = a[2], a10 = a[3], a11 = a[4], a12 = a[5], a20 = a[6], a21 = a[7], a22 = a[8], s = Math.sin(rad), c = Math.cos(rad); out[0] = c * a00 + s * a10; out[1] = c * a01 + s * a11; out[2] = c * a02 + s * a12; out[3] = c * a10 - s * a00; out[4] = c * a11 - s * a01; out[5] = c * a12 - s * a02; out[6] = a20; out[7] = a21; out[8] = a22; return out; } ; /** * Scales the mat3 by the dimensions in the given vec2 * * @param {mat3} out the receiving matrix * @param {mat3} a the matrix to rotate * @param {vec2} v the vec2 to scale the matrix by * @returns {mat3} out **/ function scale(out, a, v) { var x = v[0], y = v[1]; out[0] = x * a[0]; out[1] = x * a[1]; out[2] = x * a[2]; out[3] = y * a[3]; out[4] = y * a[4]; out[5] = y * a[5]; out[6] = a[6]; out[7] = a[7]; out[8] = a[8]; return out; } /** * Creates a matrix from a vector translation * This is equivalent to (but much faster than): * * mat3.identity(dest); * mat3.translate(dest, dest, vec); * * @param {mat3} out mat3 receiving operation result * @param {vec2} v Translation vector * @returns {mat3} out */ function fromTranslation(out, v) { out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = 1; out[5] = 0; out[6] = v[0]; out[7] = v[1]; out[8] = 1; return out; } /** * Creates a matrix from a given angle * This is equivalent to (but much faster than): * * mat3.identity(dest); * mat3.rotate(dest, dest, rad); * * @param {mat3} out mat3 receiving operation result * @param {Number} rad the angle to rotate the matrix by * @returns {mat3} out */ function fromRotation(out, rad) { var s = Math.sin(rad), c = Math.cos(rad); out[0] = c; out[1] = s; out[2] = 0; out[3] = -s; out[4] = c; out[5] = 0; out[6] = 0; out[7] = 0; out[8] = 1; return out; } /** * Creates a matrix from a vector scaling * This is equivalent to (but much faster than): * * mat3.identity(dest); * mat3.scale(dest, dest, vec); * * @param {mat3} out mat3 receiving operation result * @param {vec2} v Scaling vector * @returns {mat3} out */ function fromScaling(out, v) { out[0] = v[0]; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = v[1]; out[5] = 0; out[6] = 0; out[7] = 0; out[8] = 1; return out; } /** * Copies the values from a mat2d into a mat3 * * @param {mat3} out the receiving matrix * @param {mat2d} a the matrix to copy * @returns {mat3} out **/ function fromMat2d(out, a) { out[0] = a[0]; out[1] = a[1]; out[2] = 0; out[3] = a[2]; out[4] = a[3]; out[5] = 0; out[6] = a[4]; out[7] = a[5]; out[8] = 1; return out; } /** * Calculates a 3x3 matrix from the given quaternion * * @param {mat3} out mat3 receiving operation result * @param {quat} q Quaternion to create matrix from * * @returns {mat3} out */ function fromQuat(out, q) { var x = q[0], y = q[1], z = q[2], w = q[3]; var x2 = x + x; var y2 = y + y; var z2 = z + z; var xx = x * x2; var yx = y * x2; var yy = y * y2; var zx = z * x2; var zy = z * y2; var zz = z * z2; var wx = w * x2; var wy = w * y2; var wz = w * z2; out[0] = 1 - yy - zz; out[3] = yx - wz; out[6] = zx + wy; out[1] = yx + wz; out[4] = 1 - xx - zz; out[7] = zy - wx; out[2] = zx - wy; out[5] = zy + wx; out[8] = 1 - xx - yy; return out; } /** * Calculates a 3x3 normal matrix (transpose inverse) from the 4x4 matrix * * @param {mat3} out mat3 receiving operation result * @param {mat4} a Mat4 to derive the normal matrix from * * @returns {mat3} out */ function normalFromMat4(out, a) { var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3]; var a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7]; var a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11]; var a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; var b00 = a00 * a11 - a01 * a10; var b01 = a00 * a12 - a02 * a10; var b02 = a00 * a13 - a03 * a10; var b03 = a01 * a12 - a02 * a11; var b04 = a01 * a13 - a03 * a11; var b05 = a02 * a13 - a03 * a12; var b06 = a20 * a31 - a21 * a30; var b07 = a20 * a32 - a22 * a30; var b08 = a20 * a33 - a23 * a30; var b09 = a21 * a32 - a22 * a31; var b10 = a21 * a33 - a23 * a31; var b11 = a22 * a33 - a23 * a32; // Calculate the determinant var det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; if (!det) { return null; } det = 1.0 / det; out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; out[1] = (a12 * b08 - a10 * b11 - a13 * b07) * det; out[2] = (a10 * b10 - a11 * b08 + a13 * b06) * det; out[3] = (a02 * b10 - a01 * b11 - a03 * b09) * det; out[4] = (a00 * b11 - a02 * b08 + a03 * b07) * det; out[5] = (a01 * b08 - a00 * b10 - a03 * b06) * det; out[6] = (a31 * b05 - a32 * b04 + a33 * b03) * det; out[7] = (a32 * b02 - a30 * b05 - a33 * b01) * det; out[8] = (a30 * b04 - a31 * b02 + a33 * b00) * det; return out; } /** * Generates a 2D projection matrix with the given bounds * * @param {mat3} out mat3 frustum matrix will be written into * @param {number} width Width of your gl context * @param {number} height Height of gl context * @returns {mat3} out */ function projection(out, width, height) { out[0] = 2 / width; out[1] = 0; out[2] = 0; out[3] = 0; out[4] = -2 / height; out[5] = 0; out[6] = -1; out[7] = 1; out[8] = 1; return out; } /** * Returns a string representation of a mat3 * * @param {mat3} a matrix to represent as a string * @returns {String} string representation of the matrix */ function str(a) { return 'mat3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ', ' + a[3] + ', ' + a[4] + ', ' + a[5] + ', ' + a[6] + ', ' + a[7] + ', ' + a[8] + ')'; } /** * Returns Frobenius norm of a mat3 * * @param {mat3} a the matrix to calculate Frobenius norm of * @returns {Number} Frobenius norm */ function frob(a) { return Math.sqrt(Math.pow(a[0], 2) + Math.pow(a[1], 2) + Math.pow(a[2], 2) + Math.pow(a[3], 2) + Math.pow(a[4], 2) + Math.pow(a[5], 2) + Math.pow(a[6], 2) + Math.pow(a[7], 2) + Math.pow(a[8], 2)); } /** * Adds two mat3's * * @param {mat3} out the receiving matrix * @param {mat3} a the first operand * @param {mat3} b the second operand * @returns {mat3} out */ function add(out, a, b) { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; out[2] = a[2] + b[2]; out[3] = a[3] + b[3]; out[4] = a[4] + b[4]; out[5] = a[5] + b[5]; out[6] = a[6] + b[6]; out[7] = a[7] + b[7]; out[8] = a[8] + b[8]; return out; } /** * Subtracts matrix b from matrix a * * @param {mat3} out the receiving matrix * @param {mat3} a the first operand * @param {mat3} b the second operand * @returns {mat3} out */ function subtract(out, a, b) { out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; out[2] = a[2] - b[2]; out[3] = a[3] - b[3]; out[4] = a[4] - b[4]; out[5] = a[5] - b[5]; out[6] = a[6] - b[6]; out[7] = a[7] - b[7]; out[8] = a[8] - b[8]; return out; } /** * Multiply each element of the matrix by a scalar. * * @param {mat3} out the receiving matrix * @param {mat3} a the matrix to scale * @param {Number} b amount to scale the matrix's elements by * @returns {mat3} out */ function multiplyScalar(out, a, b) { out[0] = a[0] * b; out[1] = a[1] * b; out[2] = a[2] * b; out[3] = a[3] * b; out[4] = a[4] * b; out[5] = a[5] * b; out[6] = a[6] * b; out[7] = a[7] * b; out[8] = a[8] * b; return out; } /** * Adds two mat3's after multiplying each element of the second operand by a scalar value. * * @param {mat3} out the receiving vector * @param {mat3} a the first operand * @param {mat3} b the second operand * @param {Number} scale the amount to scale b's elements by before adding * @returns {mat3} out */ function multiplyScalarAndAdd(out, a, b, scale) { out[0] = a[0] + b[0] * scale; out[1] = a[1] + b[1] * scale; out[2] = a[2] + b[2] * scale; out[3] = a[3] + b[3] * scale; out[4] = a[4] + b[4] * scale; out[5] = a[5] + b[5] * scale; out[6] = a[6] + b[6] * scale; out[7] = a[7] + b[7] * scale; out[8] = a[8] + b[8] * scale; return out; } /** * Returns whether or not the matrices have exactly the same elements in the same position (when compared with ===) * * @param {mat3} a The first matrix. * @param {mat3} b The second matrix. * @returns {Boolean} True if the matrices are equal, false otherwise. */ function exactEquals(a, b) { return a[0] === b[0] && a[1] === b[1] && a[2] === b[2] && a[3] === b[3] && a[4] === b[4] && a[5] === b[5] && a[6] === b[6] && a[7] === b[7] && a[8] === b[8]; } /** * Returns whether or not the matrices have approximately the same elements in the same position. * * @param {mat3} a The first matrix. * @param {mat3} b The second matrix. * @returns {Boolean} True if the matrices are equal, false otherwise. */ function equals(a, b) { var a0 = a[0], a1 = a[1], a2 = a[2], a3 = a[3], a4 = a[4], a5 = a[5], a6 = a[6], a7 = a[7], a8 = a[8]; var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3], b4 = b[4], b5 = b[5], b6 = b[6], b7 = b[7], b8 = b[8]; return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)) && Math.abs(a3 - b3) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a3), Math.abs(b3)) && Math.abs(a4 - b4) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a4), Math.abs(b4)) && Math.abs(a5 - b5) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a5), Math.abs(b5)) && Math.abs(a6 - b6) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a6), Math.abs(b6)) && Math.abs(a7 - b7) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a7), Math.abs(b7)) && Math.abs(a8 - b8) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a8), Math.abs(b8)); } /** * Alias for {@link mat3.multiply} * @function */ var mul = exports.mul = multiply; /** * Alias for {@link mat3.subtract} * @function */ var sub = exports.sub = subtract; /***/ }), /* 219 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.forEach = exports.sqrLen = exports.sqrDist = exports.dist = exports.div = exports.mul = exports.sub = exports.len = undefined; exports.create = create; exports.clone = clone; exports.fromValues = fromValues; exports.copy = copy; exports.set = set; exports.add = add; exports.subtract = subtract; exports.multiply = multiply; exports.divide = divide; exports.ceil = ceil; exports.floor = floor; exports.min = min; exports.max = max; exports.round = round; exports.scale = scale; exports.scaleAndAdd = scaleAndAdd; exports.distance = distance; exports.squaredDistance = squaredDistance; exports.length = length; exports.squaredLength = squaredLength; exports.negate = negate; exports.inverse = inverse; exports.normalize = normalize; exports.dot = dot; exports.cross = cross; exports.lerp = lerp; exports.random = random; exports.transformMat2 = transformMat2; exports.transformMat2d = transformMat2d; exports.transformMat3 = transformMat3; exports.transformMat4 = transformMat4; exports.rotate = rotate; exports.angle = angle; exports.str = str; exports.exactEquals = exactEquals; exports.equals = equals; var _common = __webpack_require__(74); var glMatrix = _interopRequireWildcard(_common); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * 2 Dimensional Vector * @module vec2 */ /** * Creates a new, empty vec2 * * @returns {vec2} a new 2D vector */ function create() { var out = new glMatrix.ARRAY_TYPE(2); if (glMatrix.ARRAY_TYPE != Float32Array) { out[0] = 0; out[1] = 0; } return out; } /** * Creates a new vec2 initialized with values from an existing vector * * @param {vec2} a vector to clone * @returns {vec2} a new 2D vector */ function clone(a) { var out = new glMatrix.ARRAY_TYPE(2); out[0] = a[0]; out[1] = a[1]; return out; } /** * Creates a new vec2 initialized with the given values * * @param {Number} x X component * @param {Number} y Y component * @returns {vec2} a new 2D vector */ function fromValues(x, y) { var out = new glMatrix.ARRAY_TYPE(2); out[0] = x; out[1] = y; return out; } /** * Copy the values from one vec2 to another * * @param {vec2} out the receiving vector * @param {vec2} a the source vector * @returns {vec2} out */ function copy(out, a) { out[0] = a[0]; out[1] = a[1]; return out; } /** * Set the components of a vec2 to the given values * * @param {vec2} out the receiving vector * @param {Number} x X component * @param {Number} y Y component * @returns {vec2} out */ function set(out, x, y) { out[0] = x; out[1] = y; return out; } /** * Adds two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ function add(out, a, b) { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; return out; } /** * Subtracts vector b from vector a * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ function subtract(out, a, b) { out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; return out; } /** * Multiplies two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ function multiply(out, a, b) { out[0] = a[0] * b[0]; out[1] = a[1] * b[1]; return out; } /** * Divides two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ function divide(out, a, b) { out[0] = a[0] / b[0]; out[1] = a[1] / b[1]; return out; } /** * Math.ceil the components of a vec2 * * @param {vec2} out the receiving vector * @param {vec2} a vector to ceil * @returns {vec2} out */ function ceil(out, a) { out[0] = Math.ceil(a[0]); out[1] = Math.ceil(a[1]); return out; } /** * Math.floor the components of a vec2 * * @param {vec2} out the receiving vector * @param {vec2} a vector to floor * @returns {vec2} out */ function floor(out, a) { out[0] = Math.floor(a[0]); out[1] = Math.floor(a[1]); return out; } /** * Returns the minimum of two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ function min(out, a, b) { out[0] = Math.min(a[0], b[0]); out[1] = Math.min(a[1], b[1]); return out; } /** * Returns the maximum of two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec2} out */ function max(out, a, b) { out[0] = Math.max(a[0], b[0]); out[1] = Math.max(a[1], b[1]); return out; } /** * Math.round the components of a vec2 * * @param {vec2} out the receiving vector * @param {vec2} a vector to round * @returns {vec2} out */ function round(out, a) { out[0] = Math.round(a[0]); out[1] = Math.round(a[1]); return out; } /** * Scales a vec2 by a scalar number * * @param {vec2} out the receiving vector * @param {vec2} a the vector to scale * @param {Number} b amount to scale the vector by * @returns {vec2} out */ function scale(out, a, b) { out[0] = a[0] * b; out[1] = a[1] * b; return out; } /** * Adds two vec2's after scaling the second operand by a scalar value * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @param {Number} scale the amount to scale b by before adding * @returns {vec2} out */ function scaleAndAdd(out, a, b, scale) { out[0] = a[0] + b[0] * scale; out[1] = a[1] + b[1] * scale; return out; } /** * Calculates the euclidian distance between two vec2's * * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {Number} distance between a and b */ function distance(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return Math.sqrt(x * x + y * y); } /** * Calculates the squared euclidian distance between two vec2's * * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {Number} squared distance between a and b */ function squaredDistance(a, b) { var x = b[0] - a[0], y = b[1] - a[1]; return x * x + y * y; } /** * Calculates the length of a vec2 * * @param {vec2} a vector to calculate length of * @returns {Number} length of a */ function length(a) { var x = a[0], y = a[1]; return Math.sqrt(x * x + y * y); } /** * Calculates the squared length of a vec2 * * @param {vec2} a vector to calculate squared length of * @returns {Number} squared length of a */ function squaredLength(a) { var x = a[0], y = a[1]; return x * x + y * y; } /** * Negates the components of a vec2 * * @param {vec2} out the receiving vector * @param {vec2} a vector to negate * @returns {vec2} out */ function negate(out, a) { out[0] = -a[0]; out[1] = -a[1]; return out; } /** * Returns the inverse of the components of a vec2 * * @param {vec2} out the receiving vector * @param {vec2} a vector to invert * @returns {vec2} out */ function inverse(out, a) { out[0] = 1.0 / a[0]; out[1] = 1.0 / a[1]; return out; } /** * Normalize a vec2 * * @param {vec2} out the receiving vector * @param {vec2} a vector to normalize * @returns {vec2} out */ function normalize(out, a) { var x = a[0], y = a[1]; var len = x * x + y * y; if (len > 0) { //TODO: evaluate use of glm_invsqrt here? len = 1 / Math.sqrt(len); out[0] = a[0] * len; out[1] = a[1] * len; } return out; } /** * Calculates the dot product of two vec2's * * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {Number} dot product of a and b */ function dot(a, b) { return a[0] * b[0] + a[1] * b[1]; } /** * Computes the cross product of two vec2's * Note that the cross product must by definition produce a 3D vector * * @param {vec3} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @returns {vec3} out */ function cross(out, a, b) { var z = a[0] * b[1] - a[1] * b[0]; out[0] = out[1] = 0; out[2] = z; return out; } /** * Performs a linear interpolation between two vec2's * * @param {vec2} out the receiving vector * @param {vec2} a the first operand * @param {vec2} b the second operand * @param {Number} t interpolation amount, in the range [0-1], between the two inputs * @returns {vec2} out */ function lerp(out, a, b, t) { var ax = a[0], ay = a[1]; out[0] = ax + t * (b[0] - ax); out[1] = ay + t * (b[1] - ay); return out; } /** * Generates a random vector with the given scale * * @param {vec2} out the receiving vector * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned * @returns {vec2} out */ function random(out, scale) { scale = scale || 1.0; var r = glMatrix.RANDOM() * 2.0 * Math.PI; out[0] = Math.cos(r) * scale; out[1] = Math.sin(r) * scale; return out; } /** * Transforms the vec2 with a mat2 * * @param {vec2} out the receiving vector * @param {vec2} a the vector to transform * @param {mat2} m matrix to transform with * @returns {vec2} out */ function transformMat2(out, a, m) { var x = a[0], y = a[1]; out[0] = m[0] * x + m[2] * y; out[1] = m[1] * x + m[3] * y; return out; } /** * Transforms the vec2 with a mat2d * * @param {vec2} out the receiving vector * @param {vec2} a the vector to transform * @param {mat2d} m matrix to transform with * @returns {vec2} out */ function transformMat2d(out, a, m) { var x = a[0], y = a[1]; out[0] = m[0] * x + m[2] * y + m[4]; out[1] = m[1] * x + m[3] * y + m[5]; return out; } /** * Transforms the vec2 with a mat3 * 3rd vector component is implicitly '1' * * @param {vec2} out the receiving vector * @param {vec2} a the vector to transform * @param {mat3} m matrix to transform with * @returns {vec2} out */ function transformMat3(out, a, m) { var x = a[0], y = a[1]; out[0] = m[0] * x + m[3] * y + m[6]; out[1] = m[1] * x + m[4] * y + m[7]; return out; } /** * Transforms the vec2 with a mat4 * 3rd vector component is implicitly '0' * 4th vector component is implicitly '1' * * @param {vec2} out the receiving vector * @param {vec2} a the vector to transform * @param {mat4} m matrix to transform with * @returns {vec2} out */ function transformMat4(out, a, m) { var x = a[0]; var y = a[1]; out[0] = m[0] * x + m[4] * y + m[12]; out[1] = m[1] * x + m[5] * y + m[13]; return out; } /** * Rotate a 2D vector * @param {vec2} out The receiving vec2 * @param {vec2} a The vec2 point to rotate * @param {vec2} b The origin of the rotation * @param {Number} c The angle of rotation * @returns {vec2} out */ function rotate(out, a, b, c) { //Translate point to the origin var p0 = a[0] - b[0], p1 = a[1] - b[1], sinC = Math.sin(c), cosC = Math.cos(c); //perform rotation and translate to correct position out[0] = p0 * cosC - p1 * sinC + b[0]; out[1] = p0 * sinC + p1 * cosC + b[1]; return out; } /** * Get the angle between two 2D vectors * @param {vec2} a The first operand * @param {vec2} b The second operand * @returns {Number} The angle in radians */ function angle(a, b) { var x1 = a[0], y1 = a[1], x2 = b[0], y2 = b[1]; var len1 = x1 * x1 + y1 * y1; if (len1 > 0) { //TODO: evaluate use of glm_invsqrt here? len1 = 1 / Math.sqrt(len1); } var len2 = x2 * x2 + y2 * y2; if (len2 > 0) { //TODO: evaluate use of glm_invsqrt here? len2 = 1 / Math.sqrt(len2); } var cosine = (x1 * x2 + y1 * y2) * len1 * len2; if (cosine > 1.0) { return 0; } else if (cosine < -1.0) { return Math.PI; } else { return Math.acos(cosine); } } /** * Returns a string representation of a vector * * @param {vec2} a vector to represent as a string * @returns {String} string representation of the vector */ function str(a) { return 'vec2(' + a[0] + ', ' + a[1] + ')'; } /** * Returns whether or not the vectors exactly have the same elements in the same position (when compared with ===) * * @param {vec2} a The first vector. * @param {vec2} b The second vector. * @returns {Boolean} True if the vectors are equal, false otherwise. */ function exactEquals(a, b) { return a[0] === b[0] && a[1] === b[1]; } /** * Returns whether or not the vectors have approximately the same elements in the same position. * * @param {vec2} a The first vector. * @param {vec2} b The second vector. * @returns {Boolean} True if the vectors are equal, false otherwise. */ function equals(a, b) { var a0 = a[0], a1 = a[1]; var b0 = b[0], b1 = b[1]; return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)); } /** * Alias for {@link vec2.length} * @function */ var len = exports.len = length; /** * Alias for {@link vec2.subtract} * @function */ var sub = exports.sub = subtract; /** * Alias for {@link vec2.multiply} * @function */ var mul = exports.mul = multiply; /** * Alias for {@link vec2.divide} * @function */ var div = exports.div = divide; /** * Alias for {@link vec2.distance} * @function */ var dist = exports.dist = distance; /** * Alias for {@link vec2.squaredDistance} * @function */ var sqrDist = exports.sqrDist = squaredDistance; /** * Alias for {@link vec2.squaredLength} * @function */ var sqrLen = exports.sqrLen = squaredLength; /** * Perform some operation over an array of vec2s. * * @param {Array} a the array of vectors to iterate over * @param {Number} stride Number of elements between the start of each vec2. If 0 assumes tightly packed * @param {Number} offset Number of elements to skip at the beginning of the array * @param {Number} count Number of vec2s to iterate over. If 0 iterates over entire array * @param {Function} fn Function to call for each vector in the array * @param {Object} [arg] additional argument to pass to fn * @returns {Array} a * @function */ var forEach = exports.forEach = function () { var vec = create(); return function (a, stride, offset, count, fn, arg) { var i = void 0, l = void 0; if (!stride) { stride = 2; } if (!offset) { offset = 0; } if (count) { l = Math.min(count * stride + offset, a.length); } else { l = a.length; } for (i = offset; i < l; i += stride) { vec[0] = a[i]; vec[1] = a[i + 1]; fn(vec, vec, arg); a[i] = vec[0]; a[i + 1] = vec[1]; } return a; }; }(); /***/ }), /* 220 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.forEach = exports.sqrLen = exports.len = exports.sqrDist = exports.dist = exports.div = exports.mul = exports.sub = undefined; exports.create = create; exports.clone = clone; exports.length = length; exports.fromValues = fromValues; exports.copy = copy; exports.set = set; exports.add = add; exports.subtract = subtract; exports.multiply = multiply; exports.divide = divide; exports.ceil = ceil; exports.floor = floor; exports.min = min; exports.max = max; exports.round = round; exports.scale = scale; exports.scaleAndAdd = scaleAndAdd; exports.distance = distance; exports.squaredDistance = squaredDistance; exports.squaredLength = squaredLength; exports.negate = negate; exports.inverse = inverse; exports.normalize = normalize; exports.dot = dot; exports.cross = cross; exports.lerp = lerp; exports.hermite = hermite; exports.bezier = bezier; exports.random = random; exports.transformMat4 = transformMat4; exports.transformMat3 = transformMat3; exports.transformQuat = transformQuat; exports.rotateX = rotateX; exports.rotateY = rotateY; exports.rotateZ = rotateZ; exports.angle = angle; exports.str = str; exports.exactEquals = exactEquals; exports.equals = equals; var _common = __webpack_require__(74); var glMatrix = _interopRequireWildcard(_common); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } } /** * 3 Dimensional Vector * @module vec3 */ /** * Creates a new, empty vec3 * * @returns {vec3} a new 3D vector */ function create() { var out = new glMatrix.ARRAY_TYPE(3); if (glMatrix.ARRAY_TYPE != Float32Array) { out[0] = 0; out[1] = 0; out[2] = 0; } return out; } /** * Creates a new vec3 initialized with values from an existing vector * * @param {vec3} a vector to clone * @returns {vec3} a new 3D vector */ function clone(a) { var out = new glMatrix.ARRAY_TYPE(3); out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; return out; } /** * Calculates the length of a vec3 * * @param {vec3} a vector to calculate length of * @returns {Number} length of a */ function length(a) { var x = a[0]; var y = a[1]; var z = a[2]; return Math.sqrt(x * x + y * y + z * z); } /** * Creates a new vec3 initialized with the given values * * @param {Number} x X component * @param {Number} y Y component * @param {Number} z Z component * @returns {vec3} a new 3D vector */ function fromValues(x, y, z) { var out = new glMatrix.ARRAY_TYPE(3); out[0] = x; out[1] = y; out[2] = z; return out; } /** * Copy the values from one vec3 to another * * @param {vec3} out the receiving vector * @param {vec3} a the source vector * @returns {vec3} out */ function copy(out, a) { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; return out; } /** * Set the components of a vec3 to the given values * * @param {vec3} out the receiving vector * @param {Number} x X component * @param {Number} y Y component * @param {Number} z Z component * @returns {vec3} out */ function set(out, x, y, z) { out[0] = x; out[1] = y; out[2] = z; return out; } /** * Adds two vec3's * * @param {vec3} out the receiving vector * @param {vec3} a the first operand * @param {vec3} b the second operand * @returns {vec3} out */ function add(out, a, b) { out[0] = a[0] + b[0]; out[1] = a[1] + b[1]; out[2] = a[2] + b[2]; return out; } /** * Subtracts vector b from vector a * * @param {vec3} out the receiving vector * @param {vec3} a the first operand * @param {vec3} b the second operand * @returns {vec3} out */ function subtract(out, a, b) { out[0] = a[0] - b[0]; out[1] = a[1] - b[1]; out[2] = a[2] - b[2]; return out; } /** * Multiplies two vec3's * * @param {vec3} out the receiving vector * @param {vec3} a the first operand * @param {vec3} b the second operand * @returns {vec3} out */ function multiply(out, a, b) { out[0] = a[0] * b[0]; out[1] = a[1] * b[1]; out[2] = a[2] * b[2]; return out; } /** * Divides two vec3's * * @param {vec3} out the receiving vector * @param {vec3} a the first operand * @param {vec3} b the second operand * @returns {vec3} out */ function divide(out, a, b) { out[0] = a[0] / b[0]; out[1] = a[1] / b[1]; out[2] = a[2] / b[2]; return out; } /** * Math.ceil the components of a vec3 * * @param {vec3} out the receiving vector * @param {vec3} a vector to ceil * @returns {vec3} out */ function ceil(out, a) { out[0] = Math.ceil(a[0]); out[1] = Math.ceil(a[1]); out[2] = Math.ceil(a[2]); return out; } /** * Math.floor the components of a vec3 * * @param {vec3} out the receiving vector * @param {vec3} a vector to floor * @returns {vec3} out */ function floor(out, a) { out[0] = Math.floor(a[0]); out[1] = Math.floor(a[1]); out[2] = Math.floor(a[2]); return out; } /** * Returns the minimum of two vec3's * * @param {vec3} out the receiving vector * @param {vec3} a the first operand * @param {vec3} b the second operand * @returns {vec3} out */ function min(out, a, b) { out[0] = Math.min(a[0], b[0]); out[1] = Math.min(a[1], b[1]); out[2] = Math.min(a[2], b[2]); return out; } /** * Returns the maximum of two vec3's * * @param {vec3} out the receiving vector * @param {vec3} a the first operand * @param {vec3} b the second operand * @returns {vec3} out */ function max(out, a, b) { out[0] = Math.max(a[0], b[0]); out[1] = Math.max(a[1], b[1]); out[2] = Math.max(a[2], b[2]); return out; } /** * Math.round the components of a vec3 * * @param {vec3} out the receiving vector * @param {vec3} a vector to round * @returns {vec3} out */ function round(out, a) { out[0] = Math.round(a[0]); out[1] = Math.round(a[1]); out[2] = Math.round(a[2]); return out; } /** * Scales a vec3 by a scalar number * * @param {vec3} out the receiving vector * @param {vec3} a the vector to scale * @param {Number} b amount to scale the vector by * @returns {vec3} out */ function scale(out, a, b) { out[0] = a[0] * b; out[1] = a[1] * b; out[2] = a[2] * b; return out; } /** * Adds two vec3's after scaling the second operand by a scalar value * * @param {vec3} out the receiving vector * @param {vec3} a the first operand * @param {vec3} b the second operand * @param {Number} scale the amount to scale b by before adding * @returns {vec3} out */ function scaleAndAdd(out, a, b, scale) { out[0] = a[0] + b[0] * scale; out[1] = a[1] + b[1] * scale; out[2] = a[2] + b[2] * scale; return out; } /** * Calculates the euclidian distance between two vec3's * * @param {vec3} a the first operand * @param {vec3} b the second operand * @returns {Number} distance between a and b */ function distance(a, b) { var x = b[0] - a[0]; var y = b[1] - a[1]; var z = b[2] - a[2]; return Math.sqrt(x * x + y * y + z * z); } /** * Calculates the squared euclidian distance between two vec3's * * @param {vec3} a the first operand * @param {vec3} b the second operand * @returns {Number} squared distance between a and b */ function squaredDistance(a, b) { var x = b[0] - a[0]; var y = b[1] - a[1]; var z = b[2] - a[2]; return x * x + y * y + z * z; } /** * Calculates the squared length of a vec3 * * @param {vec3} a vector to calculate squared length of * @returns {Number} squared length of a */ function squaredLength(a) { var x = a[0]; var y = a[1]; var z = a[2]; return x * x + y * y + z * z; } /** * Negates the components of a vec3 * * @param {vec3} out the receiving vector * @param {vec3} a vector to negate * @returns {vec3} out */ function negate(out, a) { out[0] = -a[0]; out[1] = -a[1]; out[2] = -a[2]; return out; } /** * Returns the inverse of the components of a vec3 * * @param {vec3} out the receiving vector * @param {vec3} a vector to invert * @returns {vec3} out */ function inverse(out, a) { out[0] = 1.0 / a[0]; out[1] = 1.0 / a[1]; out[2] = 1.0 / a[2]; return out; } /** * Normalize a vec3 * * @param {vec3} out the receiving vector * @param {vec3} a vector to normalize * @returns {vec3} out */ function normalize(out, a) { var x = a[0]; var y = a[1]; var z = a[2]; var len = x * x + y * y + z * z; if (len > 0) { //TODO: evaluate use of glm_invsqrt here? len = 1 / Math.sqrt(len); out[0] = a[0] * len; out[1] = a[1] * len; out[2] = a[2] * len; } return out; } /** * Calculates the dot product of two vec3's * * @param {vec3} a the first operand * @param {vec3} b the second operand * @returns {Number} dot product of a and b */ function dot(a, b) { return a[0] * b[0] + a[1] * b[1] + a[2] * b[2]; } /** * Computes the cross product of two vec3's * * @param {vec3} out the receiving vector * @param {vec3} a the first operand * @param {vec3} b the second operand * @returns {vec3} out */ function cross(out, a, b) { var ax = a[0], ay = a[1], az = a[2]; var bx = b[0], by = b[1], bz = b[2]; out[0] = ay * bz - az * by; out[1] = az * bx - ax * bz; out[2] = ax * by - ay * bx; return out; } /** * Performs a linear interpolation between two vec3's * * @param {vec3} out the receiving vector * @param {vec3} a the first operand * @param {vec3} b the second operand * @param {Number} t interpolation amount, in the range [0-1], between the two inputs * @returns {vec3} out */ function lerp(out, a, b, t) { var ax = a[0]; var ay = a[1]; var az = a[2]; out[0] = ax + t * (b[0] - ax); out[1] = ay + t * (b[1] - ay); out[2] = az + t * (b[2] - az); return out; } /** * Performs a hermite interpolation with two control points * * @param {vec3} out the receiving vector * @param {vec3} a the first operand * @param {vec3} b the second operand * @param {vec3} c the third operand * @param {vec3} d the fourth operand * @param {Number} t interpolation amount, in the range [0-1], between the two inputs * @returns {vec3} out */ function hermite(out, a, b, c, d, t) { var factorTimes2 = t * t; var factor1 = factorTimes2 * (2 * t - 3) + 1; var factor2 = factorTimes2 * (t - 2) + t; var factor3 = factorTimes2 * (t - 1); var factor4 = factorTimes2 * (3 - 2 * t); out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4; out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4; out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4; return out; } /** * Performs a bezier interpolation with two control points * * @param {vec3} out the receiving vector * @param {vec3} a the first operand * @param {vec3} b the second operand * @param {vec3} c the third operand * @param {vec3} d the fourth operand * @param {Number} t interpolation amount, in the range [0-1], between the two inputs * @returns {vec3} out */ function bezier(out, a, b, c, d, t) { var inverseFactor = 1 - t; var inverseFactorTimesTwo = inverseFactor * inverseFactor; var factorTimes2 = t * t; var factor1 = inverseFactorTimesTwo * inverseFactor; var factor2 = 3 * t * inverseFactorTimesTwo; var factor3 = 3 * factorTimes2 * inverseFactor; var factor4 = factorTimes2 * t; out[0] = a[0] * factor1 + b[0] * factor2 + c[0] * factor3 + d[0] * factor4; out[1] = a[1] * factor1 + b[1] * factor2 + c[1] * factor3 + d[1] * factor4; out[2] = a[2] * factor1 + b[2] * factor2 + c[2] * factor3 + d[2] * factor4; return out; } /** * Generates a random vector with the given scale * * @param {vec3} out the receiving vector * @param {Number} [scale] Length of the resulting vector. If ommitted, a unit vector will be returned * @returns {vec3} out */ function random(out, scale) { scale = scale || 1.0; var r = glMatrix.RANDOM() * 2.0 * Math.PI; var z = glMatrix.RANDOM() * 2.0 - 1.0; var zScale = Math.sqrt(1.0 - z * z) * scale; out[0] = Math.cos(r) * zScale; out[1] = Math.sin(r) * zScale; out[2] = z * scale; return out; } /** * Transforms the vec3 with a mat4. * 4th vector component is implicitly '1' * * @param {vec3} out the receiving vector * @param {vec3} a the vector to transform * @param {mat4} m matrix to transform with * @returns {vec3} out */ function transformMat4(out, a, m) { var x = a[0], y = a[1], z = a[2]; var w = m[3] * x + m[7] * y + m[11] * z + m[15]; w = w || 1.0; out[0] = (m[0] * x + m[4] * y + m[8] * z + m[12]) / w; out[1] = (m[1] * x + m[5] * y + m[9] * z + m[13]) / w; out[2] = (m[2] * x + m[6] * y + m[10] * z + m[14]) / w; return out; } /** * Transforms the vec3 with a mat3. * * @param {vec3} out the receiving vector * @param {vec3} a the vector to transform * @param {mat3} m the 3x3 matrix to transform with * @returns {vec3} out */ function transformMat3(out, a, m) { var x = a[0], y = a[1], z = a[2]; out[0] = x * m[0] + y * m[3] + z * m[6]; out[1] = x * m[1] + y * m[4] + z * m[7]; out[2] = x * m[2] + y * m[5] + z * m[8]; return out; } /** * Transforms the vec3 with a quat * Can also be used for dual quaternions. (Multiply it with the real part) * * @param {vec3} out the receiving vector * @param {vec3} a the vector to transform * @param {quat} q quaternion to transform with * @returns {vec3} out */ function transformQuat(out, a, q) { // benchmarks: https://jsperf.com/quaternion-transform-vec3-implementations-fixed var qx = q[0], qy = q[1], qz = q[2], qw = q[3]; var x = a[0], y = a[1], z = a[2]; // var qvec = [qx, qy, qz]; // var uv = vec3.cross([], qvec, a); var uvx = qy * z - qz * y, uvy = qz * x - qx * z, uvz = qx * y - qy * x; // var uuv = vec3.cross([], qvec, uv); var uuvx = qy * uvz - qz * uvy, uuvy = qz * uvx - qx * uvz, uuvz = qx * uvy - qy * uvx; // vec3.scale(uv, uv, 2 * w); var w2 = qw * 2; uvx *= w2; uvy *= w2; uvz *= w2; // vec3.scale(uuv, uuv, 2); uuvx *= 2; uuvy *= 2; uuvz *= 2; // return vec3.add(out, a, vec3.add(out, uv, uuv)); out[0] = x + uvx + uuvx; out[1] = y + uvy + uuvy; out[2] = z + uvz + uuvz; return out; } /** * Rotate a 3D vector around the x-axis * @param {vec3} out The receiving vec3 * @param {vec3} a The vec3 point to rotate * @param {vec3} b The origin of the rotation * @param {Number} c The angle of rotation * @returns {vec3} out */ function rotateX(out, a, b, c) { var p = [], r = []; //Translate point to the origin p[0] = a[0] - b[0]; p[1] = a[1] - b[1]; p[2] = a[2] - b[2]; //perform rotation r[0] = p[0]; r[1] = p[1] * Math.cos(c) - p[2] * Math.sin(c); r[2] = p[1] * Math.sin(c) + p[2] * Math.cos(c); //translate to correct position out[0] = r[0] + b[0]; out[1] = r[1] + b[1]; out[2] = r[2] + b[2]; return out; } /** * Rotate a 3D vector around the y-axis * @param {vec3} out The receiving vec3 * @param {vec3} a The vec3 point to rotate * @param {vec3} b The origin of the rotation * @param {Number} c The angle of rotation * @returns {vec3} out */ function rotateY(out, a, b, c) { var p = [], r = []; //Translate point to the origin p[0] = a[0] - b[0]; p[1] = a[1] - b[1]; p[2] = a[2] - b[2]; //perform rotation r[0] = p[2] * Math.sin(c) + p[0] * Math.cos(c); r[1] = p[1]; r[2] = p[2] * Math.cos(c) - p[0] * Math.sin(c); //translate to correct position out[0] = r[0] + b[0]; out[1] = r[1] + b[1]; out[2] = r[2] + b[2]; return out; } /** * Rotate a 3D vector around the z-axis * @param {vec3} out The receiving vec3 * @param {vec3} a The vec3 point to rotate * @param {vec3} b The origin of the rotation * @param {Number} c The angle of rotation * @returns {vec3} out */ function rotateZ(out, a, b, c) { var p = [], r = []; //Translate point to the origin p[0] = a[0] - b[0]; p[1] = a[1] - b[1]; p[2] = a[2] - b[2]; //perform rotation r[0] = p[0] * Math.cos(c) - p[1] * Math.sin(c); r[1] = p[0] * Math.sin(c) + p[1] * Math.cos(c); r[2] = p[2]; //translate to correct position out[0] = r[0] + b[0]; out[1] = r[1] + b[1]; out[2] = r[2] + b[2]; return out; } /** * Get the angle between two 3D vectors * @param {vec3} a The first operand * @param {vec3} b The second operand * @returns {Number} The angle in radians */ function angle(a, b) { var tempA = fromValues(a[0], a[1], a[2]); var tempB = fromValues(b[0], b[1], b[2]); normalize(tempA, tempA); normalize(tempB, tempB); var cosine = dot(tempA, tempB); if (cosine > 1.0) { return 0; } else if (cosine < -1.0) { return Math.PI; } else { return Math.acos(cosine); } } /** * Returns a string representation of a vector * * @param {vec3} a vector to represent as a string * @returns {String} string representation of the vector */ function str(a) { return 'vec3(' + a[0] + ', ' + a[1] + ', ' + a[2] + ')'; } /** * Returns whether or not the vectors have exactly the same elements in the same position (when compared with ===) * * @param {vec3} a The first vector. * @param {vec3} b The second vector. * @returns {Boolean} True if the vectors are equal, false otherwise. */ function exactEquals(a, b) { return a[0] === b[0] && a[1] === b[1] && a[2] === b[2]; } /** * Returns whether or not the vectors have approximately the same elements in the same position. * * @param {vec3} a The first vector. * @param {vec3} b The second vector. * @returns {Boolean} True if the vectors are equal, false otherwise. */ function equals(a, b) { var a0 = a[0], a1 = a[1], a2 = a[2]; var b0 = b[0], b1 = b[1], b2 = b[2]; return Math.abs(a0 - b0) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a0), Math.abs(b0)) && Math.abs(a1 - b1) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a1), Math.abs(b1)) && Math.abs(a2 - b2) <= glMatrix.EPSILON * Math.max(1.0, Math.abs(a2), Math.abs(b2)); } /** * Alias for {@link vec3.subtract} * @function */ var sub = exports.sub = subtract; /** * Alias for {@link vec3.multiply} * @function */ var mul = exports.mul = multiply; /** * Alias for {@link vec3.divide} * @function */ var div = exports.div = divide; /** * Alias for {@link vec3.distance} * @function */ var dist = exports.dist = distance; /** * Alias for {@link vec3.squaredDistance} * @function */ var sqrDist = exports.sqrDist = squaredDistance; /** * Alias for {@link vec3.length} * @function */ var len = exports.len = length; /** * Alias for {@link vec3.squaredLength} * @function */ var sqrLen = exports.sqrLen = squaredLength; /** * Perform some operation over an array of vec3s. * * @param {Array} a the array of vectors to iterate over * @param {Number} stride Number of elements between the start of each vec3. If 0 assumes tightly packed * @param {Number} offset Number of elements to skip at the beginning of the array * @param {Number} count Number of vec3s to iterate over. If 0 iterates over entire array * @param {Function} fn Function to call for each vector in the array * @param {Object} [arg] additional argument to pass to fn * @returns {Array} a * @function */ var forEach = exports.forEach = function () { var vec = create(); return function (a, stride, offset, count, fn, arg) { var i = void 0, l = void 0; if (!stride) { stride = 3; } if (!offset) { offset = 0; } if (count) { l = Math.min(count * stride + offset, a.length); } else { l = a.length; } for (i = offset; i < l; i += stride) { vec[0] = a[i]; vec[1] = a[i + 1]; vec[2] = a[i + 2]; fn(vec, vec, arg); a[i] = vec[0]; a[i + 1] = vec[1]; a[i + 2] = vec[2]; } return a; }; }(); /***/ }), /* 221 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Event = __webpack_require__(78); var EVENTS = ['mousedown', 'mouseup', 'dblclick', 'mouseenter', 'mouseout', 'mouseover', 'mousemove', 'mouseleave']; // 获取当前时间 var getNowTime = function getNowTime() { var now = new Date(); return now.getTime(); }; var CLICK_OFFSET = 40; var LEFT_BTN_CODE = 0; var preShape = null; var mousedownShape = null; var mousedownOffset = {}; var dragging = null; var clickTimestamp = 0; module.exports = { registerEvent: function registerEvent() { var self = this; var el = this.get('el'); Util.each(EVENTS, function (evt) { el.addEventListener(evt, function (e) { self._triggerEvent(evt, e); }, false); }); // special cases el.addEventListener('touchstart', function (e) { if (!Util.isEmpty(e.touches)) { self._triggerEvent('touchstart', e.touches[0]); } }, false); el.addEventListener('touchmove', function (e) { if (!Util.isEmpty(e.touches)) { self._triggerEvent('touchmove', e.touches[0]); } }, false); el.addEventListener('touchend', function (e) { if (!Util.isEmpty(e.changedTouches)) { self._triggerEvent('touchend', e.changedTouches[0]); } }, false); el.addEventListener('contextmenu', function (e) { self._triggerEvent('contextmenu', e); e.preventDefault(); }, false); }, _getEmitter: function _getEmitter(element, event) { if (element) { if (Util.isEmpty(element._getEvents())) { var parent = element.get('parent'); if (parent && !event.propagationStopped) { return this._getEmitter(parent, event); } } else { return element; } } }, _getEventObj: function _getEventObj(type, e, point, target) { var event = new Event(type, e, true, true); // 事件的x,y应该是基于画布左上角的,与canvas的matrix无关 event.x = point.x; event.y = point.y; event.clientX = e.clientX; event.clientY = e.clientY; event.currentTarget = target; event.target = target; return event; }, _triggerEvent: function _triggerEvent(type, e) { var self = this; var point = self.getPointByEvent(e); var shape = self.getShape(point.x, point.y, e); var el = self.get('el'); // svg原生事件取不到dragover, dragout, drop等事件的对象。这边需要走数学拾取。 if (dragging && self.getRenderer() === 'svg') { shape = self.getShape(point.x, point.y); } if (type === 'mousemove') { if (preShape && preShape !== shape) { self._emitEvent('mouseout', e, point, preShape); self._emitEvent('mouseleave', e, point, preShape); if (dragging) { self._emitEvent('dragleave', e, point, preShape); } // 当 mouseleave 触发时,如果拾取到其他 shape 的 mouseenter ,鼠标样式会正常 // 当鼠标移出 shape 但是移动到画布上时,没有shape,就不恢复样式。这里判断一下,直接重置 if (!shape || shape.destroyed) { el.style.cursor = 'default'; } } if (dragging) { self._emitEvent('drag', e, point, dragging); /** * H5原生事件中drag同时不会触发mousemove * 但是在上层具有嵌套关系的item事件计算中需要用到drag时的mousemove * 才能计算dragenter etc. */ self._emitEvent('mousemove', e, point, shape); } if (shape) { if (!dragging) { if (mousedownShape === shape) { var now = getNowTime(); var timeWindow = now - clickTimestamp; var dx = mousedownOffset.x - e.clientX; var dy = mousedownOffset.y - e.clientY; var dist = dx * dx + dy * dy; if (timeWindow > 120 || dist > CLICK_OFFSET) { dragging = shape; mousedownShape = null; this._emitEvent('dragstart', e, point, shape); } else { self._emitEvent('mousemove', e, point, shape); } } else { self._emitEvent('mousemove', e, point, shape); } } if (preShape !== shape) { self._emitEvent('mouseenter', e, point, shape); self._emitEvent('mouseover', e, point, shape); if (dragging) { self._emitEvent('dragenter', e, point, shape); } } } else { var canvasmousemove = self._getEventObj('mousemove', e, point, self); self.emit('mousemove', canvasmousemove); } preShape = shape; } else { this._emitEvent(type, e, point, shape || this); // e.button === 0 保证按下左键,防止点击右键触发click if (!dragging && type === 'mousedown' && e.button === LEFT_BTN_CODE) { mousedownShape = shape; mousedownOffset = { x: e.clientX, y: e.clientY }; clickTimestamp = getNowTime(); } if (type === 'mouseup' && e.button === LEFT_BTN_CODE) { var _dx = mousedownOffset.x - e.clientX; var _dy = mousedownOffset.y - e.clientY; var _dist = _dx * _dx + _dy * _dy; var _now = getNowTime(); var _timeWindow = _now - clickTimestamp; if (_dist < CLICK_OFFSET || _timeWindow < 200) { clickTimestamp = 0; this._emitEvent('click', e, point, mousedownShape || this); } if (dragging) { dragging._cfg.capture = true; this._emitEvent('dragend', e, point, dragging); dragging = null; this._emitEvent('drop', e, point, shape || this); } mousedownShape = null; } } if (shape && !shape.get('destroyed')) { el.style.cursor = shape.attr('cursor') || 'default'; } }, _emitEvent: function _emitEvent(type, evt, point, shape) { var event = this._getEventObj(type, evt, point, shape); var emitShape = this._getEmitter(shape, evt); emitShape && !emitShape.get('destroyed') && emitShape.emit(type, event); return emitShape; } }; /***/ }), /* 222 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); module.exports = { canFill: false, canStroke: false, initAttrs: function initAttrs(attrs) { this._attrs = { opacity: 1, fillOpacity: 1, strokeOpacity: 1, matrix: [1, 0, 0, 0, 1, 0, 0, 0, 1] }; this.attr(Util.assign(this.getDefaultAttrs(), attrs)); return this; }, getDefaultAttrs: function getDefaultAttrs() { return {}; }, /** * 设置或者设置属性,有以下 4 种情形: * - name 不存在, 则返回属性集合 * - name 为字符串,value 为空,获取属性值 * - name 为字符串,value 不为空,设置属性值,返回 this * - name 为键值对,value 为空,设置属性值 * * @param {String | Object} name 属性名 * @param {*} value 属性值 * @return {*} 属性值 */ attr: function attr(name, value) { var self = this; if (arguments.length === 0) { return self._attrs; } if (Util.isObject(name)) { // self._attrs = Util.deepMix(self._attrs, name); for (var k in name) { this._setAttr(k, name[k]); } self.clearBBox(); this._cfg.hasUpdate = true; return self; } if (arguments.length === 2) { this._setAttr(name, value); self.clearBBox(); this._cfg.hasUpdate = true; return self; } return self._attrs[name]; }, _setAttr: function _setAttr(name, value) { var self = this; var attrs = this._attrs; attrs[name] = value; if (name === 'fill' || name === 'stroke') { attrs[name + 'Style'] = value; return; } if (name === 'opacity') { attrs.globalAlpha = value; return; } if (name === 'clip' && value) { self._setClip(value); return; } if (name === 'path' && self._afterSetAttrPath) { self._afterSetAttrPath(value); return; } if (name === 'transform') { self.transform(value); return; } if (name === 'rotate') { self.rotateAtStart(value); } }, clearBBox: function clearBBox() { this.setSilent('box', null); }, hasFill: function hasFill() { return this.canFill && this._attrs.fillStyle; }, hasStroke: function hasStroke() { return this.canStroke && this._attrs.strokeStyle; }, _setClip: function _setClip(item) { item._cfg.renderer = this._cfg.renderer; item._cfg.canvas = this._cfg.canvas; item._cfg.parent = this._cfg.parent; item.hasFill = function () { return true; }; } }; /***/ }), /* 223 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); // 是否未改变 function isUnchanged(m) { return m[0] === 1 && m[1] === 0 && m[3] === 0 && m[4] === 1 && m[6] === 0 && m[7] === 0; } // 是否仅仅是scale function isScale(m) { return m[1] === 0 && m[3] === 0 && m[6] === 0 && m[7] === 0; } function multiple(m1, m2) { if (!isUnchanged(m2)) { if (isScale(m2)) { m1[0] *= m2[0]; m1[4] *= m2[4]; } else { Util.mat3.multiply(m1, m1, m2); } } } module.exports = { initTransform: function initTransform() {}, resetMatrix: function resetMatrix() { this.attr('matrix', [1, 0, 0, 0, 1, 0, 0, 0, 1]); }, translate: function translate(tx, ty) { var matrix = this._attrs.matrix; Util.mat3.translate(matrix, matrix, [tx, ty]); this.clearTotalMatrix(); this.attr('matrix', matrix); return this; }, rotate: function rotate(radian) { var matrix = this._attrs.matrix; Util.mat3.rotate(matrix, matrix, radian); this.clearTotalMatrix(); this.attr('matrix', matrix); return this; }, scale: function scale(s1, s2) { var matrix = this._attrs.matrix; Util.mat3.scale(matrix, matrix, [s1, s2]); this.clearTotalMatrix(); this.attr('matrix', matrix); return this; }, rotateAtStart: function rotateAtStart(rotate) { var x = this._attrs.x || this._cfg.attrs.x; var y = this._attrs.y || this._cfg.attrs.y; if (Math.abs(rotate) > Math.PI * 2) { rotate = rotate / 180 * Math.PI; } return this.transform([['t', -x, -y], ['r', rotate], ['t', x, y]]); }, move: function move(x, y) { var cx = this.get('x') || 0; // 当前的x var cy = this.get('y') || 0; // 当前的y this.translate(x - cx, y - cy); this.set('x', x); this.set('y', y); return this; }, transform: function transform(ts) { var self = this; var matrix = this._attrs.matrix; Util.each(ts, function (t) { switch (t[0]) { case 't': self.translate(t[1], t[2]); break; case 's': self.scale(t[1], t[2]); break; case 'r': self.rotate(t[1]); break; case 'm': self.attr('matrix', Util.mat3.multiply([], matrix, t[1])); self.clearTotalMatrix(); break; default: break; } }); return self; }, setTransform: function setTransform(ts) { this.attr('matrix', [1, 0, 0, 0, 1, 0, 0, 0, 1]); return this.transform(ts); }, getMatrix: function getMatrix() { return this.attr('matrix'); }, setMatrix: function setMatrix(m) { this.attr('matrix', m); this.clearTotalMatrix(); return this; }, apply: function apply(v, root) { var m; if (root) { m = this._getMatrixByRoot(root); } else { m = this.attr('matrix'); } Util.vec3.transformMat3(v, v, m); return this; }, // 获取到达指定根节点的矩阵 _getMatrixByRoot: function _getMatrixByRoot(root) { var self = this; root = root || self; var parent = self; var parents = []; while (parent !== root) { parents.unshift(parent); parent = parent.get('parent'); } parents.unshift(parent); var m = [1, 0, 0, 0, 1, 0, 0, 0, 1]; Util.each(parents, function (child) { Util.mat3.multiply(m, child.attr('matrix'), m); }); return m; }, /** * 应用到当前元素上的总的矩阵 * @return {Matrix} 矩阵 */ getTotalMatrix: function getTotalMatrix() { var m = this._cfg.totalMatrix; if (!m) { m = [1, 0, 0, 0, 1, 0, 0, 0, 1]; var parent = this._cfg.parent; if (parent) { var pm = parent.getTotalMatrix(); multiple(m, pm); } multiple(m, this.attr('matrix')); this._cfg.totalMatrix = m; } return m; }, // 清除当前的矩阵 clearTotalMatrix: function clearTotalMatrix() {// this._cfg.totalMatrix = null; }, invert: function invert(v) { var m = this.getTotalMatrix(); // 单精屏幕下大多数矩阵没变化 if (isScale(m)) { v[0] /= m[0]; v[1] /= m[4]; } else { var inm = Util.mat3.invert([], m); if (inm) { Util.vec3.transformMat3(v, v, inm); } } return this; }, resetTransform: function resetTransform(context) { var mo = this.attr('matrix'); // 不改变时 if (!isUnchanged(mo)) { context.transform(mo[0], mo[1], mo[3], mo[4], mo[6], mo[7]); } } }; /***/ }), /* 224 */ /***/ (function(module, exports, __webpack_require__) { function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } var Util = __webpack_require__(1); var ReservedProps = { delay: 'delay', repeat: 'repeat', rotate: 'rotate' }; function getFromAttrs(toAttrs, shape) { var rst = {}; var attrs = shape._attrs; for (var k in toAttrs.attrs) { rst[k] = attrs[k]; } return rst; } function getFormatProps(props, shape) { var rst = { matrix: null, attrs: {} }; var attrs = shape._attrs; for (var k in props) { if (k === 'transform') { rst.matrix = Util.transform(shape.getMatrix(), props[k]); } else if (k === 'matrix') { rst.matrix = props[k]; } else if (Util.isColorProp(k) && Util.isGradientColor(props[k])) { // 渐变色不支持动画, 直接跳色 rst.attrs[k] = props[k]; } else if (!ReservedProps[k] && attrs[k] !== props[k]) { if (k === 'rotate') { shape._attrs.rotate = shape._attrs.rotate || 0; } rst.attrs[k] = props[k]; } } return rst; } function checkExistedAttrs(animators, animator) { if (animator.onFrame) { return animators; } var delay = animator.delay; var hasOwnProperty = Object.prototype.hasOwnProperty; Util.each(animator.toAttrs, function (v, k) { Util.each(animators, function (animator) { if (delay < animator.startTime + animator.duration) { if (hasOwnProperty.call(animator.toAttrs, k)) { delete animator.toAttrs[k]; delete animator.fromAttrs[k]; } } }); }); if (animator.toMatrix) { Util.each(animators, function (animator) { if (delay < animator.startTime + animator.duration && animator.toMatrix) { delete animator.toMatrix; } }); } return animators; } module.exports = { /** * 执行动画 * @param {Object} toProps 动画最终状态 * @param {Number} duration 动画执行时间 * @param {String} easing 动画缓动效果 * @param {Function} callback 动画执行后的回调 * @param {Number} delay 动画延迟时间 */ animate: function animate(toProps, duration, easing, callback, delay) { if (delay === void 0) { delay = 0; } var self = this; self.set('animating', true); var timeline = self.get('timeline'); if (!timeline) { timeline = self.get('canvas').get('timeline'); self.setSilent('timeline', timeline); } var animators = self.get('animators') || []; // 初始化tick if (!timeline._timer) { timeline.initTimer(); } if (Util.isNumber(callback)) { delay = callback; callback = null; } if (Util.isFunction(easing)) { callback = easing; easing = 'easeLinear'; } else { easing = easing ? easing : 'easeLinear'; } var animator = { repeat: toProps.repeat, duration: duration, easing: easing, callback: callback, delay: delay, startTime: timeline.getTime(), id: Util.uniqueId() }; if (toProps.onFrame) { animator.onFrame = toProps.onFrame; } else { var formatProps = getFormatProps(toProps, self); animator = _extends({ fromAttrs: getFromAttrs(formatProps, self), toAttrs: formatProps.attrs, fromMatrix: Util.clone(self.getMatrix()), toMatrix: formatProps.matrix }, animator); } // 如果动画队列中已经有这个图形了 if (animators.length > 0) { // 先检查是否需要合并属性。若有相同的动画,将该属性从前一个动画中删除,直接用后一个动画中 animators = checkExistedAttrs(animators, animator); } else { // 否则将图形添加到队列 timeline.addAnimator(self); } animators.push(animator); self.setSilent('animators', animators); self.setSilent('pause', { isPaused: false }); }, stopAnimate: function stopAnimate() { var _this = this; var animators = this.get('animators'); // 将动画执行到最后一帧,执行回调 Util.each(animators, function (animator) { _this.attr(animator.toAttrs || animator.onFrame(1)); if (animator.toMatrix) { _this.attr('matrix', animator.toMatrix); } if (animator.callback) { animator.callback(); } }); this.setSilent('animating', false); this.setSilent('animators', []); }, pauseAnimate: function pauseAnimate() { var self = this; var timeline = self.get('timeline'); // 记录下是在什么时候暂停的 self.setSilent('pause', { isPaused: true, pauseTime: timeline.getTime() }); return self; }, resumeAnimate: function resumeAnimate() { var self = this; var timeline = self.get('timeline'); var current = timeline.getTime(); var animators = self.get('animators'); var pauseTime = self.get('pause').pauseTime; // 之后更新属性需要计算动画已经执行的时长,如果暂停了,就把初始时间调后 Util.each(animators, function (animator) { animator.startTime = animator.startTime + (current - pauseTime); animator._paused = false; animator._pauseTime = null; }); self.setSilent('pause', { isPaused: false }); self.setSilent('animators', animators); return self; } }; /***/ }), /* 225 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Event = __webpack_require__(78); var EventEmitter = __webpack_require__(117); var PROPOGATE_EVENTS = ['click', 'mousedown', 'mouseup', 'dblclick', 'contextmenu', 'mouseout', 'mouseover', 'mousemove', 'dragstart', 'drag', 'dragend', 'dragenter', 'dragleave', 'drop']; var AdvancedEE = function AdvancedEE() {}; Util.augment(AdvancedEE, EventEmitter, { emit: function emit(evt, e) { var args = arguments; EventEmitter.prototype.emit.apply(this, args); if (args.length >= 2 && args[1] instanceof Event && args[1].propagationStopped) { return; } if (PROPOGATE_EVENTS.indexOf(evt) >= 0 && e.target === this /* prevent bubbling multiple times */ ) { var shape = this._cfg.parent; while (shape && !shape.get('destroyed')) { shape.emit.apply(shape, args); shape = shape._cfg.parent; } } } }); module.exports = AdvancedEE; /***/ }), /* 226 */ /***/ (function(module, exports, __webpack_require__) { var Shape = __webpack_require__(7); Shape.Arc = __webpack_require__(120); Shape.Circle = __webpack_require__(121); Shape.Dom = __webpack_require__(122); Shape.Ellipse = __webpack_require__(123); Shape.Fan = __webpack_require__(124); Shape.Image = __webpack_require__(125); Shape.Line = __webpack_require__(126); Shape.Marker = __webpack_require__(81); Shape.Path = __webpack_require__(127); Shape.Polygon = __webpack_require__(128); Shape.Polyline = __webpack_require__(129); Shape.Rect = __webpack_require__(130); Shape.Text = __webpack_require__(131); module.exports = Shape; /***/ }), /* 227 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var Inside = __webpack_require__(79); var mathUtl = { arc: __webpack_require__(44), ellipse: __webpack_require__(119), line: __webpack_require__(43) }; var canvas = Util.createDom(''); var context = canvas.getContext('2d'); function isPointInPathByContext(x, y, ctx) { ctx.createPath(context); return context.isPointInPath(x, y); } var arc = function arc(x, y) { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var r = attrs.r, startAngle = attrs.startAngle, endAngle = attrs.endAngle, clockwise = attrs.clockwise; var lineWidth = this.getHitLineWidth(); if (this.hasStroke()) { return Inside.arcline(cx, cy, r, startAngle, endAngle, clockwise, lineWidth, x, y); } return false; }; var circle = function circle(x, y) { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var r = attrs.r; var lineWidth = this.getHitLineWidth(); var fill = this.hasFill(); var stroke = this.hasStroke(); if (fill && stroke) { return Inside.circle(cx, cy, r, x, y) || Inside.arcline(cx, cy, r, 0, Math.PI * 2, false, lineWidth, x, y); } if (fill) { return Inside.circle(cx, cy, r, x, y); } if (stroke) { return Inside.arcline(cx, cy, r, 0, Math.PI * 2, false, lineWidth, x, y); } return false; }; var ellipse = function ellipse(x, y) { var attrs = this._attrs; var fill = this.hasFill(); var stroke = this.hasStroke(); var cx = attrs.x; var cy = attrs.y; var rx = attrs.rx; var ry = attrs.ry; var lineWidth = this.getHitLineWidth(); var r = rx > ry ? rx : ry; var scaleX = rx > ry ? 1 : rx / ry; var scaleY = rx > ry ? ry / rx : 1; var p = [x, y, 1]; var m = [1, 0, 0, 0, 1, 0, 0, 0, 1]; Util.mat3.scale(m, m, [scaleX, scaleY]); Util.mat3.translate(m, m, [cx, cy]); var inm = Util.mat3.invert([], m); Util.vec3.transformMat3(p, p, inm); if (fill && stroke) { return Inside.circle(0, 0, r, p[0], p[1]) || Inside.arcline(0, 0, r, 0, Math.PI * 2, false, lineWidth, p[0], p[1]); } if (fill) { return Inside.circle(0, 0, r, p[0], p[1]); } if (stroke) { return Inside.arcline(0, 0, r, 0, Math.PI * 2, false, lineWidth, p[0], p[1]); } return false; }; var fan = function fan(x, y) { var self = this; var fill = self.hasFill(); var stroke = self.hasStroke(); var attrs = self._attrs; var cx = attrs.x; var cy = attrs.y; var rs = attrs.rs; var re = attrs.re; var startAngle = attrs.startAngle; var endAngle = attrs.endAngle; var clockwise = attrs.clockwise; var v1 = [1, 0]; var subv = [x - cx, y - cy]; var angle = Util.vec2.angleTo(v1, subv); function _isPointInFill() { var angle1 = mathUtl.arc.nearAngle(angle, startAngle, endAngle, clockwise); if (Util.isNumberEqual(angle, angle1)) { var ls = Util.vec2.squaredLength(subv); if (rs * rs <= ls && ls <= re * re) { return true; } } return false; } function _isPointInStroke() { var lineWidth = self.getHitLineWidth(); var ssp = { x: Math.cos(startAngle) * rs + cx, y: Math.sin(startAngle) * rs + cy }; var sep = { x: Math.cos(startAngle) * re + cx, y: Math.sin(startAngle) * re + cy }; var esp = { x: Math.cos(endAngle) * rs + cx, y: Math.sin(endAngle) * rs + cy }; var eep = { x: Math.cos(endAngle) * re + cx, y: Math.sin(endAngle) * re + cy }; if (Inside.line(ssp.x, ssp.y, sep.x, sep.y, lineWidth, x, y)) { return true; } if (Inside.line(esp.x, esp.y, eep.x, eep.y, lineWidth, x, y)) { return true; } if (Inside.arcline(cx, cy, rs, startAngle, endAngle, clockwise, lineWidth, x, y)) { return true; } if (Inside.arcline(cx, cy, re, startAngle, endAngle, clockwise, lineWidth, x, y)) { return true; } return false; } if (fill && stroke) { return _isPointInFill() || _isPointInStroke(); } if (fill) { return _isPointInFill(); } if (stroke) { return _isPointInStroke(); } return false; }; var image = function image(x, y) { var attrs = this._attrs; if (this.get('toDraw') || !attrs.img) { return false; } if (!this._cfg.attrs || this._cfg.attrs.img !== attrs.img) { this._setAttrImg(); } var rx = attrs.x; var ry = attrs.y; var width = attrs.width; var height = attrs.height; return Inside.rect(rx, ry, width, height, x, y); }; var line = function line(x, y) { var attrs = this._attrs; var x1 = attrs.x1, y1 = attrs.y1, x2 = attrs.x2, y2 = attrs.y2; var lineWidth = this.getHitLineWidth(); if (this.hasStroke()) { return Inside.line(x1, y1, x2, y2, lineWidth, x, y); } return false; }; var path = function path(x, y) { var self = this; var segments = self.get('segments'); var fill = self.hasFill(); var stroke = self.hasStroke(); function _isPointInStroke() { if (!Util.isEmpty(segments)) { var lineWidth = self.getHitLineWidth(); for (var i = 0, l = segments.length; i < l; i++) { if (segments[i].isInside(x, y, lineWidth)) { return true; } } return false; } } if (fill && stroke) { return isPointInPathByContext(x, y, self) || _isPointInStroke(); } if (fill) { return isPointInPathByContext(x, y, self); } if (stroke) { return _isPointInStroke(); } return false; }; var polygon = function polygon(x, y) { var self = this; var fill = self.hasFill(); var stroke = self.hasStroke(); function _isPointInStroke() { var attrs = self._attrs; var points = attrs.points; if (points.length < 2) { return false; } var lineWidth = self.getHitLineWidth(); var outPoints = points.slice(0); if (points.length >= 3) { outPoints.push(points[0]); } return Inside.polyline(outPoints, lineWidth, x, y); } if (fill && stroke) { return isPointInPathByContext(x, y, self) || _isPointInStroke(); } if (fill) { return isPointInPathByContext(x, y, self); } if (stroke) { return _isPointInStroke(); } return false; }; var marker = function marker(x, y) { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var r = attrs.radius || attrs.r; var lineWidth = this.getHitLineWidth(); return Inside.circle(cx, cy, r + lineWidth / 2, x, y); }; var polyline = function polyline(x, y) { var self = this; var attrs = self._attrs; if (self.hasStroke()) { var points = attrs.points; if (points.length < 2) { return false; } var lineWidth = attrs.lineWidth; return Inside.polyline(points, lineWidth, x, y); } return false; }; var rect = function rect(x, y) { var self = this; var fill = self.hasFill(); var stroke = self.hasStroke(); function _isPointInStroke() { var attrs = self._attrs; var rx = attrs.x; var ry = attrs.y; var width = attrs.width; var height = attrs.height; var radius = attrs.radius; var lineWidth = self.getHitLineWidth(); if (radius === 0) { var halfWidth = lineWidth / 2; return Inside.line(rx - halfWidth, ry, rx + width + halfWidth, ry, lineWidth, x, y) || Inside.line(rx + width, ry - halfWidth, rx + width, ry + height + halfWidth, lineWidth, x, y) || Inside.line(rx + width + halfWidth, ry + height, rx - halfWidth, ry + height, lineWidth, x, y) || Inside.line(rx, ry + height + halfWidth, rx, ry - halfWidth, lineWidth, x, y); } return Inside.line(rx + radius, ry, rx + width - radius, ry, lineWidth, x, y) || Inside.line(rx + width, ry + radius, rx + width, ry + height - radius, lineWidth, x, y) || Inside.line(rx + width - radius, ry + height, rx + radius, ry + height, lineWidth, x, y) || Inside.line(rx, ry + height - radius, rx, ry + radius, lineWidth, x, y) || Inside.arcline(rx + width - radius, ry + radius, radius, 1.5 * Math.PI, 2 * Math.PI, false, lineWidth, x, y) || Inside.arcline(rx + width - radius, ry + height - radius, radius, 0, 0.5 * Math.PI, false, lineWidth, x, y) || Inside.arcline(rx + radius, ry + height - radius, radius, 0.5 * Math.PI, Math.PI, false, lineWidth, x, y) || Inside.arcline(rx + radius, ry + radius, radius, Math.PI, 1.5 * Math.PI, false, lineWidth, x, y); } if (fill && stroke) { return isPointInPathByContext(x, y, self) || _isPointInStroke(); } if (fill) { return isPointInPathByContext(x, y, self); } if (stroke) { return _isPointInStroke(); } return false; }; var text = function text(x, y) { var self = this; var box = self.getBBox(); if (self.hasFill() || self.hasStroke()) { return Inside.box(box.minX, box.maxX, box.minY, box.maxY, x, y); } }; var dom = function dom(x, y) { if (!this._cfg.el) { return false; } var box = this._cfg.el.getBBox(); return Inside.box(box.x, box.x + box.width, box.y, box.y + box.height, x, y); }; var shapes = { arc: arc, circle: circle, dom: dom, ellipse: ellipse, fan: fan, image: image, line: line, path: path, marker: marker, polygon: polygon, polyline: polyline, rect: rect, text: text }; module.exports = { isPointInPath: function isPointInPath(x, y) { var shape = shapes[this.type]; if (shape) { return shape.call(this, x, y); } return false; } }; /***/ }), /* 228 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var PathUtil = __webpack_require__(82); var d3Timer = __webpack_require__(101); var d3Ease = __webpack_require__(103); var _require = __webpack_require__(133), interpolate = _require.interpolate, interpolateArray = _require.interpolateArray; // 目前整体动画只需要数值和数组的差值计算 var Timeline = function Timeline(canvas) { // 待执行动画的队列 this._animators = []; // 当前时间 this._current = 0; // 计时器实例 this._timer = null; // 画布 this.canvas = canvas; }; function _update(self, animator, ratio) { var cProps = {}; // 此刻属性 var toAttrs = animator.toAttrs; var fromAttrs = animator.fromAttrs; var toMatrix = animator.toMatrix; if (self.get('destroyed')) { return; } var interf; // 差值函数 for (var k in toAttrs) { if (!Util.isEqual(fromAttrs[k], toAttrs[k])) { if (k === 'path') { var toPath = toAttrs[k]; var fromPath = fromAttrs[k]; if (toPath.length > fromPath.length) { toPath = PathUtil.parsePathString(toAttrs[k]); // 终点状态 fromPath = PathUtil.parsePathString(fromAttrs[k]); // 起始状态 fromPath = PathUtil.fillPathByDiff(fromPath, toPath); fromPath = PathUtil.formatPath(fromPath, toPath); animator.fromAttrs.path = fromPath; animator.toAttrs.path = toPath; } else if (!animator.pathFormatted) { toPath = PathUtil.parsePathString(toAttrs[k]); fromPath = PathUtil.parsePathString(fromAttrs[k]); fromPath = PathUtil.formatPath(fromPath, toPath); animator.fromAttrs.path = fromPath; animator.toAttrs.path = toPath; animator.pathFormatted = true; } cProps[k] = []; for (var i = 0; i < toPath.length; i++) { var toPathPoint = toPath[i]; var fromPathPoint = fromPath[i]; var cPathPoint = []; for (var j = 0; j < toPathPoint.length; j++) { if (Util.isNumber(toPathPoint[j]) && fromPathPoint && Util.isNumber(fromPathPoint[j])) { interf = interpolate(fromPathPoint[j], toPathPoint[j]); cPathPoint.push(interf(ratio)); } else { cPathPoint.push(toPathPoint[j]); } } cProps[k].push(cPathPoint); } } else if (Util.isColorProp(k) && Util.isGradientColor(toAttrs[k])) { // 渐变色直接赋值,不做插值 cProps[k] = toAttrs[k]; } else { interf = interpolate(fromAttrs[k], toAttrs[k]); cProps[k] = interf(ratio); } } } if (toMatrix) { var mf = interpolateArray(animator.fromMatrix, toMatrix); var cM = mf(ratio); self.setMatrix(cM); } self.attr(cProps); } function update(shape, animator, elapsed) { var startTime = animator.startTime; // 如果还没有开始执行或暂停,先不更新 if (elapsed < startTime + animator.delay || animator.isPaused) { return false; } var ratio; var duration = animator.duration; var easing = animator.easing; // 已执行时间 elapsed = elapsed - startTime - animator.delay; if (animator.repeat) { ratio = elapsed % duration / duration; ratio = d3Ease[easing](ratio); } else { ratio = elapsed / duration; if (ratio < 1) { ratio = d3Ease[easing](ratio); } else { var attrs = animator.toAttrs || animator.onFrame(1); shape.attr(attrs); if (animator.toMatrix) { shape.setMatrix(animator.toMatrix); } return true; } } if (animator.onFrame) { var _attrs = animator.onFrame(ratio); shape.attr(_attrs); } else { _update(shape, animator, ratio); } return false; } Util.augment(Timeline, { initTimer: function initTimer() { var _this = this; var self = this; var isFinished = false; var shape, animators, animator; self._timer = d3Timer.timer(function (elapsed) { self._current = elapsed; if (_this._animators.length > 0) { for (var i = _this._animators.length - 1; i >= 0; i--) { shape = _this._animators[i]; if (shape.get('destroyed')) { // 如果已经被销毁,直接移出队列 self.removeAnimator(i); continue; } if (!shape.get('pause').isPaused) { animators = shape.get('animators'); for (var j = animators.length - 1; j >= 0; j--) { animator = animators[j]; isFinished = update(shape, animator, elapsed); if (isFinished) { animators.splice(j, 1); isFinished = false; if (animator.callback) { animator.callback(); } } } } if (animators.length === 0) { self.removeAnimator(i); } } _this.canvas.draw(); } }); }, addAnimator: function addAnimator(shape) { this._animators.push(shape); }, removeAnimator: function removeAnimator(index) { this._animators.splice(index, 1); }, isAnimating: function isAnimating() { return !!this._animators.length; }, stop: function stop() { if (this._timer) { this._timer.stop(); } }, stopAllAnimations: function stopAllAnimations() { this._animators.forEach(function (animator) { animator.stopAnimate(); }); this._animators = []; this.canvas.draw(); }, getTime: function getTime() { return this._current; } }); module.exports = Timeline; /***/ }), /* 229 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__timer_js__ = __webpack_require__(83); /* harmony default export */ __webpack_exports__["a"] = (function (callback, delay, time) { var t = new __WEBPACK_IMPORTED_MODULE_0__timer_js__["a" /* Timer */](); delay = delay == null ? 0 : +delay; t.restart(function (elapsed) { t.stop(); callback(elapsed + delay); }, delay, time); return t; }); /***/ }), /* 230 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__timer_js__ = __webpack_require__(83); /* harmony default export */ __webpack_exports__["a"] = (function (callback, delay, time) { var t = new __WEBPACK_IMPORTED_MODULE_0__timer_js__["a" /* Timer */](), total = delay; if (delay == null) return t.restart(callback, delay, time), t; delay = +delay, time = time == null ? Object(__WEBPACK_IMPORTED_MODULE_0__timer_js__["b" /* now */])() : +time; t.restart(function tick(elapsed) { elapsed += total; t.restart(tick, total += delay, time); callback(elapsed); }, delay, time); return t; }); /***/ }), /* 231 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = linear; function linear(t) { return +t; } /***/ }), /* 232 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = quadIn; /* harmony export (immutable) */ __webpack_exports__["c"] = quadOut; /* harmony export (immutable) */ __webpack_exports__["b"] = quadInOut; function quadIn(t) { return t * t; } function quadOut(t) { return t * (2 - t); } function quadInOut(t) { return ((t *= 2) <= 1 ? t * t : --t * (2 - t) + 1) / 2; } /***/ }), /* 233 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = cubicIn; /* harmony export (immutable) */ __webpack_exports__["c"] = cubicOut; /* harmony export (immutable) */ __webpack_exports__["b"] = cubicInOut; function cubicIn(t) { return t * t * t; } function cubicOut(t) { return --t * t * t + 1; } function cubicInOut(t) { return ((t *= 2) <= 1 ? t * t * t : (t -= 2) * t * t + 2) / 2; } /***/ }), /* 234 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return polyIn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return polyOut; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return polyInOut; }); var exponent = 3; var polyIn = function custom(e) { e = +e; function polyIn(t) { return Math.pow(t, e); } polyIn.exponent = custom; return polyIn; }(exponent); var polyOut = function custom(e) { e = +e; function polyOut(t) { return 1 - Math.pow(1 - t, e); } polyOut.exponent = custom; return polyOut; }(exponent); var polyInOut = function custom(e) { e = +e; function polyInOut(t) { return ((t *= 2) <= 1 ? Math.pow(t, e) : 2 - Math.pow(2 - t, e)) / 2; } polyInOut.exponent = custom; return polyInOut; }(exponent); /***/ }), /* 235 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = sinIn; /* harmony export (immutable) */ __webpack_exports__["c"] = sinOut; /* harmony export (immutable) */ __webpack_exports__["b"] = sinInOut; var pi = Math.PI, halfPi = pi / 2; function sinIn(t) { return +t === 1 ? 1 : 1 - Math.cos(t * halfPi); } function sinOut(t) { return Math.sin(t * halfPi); } function sinInOut(t) { return (1 - Math.cos(pi * t)) / 2; } /***/ }), /* 236 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = expIn; /* harmony export (immutable) */ __webpack_exports__["c"] = expOut; /* harmony export (immutable) */ __webpack_exports__["b"] = expInOut; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__math_js__ = __webpack_require__(132); function expIn(t) { return Object(__WEBPACK_IMPORTED_MODULE_0__math_js__["a" /* tpmt */])(1 - +t); } function expOut(t) { return 1 - Object(__WEBPACK_IMPORTED_MODULE_0__math_js__["a" /* tpmt */])(t); } function expInOut(t) { return ((t *= 2) <= 1 ? Object(__WEBPACK_IMPORTED_MODULE_0__math_js__["a" /* tpmt */])(1 - t) : 2 - Object(__WEBPACK_IMPORTED_MODULE_0__math_js__["a" /* tpmt */])(t - 1)) / 2; } /***/ }), /* 237 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = circleIn; /* harmony export (immutable) */ __webpack_exports__["c"] = circleOut; /* harmony export (immutable) */ __webpack_exports__["b"] = circleInOut; function circleIn(t) { return 1 - Math.sqrt(1 - t * t); } function circleOut(t) { return Math.sqrt(1 - --t * t); } function circleInOut(t) { return ((t *= 2) <= 1 ? 1 - Math.sqrt(1 - t * t) : Math.sqrt(1 - (t -= 2) * t) + 1) / 2; } /***/ }), /* 238 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = bounceIn; /* harmony export (immutable) */ __webpack_exports__["c"] = bounceOut; /* harmony export (immutable) */ __webpack_exports__["b"] = bounceInOut; var b1 = 4 / 11, b2 = 6 / 11, b3 = 8 / 11, b4 = 3 / 4, b5 = 9 / 11, b6 = 10 / 11, b7 = 15 / 16, b8 = 21 / 22, b9 = 63 / 64, b0 = 1 / b1 / b1; function bounceIn(t) { return 1 - bounceOut(1 - t); } function bounceOut(t) { return (t = +t) < b1 ? b0 * t * t : t < b3 ? b0 * (t -= b2) * t + b4 : t < b6 ? b0 * (t -= b5) * t + b7 : b0 * (t -= b8) * t + b9; } function bounceInOut(t) { return ((t *= 2) <= 1 ? 1 - bounceOut(1 - t) : bounceOut(t - 1) + 1) / 2; } /***/ }), /* 239 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return backIn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return backOut; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return backInOut; }); var overshoot = 1.70158; var backIn = function custom(s) { s = +s; function backIn(t) { return (t = +t) * t * (s * (t - 1) + t); } backIn.overshoot = custom; return backIn; }(overshoot); var backOut = function custom(s) { s = +s; function backOut(t) { return --t * t * ((t + 1) * s + t) + 1; } backOut.overshoot = custom; return backOut; }(overshoot); var backInOut = function custom(s) { s = +s; function backInOut(t) { return ((t *= 2) < 1 ? t * t * ((s + 1) * t - s) : (t -= 2) * t * ((s + 1) * t + s) + 2) / 2; } backInOut.overshoot = custom; return backInOut; }(overshoot); /***/ }), /* 240 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return elasticIn; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "c", function() { return elasticOut; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return elasticInOut; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__math_js__ = __webpack_require__(132); var tau = 2 * Math.PI, amplitude = 1, period = 0.3; var elasticIn = function custom(a, p) { var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau); function elasticIn(t) { return a * Object(__WEBPACK_IMPORTED_MODULE_0__math_js__["a" /* tpmt */])(- --t) * Math.sin((s - t) / p); } elasticIn.amplitude = function (a) { return custom(a, p * tau); }; elasticIn.period = function (p) { return custom(a, p); }; return elasticIn; }(amplitude, period); var elasticOut = function custom(a, p) { var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau); function elasticOut(t) { return 1 - a * Object(__WEBPACK_IMPORTED_MODULE_0__math_js__["a" /* tpmt */])(t = +t) * Math.sin((t + s) / p); } elasticOut.amplitude = function (a) { return custom(a, p * tau); }; elasticOut.period = function (p) { return custom(a, p); }; return elasticOut; }(amplitude, period); var elasticInOut = function custom(a, p) { var s = Math.asin(1 / (a = Math.max(1, a))) * (p /= tau); function elasticInOut(t) { return ((t = t * 2 - 1) < 0 ? a * Object(__WEBPACK_IMPORTED_MODULE_0__math_js__["a" /* tpmt */])(-t) * Math.sin((s - t) / p) : 2 - a * Object(__WEBPACK_IMPORTED_MODULE_0__math_js__["a" /* tpmt */])(t) * Math.sin((s + t) / p)) / 2; } elasticInOut.amplitude = function (a) { return custom(a, p * tau); }; elasticInOut.period = function (p) { return custom(a, p); }; return elasticInOut; }(amplitude, period); /***/ }), /* 241 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* unused harmony export gray */ /* harmony export (immutable) */ __webpack_exports__["a"] = lab; /* unused harmony export Lab */ /* unused harmony export lch */ /* harmony export (immutable) */ __webpack_exports__["b"] = hcl; /* unused harmony export Hcl */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__define_js__ = __webpack_require__(86); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__color_js__ = __webpack_require__(85); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__math_js__ = __webpack_require__(134); // https://observablehq.com/@mbostock/lab-and-rgb var K = 18, Xn = 0.96422, Yn = 1, Zn = 0.82521, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * t1 * t1, t3 = t1 * t1 * t1; function labConvert(o) { if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity); if (o instanceof Hcl) return hcl2lab(o); if (!(o instanceof __WEBPACK_IMPORTED_MODULE_1__color_js__["b" /* Rgb */])) o = Object(__WEBPACK_IMPORTED_MODULE_1__color_js__["h" /* rgbConvert */])(o); var r = rgb2lrgb(o.r), g = rgb2lrgb(o.g), b = rgb2lrgb(o.b), y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z; if (r === g && g === b) x = z = y;else { x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn); z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn); } return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity); } function gray(l, opacity) { return new Lab(l, 0, 0, opacity == null ? 1 : opacity); } function lab(l, a, b, opacity) { return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity); } function Lab(l, a, b, opacity) { this.l = +l; this.a = +a; this.b = +b; this.opacity = +opacity; } Object(__WEBPACK_IMPORTED_MODULE_0__define_js__["a" /* default */])(Lab, lab, Object(__WEBPACK_IMPORTED_MODULE_0__define_js__["b" /* extend */])(__WEBPACK_IMPORTED_MODULE_1__color_js__["a" /* Color */], { brighter: function (k) { return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity); }, darker: function (k) { return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity); }, rgb: function () { var y = (this.l + 16) / 116, x = isNaN(this.a) ? y : y + this.a / 500, z = isNaN(this.b) ? y : y - this.b / 200; x = Xn * lab2xyz(x); y = Yn * lab2xyz(y); z = Zn * lab2xyz(z); return new __WEBPACK_IMPORTED_MODULE_1__color_js__["b" /* Rgb */](lrgb2rgb(3.1338561 * x - 1.6168667 * y - 0.4906146 * z), lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.0334540 * z), lrgb2rgb(0.0719453 * x - 0.2289914 * y + 1.4052427 * z), this.opacity); } })); function xyz2lab(t) { return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0; } function lab2xyz(t) { return t > t1 ? t * t * t : t2 * (t - t0); } function lrgb2rgb(x) { return 255 * (x <= 0.0031308 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055); } function rgb2lrgb(x) { return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); } function hclConvert(o) { if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity); if (!(o instanceof Lab)) o = labConvert(o); if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity); var h = Math.atan2(o.b, o.a) * __WEBPACK_IMPORTED_MODULE_2__math_js__["b" /* rad2deg */]; return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity); } function lch(l, c, h, opacity) { return arguments.length === 1 ? hclConvert(l) : new Hcl(h, c, l, opacity == null ? 1 : opacity); } function hcl(h, c, l, opacity) { return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity); } function Hcl(h, c, l, opacity) { this.h = +h; this.c = +c; this.l = +l; this.opacity = +opacity; } function hcl2lab(o) { if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity); var h = o.h * __WEBPACK_IMPORTED_MODULE_2__math_js__["a" /* deg2rad */]; return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity); } Object(__WEBPACK_IMPORTED_MODULE_0__define_js__["a" /* default */])(Hcl, hcl, Object(__WEBPACK_IMPORTED_MODULE_0__define_js__["b" /* extend */])(__WEBPACK_IMPORTED_MODULE_1__color_js__["a" /* Color */], { brighter: function (k) { return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity); }, darker: function (k) { return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity); }, rgb: function () { return hcl2lab(this).rgb(); } })); /***/ }), /* 242 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = cubehelix; /* unused harmony export Cubehelix */ /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__define_js__ = __webpack_require__(86); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__color_js__ = __webpack_require__(85); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_2__math_js__ = __webpack_require__(134); var A = -0.14861, B = +1.78277, C = -0.29227, D = -0.90649, E = +1.97294, ED = E * D, EB = E * B, BC_DA = B * C - D * A; function cubehelixConvert(o) { if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity); if (!(o instanceof __WEBPACK_IMPORTED_MODULE_1__color_js__["b" /* Rgb */])) o = Object(__WEBPACK_IMPORTED_MODULE_1__color_js__["h" /* rgbConvert */])(o); var r = o.r / 255, g = o.g / 255, b = o.b / 255, l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB), bl = b - l, k = (E * (g - l) - C * bl) / D, s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), // NaN if l=0 or l=1 h = s ? Math.atan2(k, bl) * __WEBPACK_IMPORTED_MODULE_2__math_js__["b" /* rad2deg */] - 120 : NaN; return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity); } function cubehelix(h, s, l, opacity) { return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity); } function Cubehelix(h, s, l, opacity) { this.h = +h; this.s = +s; this.l = +l; this.opacity = +opacity; } Object(__WEBPACK_IMPORTED_MODULE_0__define_js__["a" /* default */])(Cubehelix, cubehelix, Object(__WEBPACK_IMPORTED_MODULE_0__define_js__["b" /* extend */])(__WEBPACK_IMPORTED_MODULE_1__color_js__["a" /* Color */], { brighter: function (k) { k = k == null ? __WEBPACK_IMPORTED_MODULE_1__color_js__["c" /* brighter */] : Math.pow(__WEBPACK_IMPORTED_MODULE_1__color_js__["c" /* brighter */], k); return new Cubehelix(this.h, this.s, this.l * k, this.opacity); }, darker: function (k) { k = k == null ? __WEBPACK_IMPORTED_MODULE_1__color_js__["d" /* darker */] : Math.pow(__WEBPACK_IMPORTED_MODULE_1__color_js__["d" /* darker */], k); return new Cubehelix(this.h, this.s, this.l * k, this.opacity); }, rgb: function () { var h = isNaN(this.h) ? 0 : (this.h + 120) * __WEBPACK_IMPORTED_MODULE_2__math_js__["a" /* deg2rad */], l = +this.l, a = isNaN(this.s) ? 0 : this.s * l * (1 - l), cosh = Math.cos(h), sinh = Math.sin(h); return new __WEBPACK_IMPORTED_MODULE_1__color_js__["b" /* Rgb */](255 * (l + a * (A * cosh + B * sinh)), 255 * (l + a * (C * cosh + D * sinh)), 255 * (l + a * (E * cosh)), this.opacity); } })); /***/ }), /* 243 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony default export */ __webpack_exports__["a"] = (function (a, b) { return a = +a, b -= a, function (t) { return Math.round(a + b * t); }; }); /***/ }), /* 244 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return interpolateTransformCss; }); /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return interpolateTransformSvg; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__number__ = __webpack_require__(47); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__parse__ = __webpack_require__(245); function interpolateTransform(parse, pxComma, pxParen, degParen) { function pop(s) { return s.length ? s.pop() + " " : ""; } function translate(xa, ya, xb, yb, s, q) { if (xa !== xb || ya !== yb) { var i = s.push("translate(", null, pxComma, null, pxParen); q.push({ i: i - 4, x: Object(__WEBPACK_IMPORTED_MODULE_0__number__["a" /* default */])(xa, xb) }, { i: i - 2, x: Object(__WEBPACK_IMPORTED_MODULE_0__number__["a" /* default */])(ya, yb) }); } else if (xb || yb) { s.push("translate(" + xb + pxComma + yb + pxParen); } } function rotate(a, b, s, q) { if (a !== b) { if (a - b > 180) b += 360;else if (b - a > 180) a += 360; // shortest path q.push({ i: s.push(pop(s) + "rotate(", null, degParen) - 2, x: Object(__WEBPACK_IMPORTED_MODULE_0__number__["a" /* default */])(a, b) }); } else if (b) { s.push(pop(s) + "rotate(" + b + degParen); } } function skewX(a, b, s, q) { if (a !== b) { q.push({ i: s.push(pop(s) + "skewX(", null, degParen) - 2, x: Object(__WEBPACK_IMPORTED_MODULE_0__number__["a" /* default */])(a, b) }); } else if (b) { s.push(pop(s) + "skewX(" + b + degParen); } } function scale(xa, ya, xb, yb, s, q) { if (xa !== xb || ya !== yb) { var i = s.push(pop(s) + "scale(", null, ",", null, ")"); q.push({ i: i - 4, x: Object(__WEBPACK_IMPORTED_MODULE_0__number__["a" /* default */])(xa, xb) }, { i: i - 2, x: Object(__WEBPACK_IMPORTED_MODULE_0__number__["a" /* default */])(ya, yb) }); } else if (xb !== 1 || yb !== 1) { s.push(pop(s) + "scale(" + xb + "," + yb + ")"); } } return function (a, b) { var s = [], // string constants and placeholders q = []; // number interpolators a = parse(a), b = parse(b); translate(a.translateX, a.translateY, b.translateX, b.translateY, s, q); rotate(a.rotate, b.rotate, s, q); skewX(a.skewX, b.skewX, s, q); scale(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q); a = b = null; // gc return function (t) { var i = -1, n = q.length, o; while (++i < n) s[(o = q[i]).i] = o.x(t); return s.join(""); }; }; } var interpolateTransformCss = interpolateTransform(__WEBPACK_IMPORTED_MODULE_1__parse__["a" /* parseCss */], "px, ", "px)", "deg)"); var interpolateTransformSvg = interpolateTransform(__WEBPACK_IMPORTED_MODULE_1__parse__["b" /* parseSvg */], ", ", ")", ")"); /***/ }), /* 245 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = parseCss; /* harmony export (immutable) */ __webpack_exports__["b"] = parseSvg; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0__decompose__ = __webpack_require__(246); var cssNode, cssRoot, cssView, svgNode; function parseCss(value) { if (value === "none") return __WEBPACK_IMPORTED_MODULE_0__decompose__["b" /* identity */]; if (!cssNode) cssNode = document.createElement("DIV"), cssRoot = document.documentElement, cssView = document.defaultView; cssNode.style.transform = value; value = cssView.getComputedStyle(cssRoot.appendChild(cssNode), null).getPropertyValue("transform"); cssRoot.removeChild(cssNode); value = value.slice(7, -1).split(","); return Object(__WEBPACK_IMPORTED_MODULE_0__decompose__["a" /* default */])(+value[0], +value[1], +value[2], +value[3], +value[4], +value[5]); } function parseSvg(value) { if (value == null) return __WEBPACK_IMPORTED_MODULE_0__decompose__["b" /* identity */]; if (!svgNode) svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g"); svgNode.setAttribute("transform", value); if (!(value = svgNode.transform.baseVal.consolidate())) return __WEBPACK_IMPORTED_MODULE_0__decompose__["b" /* identity */]; value = value.matrix; return Object(__WEBPACK_IMPORTED_MODULE_0__decompose__["a" /* default */])(value.a, value.b, value.c, value.d, value.e, value.f); } /***/ }), /* 246 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return identity; }); var degrees = 180 / Math.PI; var identity = { translateX: 0, translateY: 0, rotate: 0, skewX: 0, scaleX: 1, scaleY: 1 }; /* harmony default export */ __webpack_exports__["a"] = (function (a, b, c, d, e, f) { var scaleX, scaleY, skewX; if (scaleX = Math.sqrt(a * a + b * b)) a /= scaleX, b /= scaleX; if (skewX = a * c + b * d) c -= a * skewX, d -= b * skewX; if (scaleY = Math.sqrt(c * c + d * d)) c /= scaleY, d /= scaleY, skewX /= scaleY; if (a * d < b * c) a = -a, b = -b, skewX = -skewX, scaleX = -scaleX; return { translateX: e, translateY: f, rotate: Math.atan2(b, a) * degrees, skewX: Math.atan(skewX) * degrees, scaleX: scaleX, scaleY: scaleY }; }); /***/ }), /* 247 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; var rho = Math.SQRT2, rho2 = 2, rho4 = 4, epsilon2 = 1e-12; function cosh(x) { return ((x = Math.exp(x)) + 1 / x) / 2; } function sinh(x) { return ((x = Math.exp(x)) - 1 / x) / 2; } function tanh(x) { return ((x = Math.exp(2 * x)) - 1) / (x + 1); } // p0 = [ux0, uy0, w0] // p1 = [ux1, uy1, w1] /* harmony default export */ __webpack_exports__["a"] = (function (p0, p1) { var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; // Special case for u0 ≅ u1. if (d2 < epsilon2) { S = Math.log(w1 / w0) / rho; i = function (t) { return [ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(rho * t * S)]; }; } // General case. else { var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1), b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); S = (r1 - r0) / rho; i = function (t) { var s = t * S, coshr0 = cosh(r0), u = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s + r0) - sinh(r0)); return [ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / cosh(rho * s + r0)]; }; } i.duration = S * 1000; return i; }); /***/ }), /* 248 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return hslLong; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_d3_color__ = __webpack_require__(19); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__color__ = __webpack_require__(32); function hsl(hue) { return function (start, end) { var h = hue((start = Object(__WEBPACK_IMPORTED_MODULE_0_d3_color__["d" /* hsl */])(start)).h, (end = Object(__WEBPACK_IMPORTED_MODULE_0_d3_color__["d" /* hsl */])(end)).h), s = Object(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */])(start.s, end.s), l = Object(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */])(start.l, end.l), opacity = Object(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */])(start.opacity, end.opacity); return function (t) { start.h = h(t); start.s = s(t); start.l = l(t); start.opacity = opacity(t); return start + ""; }; }; } /* harmony default export */ __webpack_exports__["a"] = (hsl(__WEBPACK_IMPORTED_MODULE_1__color__["c" /* hue */])); var hslLong = hsl(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */]); /***/ }), /* 249 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (immutable) */ __webpack_exports__["a"] = lab; /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_d3_color__ = __webpack_require__(19); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__color__ = __webpack_require__(32); function lab(start, end) { var l = Object(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */])((start = Object(__WEBPACK_IMPORTED_MODULE_0_d3_color__["e" /* lab */])(start)).l, (end = Object(__WEBPACK_IMPORTED_MODULE_0_d3_color__["e" /* lab */])(end)).l), a = Object(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */])(start.a, end.a), b = Object(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */])(start.b, end.b), opacity = Object(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */])(start.opacity, end.opacity); return function (t) { start.l = l(t); start.a = a(t); start.b = b(t); start.opacity = opacity(t); return start + ""; }; } /***/ }), /* 250 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "b", function() { return hclLong; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_d3_color__ = __webpack_require__(19); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__color__ = __webpack_require__(32); function hcl(hue) { return function (start, end) { var h = hue((start = Object(__WEBPACK_IMPORTED_MODULE_0_d3_color__["c" /* hcl */])(start)).h, (end = Object(__WEBPACK_IMPORTED_MODULE_0_d3_color__["c" /* hcl */])(end)).h), c = Object(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */])(start.c, end.c), l = Object(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */])(start.l, end.l), opacity = Object(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */])(start.opacity, end.opacity); return function (t) { start.h = h(t); start.c = c(t); start.l = l(t); start.opacity = opacity(t); return start + ""; }; }; } /* harmony default export */ __webpack_exports__["a"] = (hcl(__WEBPACK_IMPORTED_MODULE_1__color__["c" /* hue */])); var hclLong = hcl(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */]); /***/ }), /* 251 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "a", function() { return cubehelixLong; }); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_d3_color__ = __webpack_require__(19); /* harmony import */ var __WEBPACK_IMPORTED_MODULE_1__color__ = __webpack_require__(32); function cubehelix(hue) { return function cubehelixGamma(y) { y = +y; function cubehelix(start, end) { var h = hue((start = Object(__WEBPACK_IMPORTED_MODULE_0_d3_color__["b" /* cubehelix */])(start)).h, (end = Object(__WEBPACK_IMPORTED_MODULE_0_d3_color__["b" /* cubehelix */])(end)).h), s = Object(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */])(start.s, end.s), l = Object(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */])(start.l, end.l), opacity = Object(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */])(start.opacity, end.opacity); return function (t) { start.h = h(t); start.s = s(t); start.l = l(Math.pow(t, y)); start.opacity = opacity(t); return start + ""; }; } cubehelix.gamma = cubehelixGamma; return cubehelix; }(1); } /* harmony default export */ __webpack_exports__["b"] = (cubehelix(__WEBPACK_IMPORTED_MODULE_1__color__["c" /* hue */])); var cubehelixLong = cubehelix(__WEBPACK_IMPORTED_MODULE_1__color__["a" /* default */]); /***/ }), /* 252 */ /***/ (function(module, __webpack_exports__, __webpack_require__) { "use strict"; /* harmony default export */ __webpack_exports__["a"] = (function (interpolator, n) { var samples = new Array(n); for (var i = 0; i < n; ++i) samples[i] = interpolator(i / (n - 1)); return samples; }); /***/ }), /* 253 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { canvas: __webpack_require__(254), svg: __webpack_require__(257) }; /***/ }), /* 254 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { painter: __webpack_require__(255) }; /***/ }), /* 255 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var renderUtil = __webpack_require__(256); var SHAPE_ATTRS = ['fillStyle', 'font', 'globalAlpha', 'lineCap', 'lineWidth', 'lineJoin', 'miterLimit', 'shadowBlur', 'shadowColor', 'shadowOffsetX', 'shadowOffsetY', 'strokeStyle', 'textAlign', 'textBaseline', 'lineDash', 'lineDashOffset']; var Painter = /*#__PURE__*/function () { function Painter(dom) { if (!dom) { return null; } var canvasId = Util.uniqueId('canvas_'); var canvasDom = Util.createDom(''); dom.appendChild(canvasDom); this.type = 'canvas'; this.canvas = canvasDom; this.context = canvasDom.getContext('2d'); this.toDraw = false; return this; } var _proto = Painter.prototype; _proto.beforeDraw = function beforeDraw() { var el = this.canvas; this.context && this.context.clearRect(0, 0, el.width, el.height); }; _proto.draw = function draw(model) { var self = this; function drawInner() { self.animateHandler = Util.requestAnimationFrame(function () { self.animateHandler = undefined; if (self.toDraw) { drawInner(); } }); self.beforeDraw(); try { self._drawGroup(model); } catch (ev) { // 绘制时异常,中断重绘 console.warn('error in draw canvas, detail as:'); console.warn(ev); } finally { self.toDraw = false; } } if (self.animateHandler) { self.toDraw = true; } else { drawInner(); } }; _proto.drawSync = function drawSync(model) { this.beforeDraw(); this._drawGroup(model); }; _proto._drawGroup = function _drawGroup(group) { if (group._cfg.removed || group._cfg.destroyed || !group._cfg.visible) { return; } var self = this; var children = group._cfg.children; var child = null; this.setContext(group); for (var i = 0; i < children.length; i++) { child = children[i]; if (children[i].isGroup) { self._drawGroup(child); } else { self._drawShape(child); } } this.restoreContext(group); }; _proto._drawShape = function _drawShape(shape) { if (shape._cfg.removed || shape._cfg.destroyed || !shape._cfg.visible) { return; } this.setContext(shape); shape.drawInner(this.context); this.restoreContext(shape); shape._cfg.attrs = shape._attrs; shape._cfg.hasUpdate = false; }; _proto.setContext = function setContext(shape) { var context = this.context; var clip = shape._attrs.clip; context.save(); if (clip) { // context.save(); clip.resetTransform(context); clip.createPath(context); context.clip(); // context.restore(); } this.resetContext(shape); shape.resetTransform(context); }; _proto.restoreContext = function restoreContext() { this.context.restore(); }; _proto.resetContext = function resetContext(shape) { var context = this.context; var elAttrs = shape._attrs; // var canvas = this.get('canvas'); if (!shape.isGroup) { for (var k in elAttrs) { if (SHAPE_ATTRS.indexOf(k) > -1) { // 非canvas属性不附加 var v = elAttrs[k]; if (k === 'fillStyle') { v = renderUtil.parseStyle(v, shape, context); } if (k === 'strokeStyle') { v = renderUtil.parseStyle(v, shape, context); } if (k === 'lineDash' && context.setLineDash) { if (Util.isArray(v)) { context.setLineDash(v); } else if (Util.isString(v)) { context.setLineDash(v.split(' ')); } } else { context[k] = v; } } } } }; return Painter; }(); module.exports = Painter; /***/ }), /* 256 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var regexTags = /[MLHVQTCSAZ]([^MLHVQTCSAZ]*)/ig; var regexDot = /[^\s\,]+/ig; var regexLG = /^l\s*\(\s*([\d.]+)\s*\)\s*(.*)/i; var regexRG = /^r\s*\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)\s*(.*)/i; var regexPR = /^p\s*\(\s*([axyn])\s*\)\s*(.*)/i; var regexColorStop = /[\d.]+:(#[^\s]+|[^\)]+\))/ig; // const numColorCache = {}; function addStop(steps, gradient) { var arr = steps.match(regexColorStop); Util.each(arr, function (item) { item = item.split(':'); gradient.addColorStop(item[0], item[1]); }); } function parseLineGradient(color, self, context) { var arr = regexLG.exec(color); var angle = Util.mod(Util.toRadian(parseFloat(arr[1])), Math.PI * 2); var steps = arr[2]; var box = self.getBBox(); var start; var end; if (angle >= 0 && angle < 0.5 * Math.PI) { start = { x: box.minX, y: box.minY }; end = { x: box.maxX, y: box.maxY }; } else if (0.5 * Math.PI <= angle && angle < Math.PI) { start = { x: box.maxX, y: box.minY }; end = { x: box.minX, y: box.maxY }; } else if (Math.PI <= angle && angle < 1.5 * Math.PI) { start = { x: box.maxX, y: box.maxY }; end = { x: box.minX, y: box.minY }; } else { start = { x: box.minX, y: box.maxY }; end = { x: box.maxX, y: box.minY }; } var tanTheta = Math.tan(angle); var tanTheta2 = tanTheta * tanTheta; var x = (end.x - start.x + tanTheta * (end.y - start.y)) / (tanTheta2 + 1) + start.x; var y = tanTheta * (end.x - start.x + tanTheta * (end.y - start.y)) / (tanTheta2 + 1) + start.y; var gradient = context.createLinearGradient(start.x, start.y, x, y); addStop(steps, gradient); return gradient; } function parseRadialGradient(color, self, context) { var arr = regexRG.exec(color); var fx = parseFloat(arr[1]); var fy = parseFloat(arr[2]); var fr = parseFloat(arr[3]); var steps = arr[4]; // 环半径为0时,默认无渐变,取渐变序列的最后一个颜色 if (fr === 0) { var colors = steps.match(regexColorStop); return colors[colors.length - 1].split(':')[1]; } var box = self.getBBox(); var width = box.maxX - box.minX; var height = box.maxY - box.minY; var r = Math.sqrt(width * width + height * height) / 2; var gradient = context.createRadialGradient(box.minX + width * fx, box.minY + height * fy, fr * r, box.minX + width / 2, box.minY + height / 2, r); addStop(steps, gradient); return gradient; } function parsePattern(color, self, context) { if (self.get('patternSource') && self.get('patternSource') === color) { return self.get('pattern'); } var pattern; var img; var arr = regexPR.exec(color); var repeat = arr[1]; var source = arr[2]; // Function to be called when pattern loads function onload() { // Create pattern pattern = context.createPattern(img, repeat); self.setSilent('pattern', pattern); // be a cache self.setSilent('patternSource', color); } switch (repeat) { case 'a': repeat = 'repeat'; break; case 'x': repeat = 'repeat-x'; break; case 'y': repeat = 'repeat-y'; break; case 'n': repeat = 'no-repeat'; break; default: repeat = 'no-repeat'; } img = new Image(); // If source URL is not a data URL if (!source.match(/^data:/i)) { // Set crossOrigin for this image img.crossOrigin = 'Anonymous'; } img.src = source; if (img.complete) { onload(); } else { img.onload = onload; // Fix onload() bug in IE9 img.src = img.src; } return pattern; } module.exports = { parsePath: function parsePath(path) { path = path || []; if (Util.isArray(path)) { return path; } if (Util.isString(path)) { path = path.match(regexTags); Util.each(path, function (item, index) { item = item.match(regexDot); if (item[0].length > 1) { var tag = item[0].charAt(0); item.splice(1, 0, item[0].substr(1)); item[0] = tag; } Util.each(item, function (sub, i) { if (!isNaN(sub)) { item[i] = +sub; } }); path[index] = item; }); return path; } }, parseStyle: function parseStyle(color, self, context) { if (Util.isString(color)) { if (color[1] === '(' || color[2] === '(') { if (color[0] === 'l') { // regexLG.test(color) return parseLineGradient(color, self, context); } else if (color[0] === 'r') { // regexRG.test(color) return parseRadialGradient(color, self, context); } else if (color[0] === 'p') { // regexPR.test(color) return parsePattern(color, self, context); } } return color; } } /* , numberToColor(num) { // 增加缓存 let color = numColorCache[num]; if (!color) { let str = num.toString(16); for (let i = str.length; i < 6; i++) { str = '0' + str; } color = '#' + str; numColorCache[num] = color; } return color; }*/ }; /***/ }), /* 257 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { painter: __webpack_require__(258), getShape: __webpack_require__(265) }; /***/ }), /* 258 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(1); var _require = __webpack_require__(31), parseRadius = _require.parseRadius; var Marker = __webpack_require__(81); var Defs = __webpack_require__(259); var SHAPE_TO_TAGS = { rect: 'path', circle: 'circle', line: 'line', path: 'path', marker: 'path', text: 'text', polygon: 'polygon', image: 'image', ellipse: 'ellipse', dom: 'foreignObject', fan: 'path', group: 'g' }; var LETTER_SPACING = 0.3; var SVG_ATTR_MAP = { opacity: 'opacity', fillStyle: 'fill', strokeOpacity: 'stroke-opacity', fillOpacity: 'fill-opacity', strokeStyle: 'stroke', x: 'x', y: 'y', r: 'r', rx: 'rx', ry: 'ry', width: 'width', height: 'height', x1: 'x1', x2: 'x2', y1: 'y1', y2: 'y2', lineCap: 'stroke-linecap', lineJoin: 'stroke-linejoin', lineWidth: 'stroke-width', lineDash: 'stroke-dasharray', lineDashOffset: 'stroke-dashoffset', miterLimit: 'stroke-miterlimit', font: 'font', fontSize: 'font-size', fontStyle: 'font-style', fontVariant: 'font-variant', fontWeight: 'font-weight', fontFamily: 'font-family', startArrow: 'marker-start', endArrow: 'marker-end', path: 'd', "class": 'class', id: 'id', style: 'style', preserveAspectRatio: 'preserveAspectRatio' }; var BASELINE_MAP = { top: 'before-edge', middle: 'central', bottom: 'after-edge', alphabetic: 'baseline', hanging: 'hanging' }; var ANCHOR_MAP = { left: 'left', start: 'left', center: 'middle', right: 'end', end: 'end' }; var Painter = /*#__PURE__*/function () { function Painter(dom) { if (!dom) { return null; } var svgId = Util.uniqueId('canvas_'); var canvasDom = Util.createDom(""); dom.appendChild(canvasDom); this.type = 'svg'; this.canvas = canvasDom; this.context = new Defs(canvasDom); this.toDraw = false; return this; } var _proto = Painter.prototype; _proto.draw = function draw(model) { var self = this; function drawInner() { self.animateHandler = Util.requestAnimationFrame(function () { self.animateHandler = undefined; if (self.toDraw) { drawInner(); } }); try { self._drawChildren(model); } catch (ev) { // 绘制时异常,中断重绘 console.warn('error in draw canvas, detail as:'); console.warn(ev); } finally { self.toDraw = false; } } if (self.animateHandler) { self.toDraw = true; } else { drawInner(); } }; _proto.drawSync = function drawSync(model) { this._drawChildren(model); }; _proto._drawGroup = function _drawGroup(model, index) { var cfg = model._cfg; if (cfg.removed || cfg.destroyed) { return; } if (cfg.tobeRemoved) { Util.each(cfg.tobeRemoved, function (item) { if (item.parentNode) { item.parentNode.removeChild(item); } }); cfg.tobeRemoved = []; } this._drawShape(model, index); if (cfg.children && cfg.children.length > 0) { this._drawChildren(model); } }; _proto._drawChildren = function _drawChildren(parent) { var self = this; var children = parent._cfg.children; var shape; // 防止在画children的时候,父group已经被destroy if (!children) { return; } for (var i = 0; i < children.length; i++) { shape = children[i]; if (shape.isGroup) { self._drawGroup(shape, i); } else { self._drawShape(shape, i); } } }; _proto._drawShape = function _drawShape(model, index) { var self = this; var attrs = model._attrs; var cfg = model._cfg; var el = cfg.el; // 删除 if (cfg.removed || cfg.destroyed) { if (el) { el.parentNode.removeChild(cfg.el); } return; } // 新增节点 if (!el && cfg.parent) { self._createDom(model, index); self._updateShape(model); } el = cfg.el; if (cfg.visible === false) { el.setAttribute('visibility', 'hidden'); return; } if (cfg.visible && el.hasAttribute('visibility')) { el.removeAttribute('visibility'); } // 更新 if (cfg.hasUpdate) { self._updateShape(model); } if (attrs.clip && attrs.clip._cfg.hasUpdate) { self._updateShape(attrs.clip); } }; _proto._updateShape = function _updateShape(model) { var self = this; var attrs = model._attrs; var formerAttrs = model._cfg.attrs; if (!formerAttrs) { return; } if (!model._cfg.el) { self._createDom(model); } if ('clip' in attrs) { this._setClip(model, attrs.clip); } if ('shadowOffsetX' in attrs || 'shadowOffsetY' in attrs || 'shadowBlur' in attrs || 'shadowColor' in attrs) { this._setShadow(model); } if (model.type === 'text') { self._updateText(model); return; } if (model.type === 'fan') { self._updateFan(model); } if (model.type === 'marker') { model._cfg.el.setAttribute('d', self._assembleMarker(attrs)); } if (model.type === 'rect') { model._cfg.el.setAttribute('d', self._assembleRect(attrs)); } for (var key in attrs) { if (attrs[key] !== formerAttrs[key]) { self._setAttribute(model, key, attrs[key]); } } model._cfg.attrs = Util.deepMix({}, model._attrs); model._cfg.hasUpdate = false; }; _proto._setAttribute = function _setAttribute(model, name, value) { var type = model.type; var attrs = model._attrs; var el = model._cfg.el; var defs = this.context; // 计算marker路径 if ((type === 'marker' || type === 'rect') && ~['x', 'y', 'radius', 'r'].indexOf(name)) { return; } // 圆和椭圆不是x, y, 是cx, cy。 marker的x,y 用于计算marker的路径,不需要写到dom if (~['circle', 'ellipse'].indexOf(type) && ~['x', 'y'].indexOf(name)) { el.setAttribute('c' + name, parseInt(value, 10)); return; } // 多边形 if (type === 'polygon' && name === 'points') { if (!value || value.length === 0) { value = ''; } if (Util.isArray(value)) { value = value.map(function (point) { return point[0] + ',' + point[1]; }); value = value.join(' '); } el.setAttribute('points', value); return; } // 设置path if (name === 'path' && Util.isArray(value)) { el.setAttribute('d', this._formatPath(value)); return; } // 设置图片 if (name === 'img') { this._setImage(model, value); return; } if (name === 'transform') { if (!value) { el.removeAttribute('transform'); return; } this._setTransform(model); return; } if (name === 'rotate') { if (!value) { el.removeAttribute('transform'); return; } this._setTransform(model); return; } if (name === 'matrix') { this._setTransform(model); return; } if (name === 'fillStyle' || name === 'strokeStyle') { this._setColor(model, name, value); return; } if (name === 'clip') { return; } if (~name.indexOf('Arrow')) { name = SVG_ATTR_MAP[name]; if (!value) { model._cfg[name] = null; el.removeAttribute(name); } else { var id = null; if (typeof value === 'boolean') { id = defs.getDefaultArrow(attrs, name); } else { id = defs.addArrow(attrs, name); } el.setAttribute(name, "url(#" + id + ")"); model._cfg[name] = id; } return; } // foreignObject if (name === 'html') { if (typeof value === 'string') { el.innerHTML = value; } else { el.innerHTML = ''; el.appendChild(value); } } if (SVG_ATTR_MAP[name]) { el.setAttribute(SVG_ATTR_MAP[name], value); } }; _proto._createDom = function _createDom(model, index) { var type = SHAPE_TO_TAGS[model.type]; var attrs = model._attrs; var parent = model._cfg.parent; if (!type) { throw new Error('the type' + model.type + 'is not supported by svg'); } var shape = document.createElementNS('http://www.w3.org/2000/svg', type); if (model._cfg.id) { shape.id = model._cfg.id; } model._cfg.el = shape; if (parent) { var parentNode = parent._cfg.el; if (typeof index === 'undefined') { parentNode.appendChild(shape); } else { var childNodes = parent._cfg.el.childNodes; // svg下天然有defs作为子节点,svg下子元素index需要+1 if (parentNode.tagName === 'svg') { index += 1; } if (childNodes.length <= index) { parentNode.appendChild(shape); } else { parentNode.insertBefore(shape, childNodes[index]); } } } model._cfg.attrs = {}; if (model.type === 'text') { shape.setAttribute('paint-order', 'stroke'); shape.setAttribute('style', 'stroke-linecap:butt; stroke-linejoin:miter;'); } else { if (!attrs.stroke && !attrs.strokeStyle) { shape.setAttribute('stroke', 'none'); } if (!attrs.fill && !attrs.fillStyle) { shape.setAttribute('fill', 'none'); } } return shape; }; _proto._assembleMarker = function _assembleMarker(attrs) { var r = attrs.r; if (typeof attrs.r === 'undefined') { r = attrs.radius; } if (isNaN(Number(attrs.x)) || isNaN(Number(attrs.y)) || isNaN(Number(r))) { return ''; } var d = ''; if (typeof attrs.symbol === 'function') { d = attrs.symbol(attrs.x, attrs.y, r); } else { d = Marker.Symbols[attrs.symbol || 'circle'](attrs.x, attrs.y, r); } if (Util.isArray(d)) { d = d.map(function (path) { return path.join(' '); }).join(''); } return d; }; _proto._assembleRect = function _assembleRect(attrs) { var x = attrs.x; var y = attrs.y; var w = attrs.width; var h = attrs.height; var radius = attrs.radius; if (!radius) { return "M " + x + "," + y + " l " + w + ",0 l 0," + h + " l" + -w + " 0 z"; } var r = parseRadius(radius); if (Util.isArray(radius)) { if (radius.length === 1) { r.r1 = r.r2 = r.r3 = r.r4 = radius[0]; } else if (radius.length === 2) { r.r1 = r.r3 = radius[0]; r.r2 = r.r4 = radius[1]; } else if (radius.length === 3) { r.r1 = radius[0]; r.r2 = r.r4 = radius[1]; r.r3 = radius[2]; } else { r.r1 = radius[0]; r.r2 = radius[1]; r.r3 = radius[2]; r.r4 = radius[3]; } } else { r.r1 = r.r2 = r.r3 = r.r4 = radius; } var d = [["M " + (x + r.r1) + "," + y], ["l " + (w - r.r1 - r.r2) + ",0"], ["a " + r.r2 + "," + r.r2 + ",0,0,1," + r.r2 + "," + r.r2], ["l 0," + (h - r.r2 - r.r3)], ["a " + r.r3 + "," + r.r3 + ",0,0,1," + -r.r3 + "," + r.r3], ["l " + (r.r3 + r.r4 - w) + ",0"], ["a " + r.r4 + "," + r.r4 + ",0,0,1," + -r.r4 + "," + -r.r4], ["l 0," + (r.r4 + r.r1 - h)], ["a " + r.r1 + "," + r.r1 + ",0,0,1," + r.r1 + "," + -r.r1], ['z']]; return d.join(' '); }; _proto._formatPath = function _formatPath(value) { value = value.map(function (path) { return path.join(' '); }).join(''); if (~value.indexOf('NaN')) { return ''; } return value; }; _proto._setTransform = function _setTransform(model) { var matrix = model._attrs.matrix; var el = model._cfg.el; var transform = []; for (var i = 0; i < 9; i += 3) { transform.push(matrix[i] + ',' + matrix[i + 1]); } transform = transform.join(','); if (transform.indexOf('NaN') === -1) { el.setAttribute('transform', "matrix(" + transform + ")"); } else { console.warn('invalid matrix:', matrix); } }; _proto._setImage = function _setImage(model, img) { var attrs = model._attrs; var el = model._cfg.el; if (Util.isString(img)) { el.setAttribute('href', img); } else if (img instanceof Image) { if (!attrs.width) { el.setAttribute('width', img.width); model._attrs.width = img.width; } if (!attrs.height) { el.setAttribute('height', img.height); model._attrs.height = img.height; } el.setAttribute('href', img.src); } else if (img instanceof HTMLElement && Util.isString(img.nodeName) && img.nodeName.toUpperCase() === 'CANVAS') { el.setAttribute('href', img.toDataURL()); } else if (img instanceof ImageData) { var canvas = document.createElement('canvas'); canvas.setAttribute('width', img.width); canvas.setAttribute('height', img.height); canvas.getContext('2d').putImageData(img, 0, 0); if (!attrs.width) { el.setAttribute('width', img.width); model._attrs.width = img.width; } if (!attrs.height) { el.setAttribute('height', img.height); model._attrs.height = img.height; } el.setAttribute('href', canvas.toDataURL()); } }; _proto._updateFan = function _updateFan(model) { function getPoint(angle, radius, center) { return { x: radius * Math.cos(angle) + center.x, y: radius * Math.sin(angle) + center.y }; } var attrs = model._attrs; var cfg = model._cfg; var center = { x: attrs.x, y: attrs.y }; var d = []; var startAngle = attrs.startAngle; var endAngle = attrs.endAngle; if (Util.isNumberEqual(endAngle - startAngle, Math.PI * 2)) { endAngle -= 0.00001; } var outerStart = getPoint(startAngle, attrs.re, center); var outerEnd = getPoint(endAngle, attrs.re, center); var fa = endAngle > startAngle ? 1 : 0; var fs = Math.abs(endAngle - startAngle) > Math.PI ? 1 : 0; var rs = attrs.rs; var re = attrs.re; var innerStart = getPoint(startAngle, attrs.rs, center); var innerEnd = getPoint(endAngle, attrs.rs, center); if (attrs.rs > 0) { d.push("M " + outerEnd.x + "," + outerEnd.y); d.push("L " + innerEnd.x + "," + innerEnd.y); d.push("A " + rs + "," + rs + ",0," + fs + "," + (fa === 1 ? 0 : 1) + "," + innerStart.x + "," + innerStart.y); d.push("L " + outerStart.x + " " + outerStart.y); } else { d.push("M " + center.x + "," + center.y); d.push("L " + outerStart.x + "," + outerStart.y); } d.push("A " + re + "," + re + ",0," + fs + "," + fa + "," + outerEnd.x + "," + outerEnd.y); if (attrs.rs > 0) { d.push("L " + innerEnd.x + "," + innerEnd.y); } else { d.push('Z'); } cfg.el.setAttribute('d', d.join(' ')); }; _proto._updateText = function _updateText(model) { var self = this; var attrs = model._attrs; var formerAttrs = model._cfg.attrs; var el = model._cfg.el; this._setFont(model); for (var attr in attrs) { if (attrs[attr] !== formerAttrs[attr]) { if (attr === 'text') { self._setText(model, "" + attrs[attr]); continue; } if (attr === 'fillStyle' || attr === 'strokeStyle') { this._setColor(model, attr, attrs[attr]); continue; } if (attr === 'matrix') { this._setTransform(model); continue; } if (SVG_ATTR_MAP[attr]) { el.setAttribute(SVG_ATTR_MAP[attr], attrs[attr]); } } } model._cfg.attrs = Object.assign({}, model._attrs); model._cfg.hasUpdate = false; }; _proto._setFont = function _setFont(model) { var el = model.get('el'); var attrs = model._attrs; var fontSize = attrs.fontSize; el.setAttribute('alignment-baseline', BASELINE_MAP[attrs.textBaseline] || 'baseline'); el.setAttribute('text-anchor', ANCHOR_MAP[attrs.textAlign] || 'left'); if (fontSize && +fontSize < 12) { // 小于 12 像素的文本进行 scale 处理 attrs.matrix = [1, 0, 0, 0, 1, 0, 0, 0, 1]; model.transform([['t', -attrs.x, -attrs.y], ['s', +fontSize / 12, +fontSize / 12], ['t', attrs.x, attrs.y]]); } }; _proto._setText = function _setText(model, text) { var el = model._cfg.el; var baseline = model._attrs.textBaseline || 'bottom'; if (!text) { el.innerHTML = ''; } else if (~text.indexOf('\n')) { var x = model._attrs.x; var textArr = text.split('\n'); var textLen = textArr.length - 1; var arr = ''; Util.each(textArr, function (segment, i) { if (i === 0) { if (baseline === 'alphabetic') { arr += "" + segment + ""; } else if (baseline === 'top') { arr += "" + segment + ""; } else if (baseline === 'middle') { arr += "" + segment + ""; } else if (baseline === 'bottom') { arr += "" + segment + ""; } else if (baseline === 'hanging') { arr += "" + segment + ""; } } else { arr += "" + segment + ""; } }); el.innerHTML = arr; } else { el.innerHTML = text; } }; _proto._setClip = function _setClip(model, value) { var el = model._cfg.el; if (!value) { el.removeAttribute('clip-path'); return; } if (!el.hasAttribute('clip-path')) { this._createDom(value); this._updateShape(value); var id = this.context.addClip(value); el.setAttribute('clip-path', "url(#" + id + ")"); } else if (value._cfg.hasUpdate) { this._updateShape(value); } }; _proto._setColor = function _setColor(model, name, value) { var el = model._cfg.el; var defs = this.context; if (!value) { el.setAttribute(SVG_ATTR_MAP[name], 'none'); return; } value = value.trim(); if (/^[r,R,L,l]{1}[\s]*\(/.test(value)) { var id = defs.find('gradient', value); if (!id) { id = defs.addGradient(value); } el.setAttribute(SVG_ATTR_MAP[name], "url(#" + id + ")"); } else if (/^[p,P]{1}[\s]*\(/.test(value)) { var _id = defs.find('pattern', value); if (!_id) { _id = defs.addPattern(value); } el.setAttribute(SVG_ATTR_MAP[name], "url(#" + _id + ")"); } else { el.setAttribute(SVG_ATTR_MAP[name], value); } }; _proto._setShadow = function _setShadow(model) { var el = model._cfg.el; var attrs = model._attrs; var cfg = { dx: attrs.shadowOffsetX, dy: attrs.shadowOffsetY, blur: attrs.shadowBlur, color: attrs.shadowColor }; if (!cfg.dx && !cfg.dy && !cfg.blur && !cfg.color) { el.removeAttribute('filter'); } else { var id = this.context.find('filter', cfg); if (!id) { id = this.context.addShadow(cfg, this); } el.setAttribute('filter', "url(#" + id + ")"); } }; return Painter; }(); module.exports = Painter; /***/ }), /* 259 */ /***/ (function(module, exports, __webpack_require__) { /** * Created by Elaine on 2018/5/9. */ var Util = __webpack_require__(1); var Gradient = __webpack_require__(260); var Shadow = __webpack_require__(261); var Arrow = __webpack_require__(262); var Clip = __webpack_require__(263); var Pattern = __webpack_require__(264); var Defs = /*#__PURE__*/function () { function Defs(canvas) { var el = document.createElementNS('http://www.w3.org/2000/svg', 'defs'); var id = Util.uniqueId('defs_'); el.id = id; canvas.appendChild(el); this.children = []; this.defaultArrow = {}; this.el = el; this.canvas = canvas; } var _proto = Defs.prototype; _proto.find = function find(type, attr) { var children = this.children; var result = null; for (var i = 0; i < children.length; i++) { if (children[i].match(type, attr)) { result = children[i].id; break; } } return result; }; _proto.findById = function findById(id) { var children = this.children; var flag = null; for (var i = 0; i < children.length; i++) { if (children[i].id === id) { flag = children[i]; break; } } return flag; }; _proto.add = function add(item) { this.children.push(item); item.canvas = this.canvas; item.parent = this; }; _proto.getDefaultArrow = function getDefaultArrow(attrs, name) { var stroke = attrs.stroke || attrs.strokeStyle; if (this.defaultArrow[stroke]) { return this.defaultArrow[stroke].id; } var arrow = new Arrow(attrs, name); this.defaultArrow[stroke] = arrow; this.el.appendChild(arrow.el); return arrow.id; }; _proto.addGradient = function addGradient(cfg) { var gradient = new Gradient(cfg); this.el.appendChild(gradient.el); this.add(gradient); return gradient.id; }; _proto.addArrow = function addArrow(attrs, name) { var arrow = new Arrow(attrs, name); this.el.appendChild(arrow.el); return arrow.id; }; _proto.addShadow = function addShadow(cfg) { var shadow = new Shadow(cfg); this.el.appendChild(shadow.el); this.add(shadow); return shadow.id; }; _proto.addPattern = function addPattern(cfg) { var pattern = new Pattern(cfg); this.el.appendChild(pattern.el); this.add(pattern); return pattern.id; }; _proto.addClip = function addClip(cfg) { var clip = new Clip(cfg); this.el.appendChild(clip.el); this.add(clip); return clip.id; }; return Defs; }(); module.exports = Defs; /***/ }), /* 260 */ /***/ (function(module, exports, __webpack_require__) { /** * Created by Elaine on 2018/5/9. */ var Util = __webpack_require__(1); var regexLG = /^l\s*\(\s*([\d.]+)\s*\)\s*(.*)/i; var regexRG = /^r\s*\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)\s*(.*)/i; var regexColorStop = /[\d.]+:(#[^\s]+|[^\)]+\))/ig; function addStop(steps) { var arr = steps.match(regexColorStop); if (!arr) { return ''; } var stops = ''; arr.sort(function (a, b) { a = a.split(':'); b = b.split(':'); return Number(a[0]) - Number(b[0]); }); Util.each(arr, function (item) { item = item.split(':'); stops += ""; }); return stops; } function parseLineGradient(color, el) { var arr = regexLG.exec(color); var angle = Util.mod(Util.toRadian(parseFloat(arr[1])), Math.PI * 2); var steps = arr[2]; var start; var end; if (angle >= 0 && angle < 0.5 * Math.PI) { start = { x: 0, y: 0 }; end = { x: 1, y: 1 }; } else if (0.5 * Math.PI <= angle && angle < Math.PI) { start = { x: 1, y: 0 }; end = { x: 0, y: 1 }; } else if (Math.PI <= angle && angle < 1.5 * Math.PI) { start = { x: 1, y: 1 }; end = { x: 0, y: 0 }; } else { start = { x: 0, y: 1 }; end = { x: 1, y: 0 }; } var tanTheta = Math.tan(angle); var tanTheta2 = tanTheta * tanTheta; var x = (end.x - start.x + tanTheta * (end.y - start.y)) / (tanTheta2 + 1) + start.x; var y = tanTheta * (end.x - start.x + tanTheta * (end.y - start.y)) / (tanTheta2 + 1) + start.y; el.setAttribute('x1', start.x); el.setAttribute('y1', start.y); el.setAttribute('x2', x); el.setAttribute('y2', y); el.innerHTML = addStop(steps); } function parseRadialGradient(color, self) { var arr = regexRG.exec(color); var cx = parseFloat(arr[1]); var cy = parseFloat(arr[2]); var r = parseFloat(arr[3]); var steps = arr[4]; self.setAttribute('cx', cx); self.setAttribute('cy', cy); self.setAttribute('r', r); self.innerHTML = addStop(steps); } var Gradient = /*#__PURE__*/function () { function Gradient(cfg) { var el = null; var id = Util.uniqueId('gradient_'); if (cfg.toLowerCase()[0] === 'l') { el = document.createElementNS('http://www.w3.org/2000/svg', 'linearGradient'); parseLineGradient(cfg, el); } else { el = document.createElementNS('http://www.w3.org/2000/svg', 'radialGradient'); parseRadialGradient(cfg, el); } el.setAttribute('id', id); this.el = el; this.id = id; this.cfg = cfg; return this; } var _proto = Gradient.prototype; _proto.match = function match(type, attr) { return this.cfg === attr; }; return Gradient; }(); module.exports = Gradient; /***/ }), /* 261 */ /***/ (function(module, exports, __webpack_require__) { /** * Created by Elaine on 2018/5/10. */ var Util = __webpack_require__(1); var ATTR_MAP = { shadowColor: 'color', shadowOpacity: 'opacity', shadowBlur: 'blur', shadowOffsetX: 'dx', shadowOffsetY: 'dy' }; var SHADOW_DIMENSION = { x: '-40%', y: '-40%', width: '200%', height: '200%' }; var Shadow = /*#__PURE__*/function () { function Shadow(cfg) { this.type = 'filter'; var el = document.createElementNS('http://www.w3.org/2000/svg', 'filter'); // expand the filter region to fill in shadows Util.each(SHADOW_DIMENSION, function (v, k) { el.setAttribute(k, v); }); this.el = el; this.id = Util.uniqueId('filter_'); this.el.id = this.id; this.cfg = cfg; this._parseShadow(cfg, el); return this; } var _proto = Shadow.prototype; _proto.match = function match(type, cfg) { if (this.type !== type) { return false; } var flag = true; var config = this.cfg; Util.each(Object.keys(config), function (attr) { if (config[attr] !== cfg[attr]) { flag = false; return false; } }); return flag; }; _proto.update = function update(name, value) { var config = this.cfg; config[ATTR_MAP[name]] = value; this._parseShadow(config, this.el); return this; }; _proto._parseShadow = function _parseShadow(config, el) { var child = ""; el.innerHTML = child; }; return Shadow; }(); module.exports = Shadow; /***/ }), /* 262 */ /***/ (function(module, exports, __webpack_require__) { /** * Created by Elaine on 2018/5/11. */ var Util = __webpack_require__(1); var Arrow = /*#__PURE__*/function () { function Arrow(attrs, type) { var el = document.createElementNS('http://www.w3.org/2000/svg', 'marker'); var id = Util.uniqueId('marker_'); el.setAttribute('id', id); var shape = document.createElementNS('http://www.w3.org/2000/svg', 'path'); shape.setAttribute('stroke', 'none'); shape.setAttribute('fill', attrs.stroke || '#000'); el.appendChild(shape); el.setAttribute('overflow', 'visible'); el.setAttribute('orient', 'auto-start-reverse'); this.el = el; this.child = shape; this.id = id; this.cfg = attrs[type === 'marker-start' ? 'startArrow' : 'endArrow']; this.stroke = attrs.stroke || '#000'; if (this.cfg === true) { this._setDefaultPath(type, shape); } else { this._setMarker(attrs.lineWidth, shape); } return this; } var _proto = Arrow.prototype; _proto.match = function match() { return false; }; _proto._setDefaultPath = function _setDefaultPath(type, el) { var parent = this.el; el.setAttribute('d', 'M0,0 L6,3 L0,6 L3,3Z'); parent.setAttribute('refX', 3); parent.setAttribute('refY', 3); }; _proto._setMarker = function _setMarker(r, el) { var parent = this.el; var path = this.cfg.path; var d = this.cfg.d; if (Util.isArray(path)) { path = path.map(function (segment) { return segment.join(' '); }).join(''); } el.setAttribute('d', path); parent.appendChild(el); if (d) { parent.setAttribute('refX', d / r); } }; _proto.update = function update(fill) { var child = this.child; if (child.attr) { child.attr('fill', fill); } else { child.setAttribute('fill', fill); } }; return Arrow; }(); module.exports = Arrow; /***/ }), /* 263 */ /***/ (function(module, exports, __webpack_require__) { /** * Created by Elaine on 2018/5/14. */ var Util = __webpack_require__(1); var Clip = /*#__PURE__*/function () { function Clip(cfg) { this.type = 'clip'; var el = document.createElementNS('http://www.w3.org/2000/svg', 'clipPath'); this.el = el; this.id = Util.uniqueId('clip_'); el.id = this.id; var shapeEl = cfg._cfg.el; // just in case the clip shape is also a shape needs to be drawn el.appendChild(shapeEl.cloneNode(true)); this.cfg = cfg; return this; } var _proto = Clip.prototype; _proto.match = function match() { return false; }; _proto.remove = function remove() { var el = this.el; el.parentNode.removeChild(el); }; return Clip; }(); module.exports = Clip; /***/ }), /* 264 */ /***/ (function(module, exports, __webpack_require__) { /** * Created by Elaine on 2018/5/9. */ var Util = __webpack_require__(1); var regexPR = /^p\s*\(\s*([axyn])\s*\)\s*(.*)/i; var Pattern = /*#__PURE__*/function () { function Pattern(cfg) { var el = document.createElementNS('http://www.w3.org/2000/svg', 'pattern'); el.setAttribute('patternUnits', 'userSpaceOnUse'); var child = document.createElementNS('http://www.w3.org/2000/svg', 'image'); el.appendChild(child); var id = Util.uniqueId('pattern_'); el.id = id; this.el = el; this.id = id; this.cfg = cfg; var arr = regexPR.exec(cfg); var source = arr[2]; child.setAttribute('href', source); var img = new Image(); if (!source.match(/^data:/i)) { img.crossOrigin = 'Anonymous'; } img.src = source; function onload() { el.setAttribute('width', img.width); el.setAttribute('height', img.height); } if (img.complete) { onload(); } else { img.onload = onload; // Fix onload() bug in IE9 img.src = img.src; } return this; } var _proto = Pattern.prototype; _proto.match = function match(type, attr) { return this.cfg === attr; }; return Pattern; }(); module.exports = Pattern; /***/ }), /* 265 */ /***/ (function(module, exports) { var TAG_MAP = { svg: 'svg', circle: 'circle', rect: 'rect', text: 'text', path: 'path', foreignObject: 'foreignObject', polygon: 'polygon', ellipse: 'ellipse', image: 'image' }; module.exports = function getShape(x, y, e) { var target = e.target || e.srcElement; if (!TAG_MAP[target.tagName]) { var parent = target.parentNode; while (parent && !TAG_MAP[parent.tagName]) { parent = parent.parentNode; } target = parent; } if (this._cfg.el === target) { return this; } return this.find(function (item) { return item._cfg && item._cfg.el === target; }); }; /***/ }), /* 266 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { addEventListener: __webpack_require__(267), createDom: __webpack_require__(71), getBoundingClientRect: __webpack_require__(268), getHeight: __webpack_require__(269), getOuterHeight: __webpack_require__(270), getOuterWidth: __webpack_require__(271), getRatio: __webpack_require__(272), getStyle: __webpack_require__(273), getWidth: __webpack_require__(274), modifyCSS: __webpack_require__(72), requestAnimationFrame: __webpack_require__(73) }; /***/ }), /* 267 */ /***/ (function(module, exports) { /** * 添加事件监听器 * @param {Object} target DOM对象 * @param {String} eventType 事件名 * @param {Funtion} callback 回调函数 * @return {Object} 返回对象 */ module.exports = function addEventListener(target, eventType, callback) { if (target) { if (target.addEventListener) { target.addEventListener(eventType, callback, false); return { remove: function remove() { target.removeEventListener(eventType, callback, false); } }; } else if (target.attachEvent) { target.attachEvent('on' + eventType, callback); return { remove: function remove() { target.detachEvent('on' + eventType, callback); } }; } } }; /***/ }), /* 268 */ /***/ (function(module, exports) { module.exports = function getBoundingClientRect(node, defaultValue) { if (node && node.getBoundingClientRect) { var rect = node.getBoundingClientRect(); var top = document.documentElement.clientTop; var left = document.documentElement.clientLeft; return { top: rect.top - top, bottom: rect.bottom - top, left: rect.left - left, right: rect.right - left }; } return defaultValue || null; }; /***/ }), /* 269 */ /***/ (function(module, exports) { /** * 获取高度 * @param {HTMLElement} el dom节点 * @param {Number} defaultValue 默认值 * @return {Number} 高度 */ module.exports = function getHeight(el, defaultValue) { var height = this.getStyle(el, 'height', defaultValue); if (height === 'auto') { height = el.offsetHeight; } return parseFloat(height); }; /***/ }), /* 270 */ /***/ (function(module, exports) { /** * 获取外层高度 * @param {HTMLElement} el dom节点 * @param {Number} defaultValue 默认值 * @return {Number} 高度 */ module.exports = function getOuterHeight(el, defaultValue) { var height = this.getHeight(el, defaultValue); var bTop = parseFloat(this.getStyle(el, 'borderTopWidth')) || 0; var pTop = parseFloat(this.getStyle(el, 'paddingTop')) || 0; var pBottom = parseFloat(this.getStyle(el, 'paddingBottom')) || 0; var bBottom = parseFloat(this.getStyle(el, 'borderBottomWidth')) || 0; return height + bTop + bBottom + pTop + pBottom; }; /***/ }), /* 271 */ /***/ (function(module, exports) { /** * 获取外层宽度 * @param {HTMLElement} el dom节点 * @param {Number} defaultValue 默认值 * @return {Number} 宽度 */ module.exports = function getOuterWidth(el, defaultValue) { var width = this.getWidth(el, defaultValue); var bLeft = parseFloat(this.getStyle(el, 'borderLeftWidth')) || 0; var pLeft = parseFloat(this.getStyle(el, 'paddingLeft')) || 0; var pRight = parseFloat(this.getStyle(el, 'paddingRight')) || 0; var bRight = parseFloat(this.getStyle(el, 'borderRightWidth')) || 0; return width + bLeft + bRight + pLeft + pRight; }; /***/ }), /* 272 */ /***/ (function(module, exports) { module.exports = function getRatio() { return window.devicePixelRatio ? window.devicePixelRatio : 2; }; /***/ }), /* 273 */ /***/ (function(module, exports, __webpack_require__) { var isNil = __webpack_require__(6); /** * 获取样式 * @param {Object} dom DOM节点 * @param {String} name 样式名 * @param {Any} defaultValue 默认值 * @return {String} 属性值 */ module.exports = function getStyle(dom, name, defaultValue) { try { if (window.getComputedStyle) { return window.getComputedStyle(dom, null)[name]; } return dom.currentStyle[name]; } catch (e) { if (!isNil(defaultValue)) { return defaultValue; } return null; } }; /***/ }), /* 274 */ /***/ (function(module, exports) { /** * 获取宽度 * @param {HTMLElement} el dom节点 * @param {Number} defaultValue 默认值 * @return {Number} 宽度 */ module.exports = function getWidth(el, defaultValue) { var width = this.getStyle(el, 'width', defaultValue); if (width === 'auto') { width = el.offsetWidth; } return parseFloat(width); }; /***/ }), /* 275 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { contains: __webpack_require__(48), difference: __webpack_require__(276), find: __webpack_require__(277), firstValue: __webpack_require__(278), flatten: __webpack_require__(279), flattenDeep: __webpack_require__(280), getRange: __webpack_require__(281), merge: __webpack_require__(49), pull: __webpack_require__(67), pullAt: __webpack_require__(146), reduce: __webpack_require__(282), remove: __webpack_require__(283), sortBy: __webpack_require__(284), union: __webpack_require__(285), uniq: __webpack_require__(147), valuesOfKey: __webpack_require__(89) }; /***/ }), /* 276 */ /***/ (function(module, exports, __webpack_require__) { var filter = __webpack_require__(88); var contains = __webpack_require__(48); /** * Flattens `array` a single level deep. * * @param {Array} arr The array to inspect. * @param {Array} values The values to exclude. * @return {Array} Returns the new array of filtered values. * @example * difference([2, 1], [2, 3]); // => [1] */ var difference = function difference(arr) { var values = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; return filter(arr, function (value) { return !contains(values, value); }); }; module.exports = difference; /***/ }), /* 277 */ /***/ (function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(13); var isPlainObject = __webpack_require__(28); var isMatch = __webpack_require__(144); function find(arr, predicate) { var _predicate = void 0; if (isFunction(predicate)) { _predicate = predicate; } if (isPlainObject(predicate)) { _predicate = function _predicate(a) { return isMatch(a, predicate); }; } if (_predicate) { for (var i = 0; i < arr.length; i += 1) { if (_predicate(arr[i])) { return arr[i]; } } } return null; } module.exports = find; /***/ }), /* 278 */ /***/ (function(module, exports, __webpack_require__) { var isNil = __webpack_require__(6); var isArray = __webpack_require__(5); var firstValue = function firstValue(data, name) { var rst = null; for (var i = 0; i < data.length; i++) { var obj = data[i]; var value = obj[name]; if (!isNil(value)) { if (isArray(value)) { rst = value[0]; } else { rst = value; } break; } } return rst; }; module.exports = firstValue; /***/ }), /* 279 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(5); var each = __webpack_require__(3); /** * Flattens `array` a single level deep. * * @param {Array} arr The array to flatten. * @return {Array} Returns the new flattened array. * @example * * flatten([1, [2, [3, [4]], 5]]); // => [1, 2, [3, [4]], 5] */ var flatten = function flatten(arr) { if (!isArray(arr)) { return arr; } var result = []; each(arr, function (item) { if (isArray(item)) { each(item, function (subItem) { result.push(subItem); }); } else { result.push(item); } }); return result; }; module.exports = flatten; /***/ }), /* 280 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(5); /** * Flattens `array` a single level deep. * * @param {Array} arr The array to flatten. * @param {Array} result The array to return. * @return {Array} Returns the new flattened array. * @example * * flattenDeep([1, [2, [3, [4]], 5]]); // => [1, 2, 3, 4, 5] */ var flattenDeep = function flattenDeep(arr) { var result = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : []; if (!isArray(arr)) { result.push(arr); } else { for (var i = 0; i < arr.length; i += 1) { flattenDeep(arr[i], result); } } return result; }; module.exports = flattenDeep; /***/ }), /* 281 */ /***/ (function(module, exports, __webpack_require__) { var filter = __webpack_require__(88); var isArray = __webpack_require__(5); var getRange = function getRange(values) { // 存在 NaN 时,min,max 判定会出问题 values = filter(values, function (v) { return !isNaN(v); }); if (!values.length) { // 如果没有数值则直接返回0 return { min: 0, max: 0 }; } if (isArray(values[0])) { var tmp = []; for (var i = 0; i < values.length; i++) { tmp = tmp.concat(values[i]); } values = tmp; } var max = Math.max.apply(null, values); var min = Math.min.apply(null, values); return { min: min, max: max }; }; module.exports = getRange; /***/ }), /* 282 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(5); var isPlainObject = __webpack_require__(28); var each = __webpack_require__(3); var reduce = function reduce(arr, fn, init) { if (!isArray(arr) && !isPlainObject(arr)) { return arr; } var result = init; each(arr, function (data, i) { result = fn(result, data, i); }); return result; }; module.exports = reduce; /***/ }), /* 283 */ /***/ (function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(15); var pullAt = __webpack_require__(146); var remove = function remove(arr, predicate) { /** * const arr = [1, 2, 3, 4] * const evens = remove(arr, n => n % 2 == 0) * console.log(arr) // => [1, 3] * console.log(evens) // => [2, 4] */ var result = []; if (!isArrayLike(arr)) { return result; } var i = -1; var indexes = []; var length = arr.length; while (++i < length) { var value = arr[i]; if (predicate(value, i, arr)) { result.push(value); indexes.push(i); } } pullAt(arr, indexes); return result; }; module.exports = remove; /***/ }), /* 284 */ /***/ (function(module, exports, __webpack_require__) { var isString = __webpack_require__(12); var isFunction = __webpack_require__(13); var isArray = __webpack_require__(5); function sortBy(arr, key) { var comparer = void 0; if (isFunction(key)) { comparer = function comparer(a, b) { return key(a) - key(b); }; } else { var keys = []; if (isString(key)) { keys.push(key); } else if (isArray(key)) { keys = key; } comparer = function comparer(a, b) { for (var i = 0; i < keys.length; i += 1) { var prop = keys[i]; if (a[prop] > b[prop]) { return 1; } if (a[prop] < b[prop]) { return -1; } } return 0; }; } arr.sort(comparer); return arr; } module.exports = sortBy; /***/ }), /* 285 */ /***/ (function(module, exports, __webpack_require__) { var each = __webpack_require__(3); var toArray = __webpack_require__(29); var uniq = __webpack_require__(147); var union = function union() { var result = []; var sources = toArray(arguments); each(sources, function (arr) { result = result.concat(arr); }); return uniq(result); }; module.exports = union; /***/ }), /* 286 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { getWrapBehavior: __webpack_require__(287), wrapBehavior: __webpack_require__(288) }; /***/ }), /* 287 */ /***/ (function(module, exports) { /** * 获取封装的事件 * @protected * @param {Object} obj 对象 * @param {String} action 事件名称 * @return {Function} 返回事件处理函数 */ function getWrapBehavior(obj, action) { return obj['_wrap_' + action]; } module.exports = getWrapBehavior; /***/ }), /* 288 */ /***/ (function(module, exports) { /** * 封装事件,便于使用上下文this,和便于解除事件时使用 * @protected * @param {Object} obj 对象 * @param {String} action 事件名称 * @return {Function} 返回事件处理函数 */ function wrapBehavior(obj, action) { if (obj['_wrap_' + action]) { return obj['_wrap_' + action]; } var method = function method(e) { obj[action](e); }; obj['_wrap_' + action] = method; return method; } module.exports = wrapBehavior; /***/ }), /* 289 */ /***/ (function(module, exports, __webpack_require__) { var number2color = __webpack_require__(290); module.exports = { number2color: number2color, numberToColor: number2color, parsePath: __webpack_require__(291), parseRadius: __webpack_require__(292) }; /***/ }), /* 290 */ /***/ (function(module, exports) { var numColorCache = {}; module.exports = function numberToColor(num) { // 增加缓存 var color = numColorCache[num]; if (!color) { var str = num.toString(16); for (var i = str.length; i < 6; i++) { str = '0' + str; } color = '#' + str; numColorCache[num] = color; } return color; }; /***/ }), /* 291 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(5); var isString = __webpack_require__(12); var each = __webpack_require__(3); var regexTags = /[MLHVQTCSAZ]([^MLHVQTCSAZ]*)/ig; var regexDot = /[^\s\,]+/ig; module.exports = function parsePath(path) { path = path || []; if (isArray(path)) { return path; } if (isString(path)) { path = path.match(regexTags); each(path, function (item, index) { item = item.match(regexDot); if (item[0].length > 1) { var tag = item[0].charAt(0); item.splice(1, 0, item[0].substr(1)); item[0] = tag; } each(item, function (sub, i) { if (!isNaN(sub)) { item[i] = +sub; } }); path[index] = item; }); return path; } }; /***/ }), /* 292 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(5); module.exports = function parseRadius(radius) { var r1 = 0, r2 = 0, r3 = 0, r4 = 0; if (isArray(radius)) { if (radius.length === 1) { r1 = r2 = r3 = r4 = radius[0]; } else if (radius.length === 2) { r1 = r3 = radius[0]; r2 = r4 = radius[1]; } else if (radius.length === 3) { r1 = radius[0]; r2 = r4 = radius[1]; r3 = radius[2]; } else { r1 = radius[0]; r2 = radius[1]; r3 = radius[2]; r4 = radius[3]; } } else { r1 = r2 = r3 = r4 = radius; } return { r1: r1, r2: r2, r3: r3, r4: r4 }; }; /***/ }), /* 293 */ /***/ (function(module, exports, __webpack_require__) { var isNumberEqual = __webpack_require__(30); module.exports = { clamp: __webpack_require__(41), fixedBase: __webpack_require__(294), isDecimal: __webpack_require__(295), isEven: __webpack_require__(296), isInteger: __webpack_require__(297), isNegative: __webpack_require__(298), isNumberEqual: isNumberEqual, isOdd: __webpack_require__(299), isPositive: __webpack_require__(300), maxBy: __webpack_require__(148), minBy: __webpack_require__(301), mod: __webpack_require__(70), snapEqual: isNumberEqual, toDegree: __webpack_require__(69), toInt: __webpack_require__(149), toInteger: __webpack_require__(149), toRadian: __webpack_require__(68) }; /***/ }), /* 294 */ /***/ (function(module, exports) { var fixedBase = function fixedBase(v, base) { var str = base.toString(); var index = str.indexOf('.'); if (index === -1) { return Math.round(v); } var length = str.substr(index + 1).length; if (length > 20) { length = 20; } return parseFloat(v.toFixed(length)); }; module.exports = fixedBase; /***/ }), /* 295 */ /***/ (function(module, exports, __webpack_require__) { var isNumber = __webpack_require__(11); var isDecimal = function isDecimal(num) { return isNumber(num) && num % 1 !== 0; }; module.exports = isDecimal; /***/ }), /* 296 */ /***/ (function(module, exports, __webpack_require__) { var isNumber = __webpack_require__(11); var isEven = function isEven(num) { return isNumber(num) && num % 2 === 0; }; module.exports = isEven; /***/ }), /* 297 */ /***/ (function(module, exports, __webpack_require__) { var isNumber = __webpack_require__(11); var isInteger = Number.isInteger ? Number.isInteger : function (num) { return isNumber(num) && num % 1 === 0; }; module.exports = isInteger; /***/ }), /* 298 */ /***/ (function(module, exports, __webpack_require__) { var isNumber = __webpack_require__(11); var isNagative = function isNagative(num) { return isNumber(num) && num < 0; }; module.exports = isNagative; /***/ }), /* 299 */ /***/ (function(module, exports, __webpack_require__) { var isNumber = __webpack_require__(11); var isOdd = function isOdd(num) { return isNumber(num) && num % 2 !== 0; }; module.exports = isOdd; /***/ }), /* 300 */ /***/ (function(module, exports, __webpack_require__) { var isNumber = __webpack_require__(11); var isPositive = function isPositive(num) { return isNumber(num) && num > 0; }; module.exports = isPositive; /***/ }), /* 301 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(5); var isFunction = __webpack_require__(13); var each = __webpack_require__(3); /** * @param {Array} arr The array to iterate over. * @param {Function} [fn] The iteratee invoked per element. * @return {*} Returns the minimum value. * @example * * var objects = [{ 'n': 1 }, { 'n': 2 }]; * * minBy(objects, function(o) { return o.n; }); * // => { 'n': 1 } * * minBy(objects, 'n'); * // => { 'n': 1 } */ var minBy = function minBy(arr, fn) { if (!isArray(arr)) { return undefined; } var min = arr[0]; var minData = void 0; if (isFunction(fn)) { minData = fn(arr[0]); } else { minData = arr[0][fn]; } var data = void 0; each(arr, function (val) { if (isFunction(fn)) { data = fn(val); } else { data = val[fn]; } if (data < minData) { min = val; minData = data; } }); return min; }; module.exports = minBy; /***/ }), /* 302 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { forIn: __webpack_require__(303), has: __webpack_require__(150), hasKey: __webpack_require__(304), hasValue: __webpack_require__(305), keys: __webpack_require__(145), isMatch: __webpack_require__(144), values: __webpack_require__(151) }; /***/ }), /* 303 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(3); /***/ }), /* 304 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(150); /***/ }), /* 305 */ /***/ (function(module, exports, __webpack_require__) { var contains = __webpack_require__(48); var values = __webpack_require__(151); module.exports = function (obj, value) { return contains(values(obj), value); }; /***/ }), /* 306 */ /***/ (function(module, exports, __webpack_require__) { var pathIntersection = __webpack_require__(307); var path2absolute = __webpack_require__(155); var path2curve = __webpack_require__(154); var catmullRom2Bezier = __webpack_require__(157); module.exports = { catmullRom2Bezier: catmullRom2Bezier, catmullRomToBezier: catmullRom2Bezier, fillPath: __webpack_require__(308), fillPathByDiff: __webpack_require__(309), formatPath: __webpack_require__(311), intersection: pathIntersection, pathIntersection: pathIntersection, parsePathArray: __webpack_require__(153), parsePathString: __webpack_require__(156), pathToAbsolute: path2absolute, path2absolute: path2absolute, pathTocurve: path2curve, path2curve: path2curve, rectPath: __webpack_require__(152) }; /***/ }), /* 307 */ /***/ (function(module, exports, __webpack_require__) { var isArray = __webpack_require__(5); var rectPath = __webpack_require__(152); var pathTocurve = __webpack_require__(154); var base3 = function base3(t, p1, p2, p3, p4) { var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4; var t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; return t * t2 - 3 * p1 + 3 * p2; }; var bezlen = function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { if (z === null) { z = 1; } z = z > 1 ? 1 : z < 0 ? 0 : z; var z2 = z / 2; var n = 12; var Tvalues = [-0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699, -0.9041, 0.9041, -0.9816, 0.9816]; var Cvalues = [0.2491, 0.2491, 0.2335, 0.2335, 0.2032, 0.2032, 0.1601, 0.1601, 0.1069, 0.1069, 0.0472, 0.0472]; var sum = 0; for (var i = 0; i < n; i++) { var ct = z2 * Tvalues[i] + z2; var xbase = base3(ct, x1, x2, x3, x4); var ybase = base3(ct, y1, y2, y3, y4); var comb = xbase * xbase + ybase * ybase; sum += Cvalues[i] * Math.sqrt(comb); } return z2 * sum; }; var curveDim = function curveDim(x0, y0, x1, y1, x2, y2, x3, y3) { var tvalues = []; var bounds = [[], []]; var a = void 0; var b = void 0; var c = void 0; var t = void 0; for (var i = 0; i < 2; ++i) { if (i === 0) { b = 6 * x0 - 12 * x1 + 6 * x2; a = -3 * x0 + 9 * x1 - 9 * x2 + 3 * x3; c = 3 * x1 - 3 * x0; } else { b = 6 * y0 - 12 * y1 + 6 * y2; a = -3 * y0 + 9 * y1 - 9 * y2 + 3 * y3; c = 3 * y1 - 3 * y0; } if (Math.abs(a) < 1e-12) { if (Math.abs(b) < 1e-12) { continue; } t = -c / b; if (t > 0 && t < 1) { tvalues.push(t); } continue; } var b2ac = b * b - 4 * c * a; var sqrtb2ac = Math.sqrt(b2ac); if (b2ac < 0) { continue; } var t1 = (-b + sqrtb2ac) / (2 * a); if (t1 > 0 && t1 < 1) { tvalues.push(t1); } var t2 = (-b - sqrtb2ac) / (2 * a); if (t2 > 0 && t2 < 1) { tvalues.push(t2); } } var j = tvalues.length; var jlen = j; var mt = void 0; while (j--) { t = tvalues[j]; mt = 1 - t; bounds[0][j] = mt * mt * mt * x0 + 3 * mt * mt * t * x1 + 3 * mt * t * t * x2 + t * t * t * x3; bounds[1][j] = mt * mt * mt * y0 + 3 * mt * mt * t * y1 + 3 * mt * t * t * y2 + t * t * t * y3; } bounds[0][jlen] = x0; bounds[1][jlen] = y0; bounds[0][jlen + 1] = x3; bounds[1][jlen + 1] = y3; bounds[0].length = bounds[1].length = jlen + 2; return { min: { x: Math.min.apply(0, bounds[0]), y: Math.min.apply(0, bounds[1]) }, max: { x: Math.max.apply(0, bounds[0]), y: Math.max.apply(0, bounds[1]) } }; }; var intersect = function intersect(x1, y1, x2, y2, x3, y3, x4, y4) { if (Math.max(x1, x2) < Math.min(x3, x4) || Math.min(x1, x2) > Math.max(x3, x4) || Math.max(y1, y2) < Math.min(y3, y4) || Math.min(y1, y2) > Math.max(y3, y4)) { return; } var nx = (x1 * y2 - y1 * x2) * (x3 - x4) - (x1 - x2) * (x3 * y4 - y3 * x4); var ny = (x1 * y2 - y1 * x2) * (y3 - y4) - (y1 - y2) * (x3 * y4 - y3 * x4); var denominator = (x1 - x2) * (y3 - y4) - (y1 - y2) * (x3 - x4); if (!denominator) { return; } var px = nx / denominator; var py = ny / denominator; var px2 = +px.toFixed(2); var py2 = +py.toFixed(2); if (px2 < +Math.min(x1, x2).toFixed(2) || px2 > +Math.max(x1, x2).toFixed(2) || px2 < +Math.min(x3, x4).toFixed(2) || px2 > +Math.max(x3, x4).toFixed(2) || py2 < +Math.min(y1, y2).toFixed(2) || py2 > +Math.max(y1, y2).toFixed(2) || py2 < +Math.min(y3, y4).toFixed(2) || py2 > +Math.max(y3, y4).toFixed(2)) { return; } return { x: px, y: py }; }; var isPointInsideBBox = function isPointInsideBBox(bbox, x, y) { return x >= bbox.x && x <= bbox.x + bbox.width && y >= bbox.y && y <= bbox.y + bbox.height; }; var box = function box(x, y, width, height) { if (x === null) { x = y = width = height = 0; } if (y === null) { y = x.y; width = x.width; height = x.height; x = x.x; } return { x: x, y: y, width: width, w: width, height: height, h: height, x2: x + width, y2: y + height, cx: x + width / 2, cy: y + height / 2, r1: Math.min(width, height) / 2, r2: Math.max(width, height) / 2, r0: Math.sqrt(width * width + height * height) / 2, path: rectPath(x, y, width, height), vb: [x, y, width, height].join(' ') }; }; var isBBoxIntersect = function isBBoxIntersect(bbox1, bbox2) { bbox1 = box(bbox1); bbox2 = box(bbox2); return isPointInsideBBox(bbox2, bbox1.x, bbox1.y) || isPointInsideBBox(bbox2, bbox1.x2, bbox1.y) || isPointInsideBBox(bbox2, bbox1.x, bbox1.y2) || isPointInsideBBox(bbox2, bbox1.x2, bbox1.y2) || isPointInsideBBox(bbox1, bbox2.x, bbox2.y) || isPointInsideBBox(bbox1, bbox2.x2, bbox2.y) || isPointInsideBBox(bbox1, bbox2.x, bbox2.y2) || isPointInsideBBox(bbox1, bbox2.x2, bbox2.y2) || (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x) && (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y); }; var bezierBBox = function bezierBBox(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y) { if (!isArray(p1x)) { p1x = [p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y]; } var bbox = curveDim.apply(null, p1x); return box(bbox.min.x, bbox.min.y, bbox.max.x - bbox.min.x, bbox.max.y - bbox.min.y); }; var findDotsAtSegment = function findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { var t1 = 1 - t; var t13 = Math.pow(t1, 3); var t12 = Math.pow(t1, 2); var t2 = t * t; var t3 = t2 * t; var x = t13 * p1x + t12 * 3 * t * c1x + t1 * 3 * t * t * c2x + t3 * p2x; var y = t13 * p1y + t12 * 3 * t * c1y + t1 * 3 * t * t * c2y + t3 * p2y; var mx = p1x + 2 * t * (c1x - p1x) + t2 * (c2x - 2 * c1x + p1x); var my = p1y + 2 * t * (c1y - p1y) + t2 * (c2y - 2 * c1y + p1y); var nx = c1x + 2 * t * (c2x - c1x) + t2 * (p2x - 2 * c2x + c1x); var ny = c1y + 2 * t * (c2y - c1y) + t2 * (p2y - 2 * c2y + c1y); var ax = t1 * p1x + t * c1x; var ay = t1 * p1y + t * c1y; var cx = t1 * c2x + t * p2x; var cy = t1 * c2y + t * p2y; var alpha = 90 - Math.atan2(mx - nx, my - ny) * 180 / Math.PI; // (mx > nx || my < ny) && (alpha += 180); return { x: x, y: y, m: { x: mx, y: my }, n: { x: nx, y: ny }, start: { x: ax, y: ay }, end: { x: cx, y: cy }, alpha: alpha }; }; var interHelper = function interHelper(bez1, bez2, justCount) { var bbox1 = bezierBBox(bez1); var bbox2 = bezierBBox(bez2); if (!isBBoxIntersect(bbox1, bbox2)) { return justCount ? 0 : []; } var l1 = bezlen.apply(0, bez1); var l2 = bezlen.apply(0, bez2); var n1 = ~~(l1 / 8); var n2 = ~~(l2 / 8); var dots1 = []; var dots2 = []; var xy = {}; var res = justCount ? 0 : []; for (var i = 0; i < n1 + 1; i++) { var d = findDotsAtSegment.apply(0, bez1.concat(i / n1)); dots1.push({ x: d.x, y: d.y, t: i / n1 }); } for (var _i = 0; _i < n2 + 1; _i++) { var _d = findDotsAtSegment.apply(0, bez2.concat(_i / n2)); dots2.push({ x: _d.x, y: _d.y, t: _i / n2 }); } for (var _i2 = 0; _i2 < n1; _i2++) { for (var j = 0; j < n2; j++) { var di = dots1[_i2]; var di1 = dots1[_i2 + 1]; var dj = dots2[j]; var dj1 = dots2[j + 1]; var ci = Math.abs(di1.x - di.x) < 0.001 ? 'y' : 'x'; var cj = Math.abs(dj1.x - dj.x) < 0.001 ? 'y' : 'x'; var is = intersect(di.x, di.y, di1.x, di1.y, dj.x, dj.y, dj1.x, dj1.y); if (is) { if (xy[is.x.toFixed(4)] === is.y.toFixed(4)) { continue; } xy[is.x.toFixed(4)] = is.y.toFixed(4); var t1 = di.t + Math.abs((is[ci] - di[ci]) / (di1[ci] - di[ci])) * (di1.t - di.t); var t2 = dj.t + Math.abs((is[cj] - dj[cj]) / (dj1[cj] - dj[cj])) * (dj1.t - dj.t); if (t1 >= 0 && t1 <= 1 && t2 >= 0 && t2 <= 1) { if (justCount) { res++; } else { res.push({ x: is.x, y: is.y, t1: t1, t2: t2 }); } } } } } return res; }; var interPathHelper = function interPathHelper(path1, path2, justCount) { path1 = pathTocurve(path1); path2 = pathTocurve(path2); var x1 = void 0; var y1 = void 0; var x2 = void 0; var y2 = void 0; var x1m = void 0; var y1m = void 0; var x2m = void 0; var y2m = void 0; var bez1 = void 0; var bez2 = void 0; var res = justCount ? 0 : []; for (var i = 0, ii = path1.length; i < ii; i++) { var pi = path1[i]; if (pi[0] === 'M') { x1 = x1m = pi[1]; y1 = y1m = pi[2]; } else { if (pi[0] === 'C') { bez1 = [x1, y1].concat(pi.slice(1)); x1 = bez1[6]; y1 = bez1[7]; } else { bez1 = [x1, y1, x1, y1, x1m, y1m, x1m, y1m]; x1 = x1m; y1 = y1m; } for (var j = 0, jj = path2.length; j < jj; j++) { var pj = path2[j]; if (pj[0] === 'M') { x2 = x2m = pj[1]; y2 = y2m = pj[2]; } else { if (pj[0] === 'C') { bez2 = [x2, y2].concat(pj.slice(1)); x2 = bez2[6]; y2 = bez2[7]; } else { bez2 = [x2, y2, x2, y2, x2m, y2m, x2m, y2m]; x2 = x2m; y2 = y2m; } var intr = interHelper(bez1, bez2, justCount); if (justCount) { res += intr; } else { for (var k = 0, kk = intr.length; k < kk; k++) { intr[k].segment1 = i; intr[k].segment2 = j; intr[k].bez1 = bez1; intr[k].bez2 = bez2; } res = res.concat(intr); } } } } } return res; }; module.exports = function pathIntersection(path1, path2) { return interPathHelper(path1, path2); }; /***/ }), /* 308 */ /***/ (function(module, exports) { function decasteljau(points, t) { var left = []; var right = []; function recurse(points, t) { if (points.length === 1) { left.push(points[0]); right.push(points[0]); } else { var middlePoints = []; for (var i = 0; i < points.length - 1; i++) { if (i === 0) { left.push(points[0]); } if (i === points.length - 2) { right.push(points[i + 1]); } middlePoints[i] = [(1 - t) * points[i][0] + t * points[i + 1][0], (1 - t) * points[i][1] + t * points[i + 1][1]]; } recurse(middlePoints, t); } } if (points.length) { recurse(points, t); } return { left: left, right: right.reverse() }; } function splitCurve(start, end, count) { var points = [[start[1], start[2]]]; count = count || 2; var segments = []; if (end[0] === 'A') { points.push(end[6]); points.push(end[7]); } else if (end[0] === 'C') { points.push([end[1], end[2]]); points.push([end[3], end[4]]); points.push([end[5], end[6]]); } else if (end[0] === 'S' || end[0] === 'Q') { points.push([end[1], end[2]]); points.push([end[3], end[4]]); } else { points.push([end[1], end[2]]); } var leftSegments = points; var t = 1 / count; for (var i = 0; i < count - 1; i++) { var rt = t / (1 - t * i); var split = decasteljau(leftSegments, rt); segments.push(split.left); leftSegments = split.right; } segments.push(leftSegments); var result = segments.map(function (segment) { var cmd = []; if (segment.length === 4) { cmd.push('C'); cmd = cmd.concat(segment[2]); } if (segment.length >= 3) { if (segment.length === 3) { cmd.push('Q'); } cmd = cmd.concat(segment[1]); } if (segment.length === 2) { cmd.push('L'); } cmd = cmd.concat(segment[segment.length - 1]); return cmd; }); return result; } function splitSegment(start, end, count) { if (count === 1) { return [[].concat(start)]; } var segments = []; if (end[0] === 'L' || end[0] === 'C' || end[0] === 'Q') { segments = segments.concat(splitCurve(start, end, count)); } else { var temp = [].concat(start); if (temp[0] === 'M') { temp[0] = 'L'; } for (var i = 0; i <= count - 1; i++) { segments.push(temp); } } return segments; } module.exports = function fillPath(source, target) { if (source.length === 1) { return source; } var sourceLen = source.length - 1; var targetLen = target.length - 1; var ratio = sourceLen / targetLen; var segmentsToFill = []; if (source.length === 1 && source[0][0] === 'M') { for (var i = 0; i < targetLen - sourceLen; i++) { source.push(source[0]); } return source; } for (var _i = 0; _i < targetLen; _i++) { var index = Math.floor(ratio * _i); segmentsToFill[index] = (segmentsToFill[index] || 0) + 1; } var filled = segmentsToFill.reduce(function (filled, count, i) { if (i === sourceLen) { return filled.concat(source[sourceLen]); } return filled.concat(splitSegment(source[i], source[i + 1], count)); }, []); filled.unshift(source[0]); if (target[targetLen] === 'Z' || target[targetLen] === 'z') { filled.push('Z'); } return filled; }; /***/ }), /* 309 */ /***/ (function(module, exports, __webpack_require__) { var isEqual = __webpack_require__(310); function getMinDiff(del, add, modify) { var type = null; var min = modify; if (add < min) { min = add; type = 'add'; } if (del < min) { min = del; type = 'del'; } return { type: type, min: min }; } /* * https://en.wikipedia.org/wiki/Levenshtein_distance * 计算两条path的编辑距离 */ var levenshteinDistance = function levenshteinDistance(source, target) { var sourceLen = source.length; var targetLen = target.length; var sourceSegment = void 0, targetSegment = void 0; var temp = 0; if (sourceLen === 0 || targetLen === 0) { return null; } var dist = []; for (var i = 0; i <= sourceLen; i++) { dist[i] = []; dist[i][0] = { min: i }; } for (var j = 0; j <= targetLen; j++) { dist[0][j] = { min: j }; } for (var _i = 1; _i <= sourceLen; _i++) { sourceSegment = source[_i - 1]; for (var _j = 1; _j <= targetLen; _j++) { targetSegment = target[_j - 1]; if (isEqual(sourceSegment, targetSegment)) { temp = 0; } else { temp = 1; } var del = dist[_i - 1][_j].min + 1; var add = dist[_i][_j - 1].min + 1; var modify = dist[_i - 1][_j - 1].min + temp; dist[_i][_j] = getMinDiff(del, add, modify); } } return dist; }; module.exports = function fillPathByDiff(source, target) { var diffMatrix = levenshteinDistance(source, target); var sourceLen = source.length; var targetLen = target.length; var changes = []; var index = 1; var minPos = 1; // 如果source和target不是完全不相等 if (diffMatrix[sourceLen][targetLen] !== sourceLen) { // 获取从source到target所需改动 for (var i = 1; i <= sourceLen; i++) { var min = diffMatrix[i][i].min; minPos = i; for (var j = index; j <= targetLen; j++) { if (diffMatrix[i][j].min < min) { min = diffMatrix[i][j].min; minPos = j; } } index = minPos; if (diffMatrix[i][index].type) { changes.push({ index: i - 1, type: diffMatrix[i][index].type }); } } // 对source进行增删path for (var _i2 = changes.length - 1; _i2 >= 0; _i2--) { index = changes[_i2].index; if (changes[_i2].type === 'add') { source.splice(index, 0, [].concat(source[index])); } else { source.splice(index, 1); } } } // source尾部补齐 sourceLen = source.length; if (sourceLen < targetLen) { for (var _i3 = 0; _i3 < targetLen - sourceLen; _i3++) { if (source[sourceLen - 1][0] === 'z' || source[sourceLen - 1][0] === 'Z') { source.splice(sourceLen - 2, 0, source[sourceLen - 2]); } else { source.push(source[sourceLen - 1]); } } } return source; }; /***/ }), /* 310 */ /***/ (function(module, exports, __webpack_require__) { var each = __webpack_require__(3); module.exports = function isEqual(obj1, obj2) { if (obj1.length !== obj2.length) { return false; } var result = true; each(obj1, function (item, i) { if (item !== obj2[i]) { result = false; return false; } }); return result; }; /***/ }), /* 311 */ /***/ (function(module, exports) { /* * 抽取pathSegment中的关键点 * M,L,A,Q,H,V一个端点 * Q, S抽取一个端点,一个控制点 * C抽取一个端点,两个控制点 */ function _getSegmentPoints(segment) { var points = []; switch (segment[0]) { case 'M': points.push([segment[1], segment[2]]); break; case 'L': points.push([segment[1], segment[2]]); break; case 'A': points.push([segment[6], segment[7]]); break; case 'Q': points.push([segment[3], segment[4]]); points.push([segment[1], segment[2]]); break; case 'T': points.push([segment[1], segment[2]]); break; case 'C': points.push([segment[5], segment[6]]); points.push([segment[1], segment[2]]); points.push([segment[3], segment[4]]); break; case 'S': points.push([segment[3], segment[4]]); points.push([segment[1], segment[2]]); break; case 'H': points.push([segment[1], segment[1]]); break; case 'V': points.push([segment[1], segment[1]]); break; default: } return points; } // 将两个点均分成count个点 function _splitPoints(points, former, count) { var result = [].concat(points); var index = void 0; var t = 1 / (count + 1); var formerEnd = _getSegmentPoints(former)[0]; for (var i = 1; i <= count; i++) { t *= i; index = Math.floor(points.length * t); if (index === 0) { result.unshift([formerEnd[0] * t + points[index][0] * (1 - t), formerEnd[1] * t + points[index][1] * (1 - t)]); } else { result.splice(index, 0, [formerEnd[0] * t + points[index][0] * (1 - t), formerEnd[1] * t + points[index][1] * (1 - t)]); } } return result; } module.exports = function formatPath(fromPath, toPath) { if (fromPath.length <= 1) { return fromPath; } var points = void 0; for (var i = 0; i < toPath.length; i++) { if (fromPath[i][0] !== toPath[i][0]) { // 获取fromPath的pathSegment的端点,根据toPath的指令对其改造 points = _getSegmentPoints(fromPath[i]); switch (toPath[i][0]) { case 'M': fromPath[i] = ['M'].concat(points[0]); break; case 'L': fromPath[i] = ['L'].concat(points[0]); break; case 'A': fromPath[i] = [].concat(toPath[i]); fromPath[i][6] = points[0][0]; fromPath[i][7] = points[0][1]; break; case 'Q': if (points.length < 2) { if (i > 0) { points = _splitPoints(points, fromPath[i - 1], 1); } else { fromPath[i] = toPath[i]; break; } } fromPath[i] = ['Q'].concat(points.reduce(function (arr, i) { return arr.concat(i); }, [])); break; case 'T': fromPath[i] = ['T'].concat(points[0]); break; case 'C': if (points.length < 3) { if (i > 0) { points = _splitPoints(points, fromPath[i - 1], 2); } else { fromPath[i] = toPath[i]; break; } } fromPath[i] = ['C'].concat(points.reduce(function (arr, i) { return arr.concat(i); }, [])); break; case 'S': if (points.length < 2) { if (i > 0) { points = _splitPoints(points, fromPath[i - 1], 1); } else { fromPath[i] = toPath[i]; break; } } fromPath[i] = ['S'].concat(points.reduce(function (arr, i) { return arr.concat(i); }, [])); break; default: fromPath[i] = toPath[i]; } } } return fromPath; }; /***/ }), /* 312 */ /***/ (function(module, exports, __webpack_require__) { var strUtil = { lc: __webpack_require__(313), lowerCase: __webpack_require__(158), lowerFirst: __webpack_require__(106), substitute: __webpack_require__(314), uc: __webpack_require__(315), upperCase: __webpack_require__(159), upperFirst: __webpack_require__(64) }; module.exports = strUtil; /***/ }), /* 313 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(158); /***/ }), /* 314 */ /***/ (function(module, exports) { var substitute = function substitute(str, o) { if (!str || !o) { return str; } return str.replace(/\\?\{([^{}]+)\}/g, function (match, name) { if (match.charAt(0) === '\\') { return match.slice(1); } return o[name] === undefined ? '' : o[name]; }); }; module.exports = substitute; /***/ }), /* 315 */ /***/ (function(module, exports, __webpack_require__) { module.exports = __webpack_require__(159); /***/ }), /* 316 */ /***/ (function(module, exports, __webpack_require__) { var isType = __webpack_require__(14); var checkType = { getType: __webpack_require__(113), isArray: __webpack_require__(5), isArrayLike: __webpack_require__(15), isBoolean: __webpack_require__(60), isFunction: __webpack_require__(13), isNil: __webpack_require__(6), isNull: __webpack_require__(317), isNumber: __webpack_require__(11), isObject: __webpack_require__(22), isObjectLike: __webpack_require__(63), isPlainObject: __webpack_require__(28), isPrototype: __webpack_require__(114), isType: isType, isUndefined: __webpack_require__(318), isString: __webpack_require__(12), isRegExp: __webpack_require__(319), isDate: __webpack_require__(111), isArguments: __webpack_require__(320), isError: __webpack_require__(321) }; module.exports = checkType; /***/ }), /* 317 */ /***/ (function(module, exports) { var isNull = function isNull(value) { return value === null; }; module.exports = isNull; /***/ }), /* 318 */ /***/ (function(module, exports) { var isUndefined = function isUndefined(value) { return value === undefined; }; module.exports = isUndefined; /***/ }), /* 319 */ /***/ (function(module, exports, __webpack_require__) { var isType = __webpack_require__(14); var isRegExp = function isRegExp(str) { return isType(str, 'RegExp'); }; module.exports = isRegExp; /***/ }), /* 320 */ /***/ (function(module, exports, __webpack_require__) { /** * 是否是参数类型 * * @param {Object} value 测试的值 * @return {Boolean} */ var isType = __webpack_require__(14); var isArguments = function isArguments(value) { return isType(value, 'Arguments'); }; module.exports = isArguments; /***/ }), /* 321 */ /***/ (function(module, exports, __webpack_require__) { /** * 是否是参数类型 * * @param {Object} value 测试的值 * @return {Boolean} */ var isType = __webpack_require__(14); var isError = function isError(value) { return isType(value, 'Error'); }; module.exports = isError; /***/ }), /* 322 */ /***/ (function(module, exports) { function debounce(func, wait, immediate) { var timeout = void 0; return function () { var context = this, args = arguments; var later = function later() { timeout = null; if (!immediate) { func.apply(context, args); } }; var callNow = immediate && !timeout; clearTimeout(timeout); timeout = setTimeout(later, wait); if (callNow) { func.apply(context, args); } }; } module.exports = debounce; /***/ }), /* 323 */ /***/ (function(module, exports, __webpack_require__) { var isArrayLike = __webpack_require__(15); var indexOf = function indexOf(arr, obj) { if (!isArrayLike(arr)) { return -1; } var m = Array.prototype.indexOf; if (m) { return m.call(arr, obj); } var index = -1; for (var i = 0; i < arr.length; i++) { if (arr[i] === obj) { index = i; break; } } return index; }; module.exports = indexOf; /***/ }), /* 324 */ /***/ (function(module, exports, __webpack_require__) { var isFunction = __webpack_require__(13); var isEqual = __webpack_require__(40); /** * @param {*} value The value to compare. * @param {*} other The other value to compare. * @param {Function} [fn] The function to customize comparisons. * @returns {boolean} Returns `true` if the values are equivalent, else `false`. * @example * * function isGreeting(value) { * return /^h(?:i|ello)$/.test(value); * } * * function customizer(objValue, othValue) { * if (isGreeting(objValue) && isGreeting(othValue)) { * return true; * } * } * * var array = ['hello', 'goodbye']; * var other = ['hi', 'goodbye']; * * isEqualWith(array, other, customizer); // => true */ var isEqualWith = function isEqualWith(value, other, fn) { if (!isFunction(fn)) { return isEqual(value, other); } return !!fn(value, other); }; module.exports = isEqualWith; /***/ }), /* 325 */ /***/ (function(module, exports, __webpack_require__) { var each = __webpack_require__(3); var isArrayLike = __webpack_require__(15); var map = function map(arr, func) { if (!isArrayLike(arr)) { return arr; } var result = []; each(arr, function (value, index) { result.push(func(value, index)); }); return result; }; module.exports = map; /***/ }), /* 326 */ /***/ (function(module, exports, __webpack_require__) { var each = __webpack_require__(3); var isPlaineObject = __webpack_require__(28); var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Creates an object composed of the picked `object` properties. * * @param {Object} object The source object. * @param {...(string|string[])} [paths] The property paths to pick. * @returns {Object} Returns the new object. * @example * * var object = { 'a': 1, 'b': '2', 'c': 3 }; * pick(object, ['a', 'c']); // => { 'a': 1, 'c': 3 } */ var pick = function pick(object, keys) { if (object === null || !isPlaineObject(object)) { return {}; } var result = {}; each(keys, function (key) { if (hasOwnProperty.call(object, key)) { result[key] = object[key]; } }); return result; }; module.exports = pick; /***/ }), /* 327 */ /***/ (function(module, exports) { function throttle(func, wait, options) { var timeout = void 0, context = void 0, args = void 0, result = void 0; var previous = 0; if (!options) options = {}; var later = function later() { previous = options.leading === false ? 0 : Date.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; var throttled = function throttled() { var now = Date.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; throttled.cancel = function () { clearTimeout(timeout); previous = 0; timeout = context = args = null; }; return throttled; } module.exports = throttle; /***/ }), /* 328 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview Default animation funciton * @author sima.zhang */ var Util = __webpack_require__(0); var G = __webpack_require__(18); var PathUtil = Util.PathUtil; function getClip(coord) { var start = coord.start; var end = coord.end; var width = coord.getWidth(); var height = coord.getHeight(); var margin = 200; var startAngle; var endAngle; var center; var radius; var clip; if (coord.isPolar) { radius = coord.getRadius(); center = coord.getCenter(); startAngle = coord.startAngle; endAngle = coord.endAngle; clip = new G.Fan({ attrs: { x: center.x, y: center.y, rs: 0, re: radius + margin, startAngle: startAngle, endAngle: startAngle } }); clip.endState = { endAngle: endAngle }; } else { clip = new G.Rect({ attrs: { x: start.x - margin, y: end.y - margin, width: coord.isTransposed ? width + margin * 2 : 0, height: coord.isTransposed ? 0 : height + margin * 2 } }); if (coord.isTransposed) { clip.endState = { height: height + margin * 2 }; } else { clip.endState = { width: width + margin * 2 }; } } clip.isClip = true; return clip; } // 获取图形的包围盒 function getPointsBox(points) { if (Util.isEmpty(points)) { return null; } var minX = points[0].x; var maxX = points[0].x; var minY = points[0].y; var maxY = points[0].y; Util.each(points, function (point) { minX = minX > point.x ? point.x : minX; maxX = maxX < point.x ? point.x : maxX; minY = minY > point.y ? point.y : minY; maxY = maxY < point.y ? point.y : maxY; }); return { minX: minX, maxX: maxX, minY: minY, maxY: maxY, centerX: (minX + maxX) / 2, centerY: (minY + maxY) / 2 }; } function getAngle(shape, coord) { var points = shape.points || shape.get('origin').points; var box = getPointsBox(points); var endAngle; var startAngle; var coordStartAngle = coord.startAngle; var coordEndAngle = coord.endAngle; var diffAngle = coordEndAngle - coordStartAngle; if (coord.isTransposed) { endAngle = box.maxY * diffAngle; startAngle = box.minY * diffAngle; } else { endAngle = box.maxX * diffAngle; startAngle = box.minX * diffAngle; } endAngle += coordStartAngle; startAngle += coordStartAngle; return { startAngle: startAngle, endAngle: endAngle }; } function getAnimateParam(animateCfg, index, id) { var result = {}; if (animateCfg.delay) { result.delay = Util.isFunction(animateCfg.delay) ? animateCfg.delay(index, id) : animateCfg.delay; } result.easing = Util.isFunction(animateCfg.easing) ? animateCfg.easing(index, id) : animateCfg.easing; result.duration = Util.isFunction(animateCfg.duration) ? animateCfg.duration(index, id) : animateCfg.duration; result.callback = animateCfg.callback; return result; } function scaleInY(shape, animateCfg) { var id = shape._id; var index = shape.get('index'); var box = shape.getBBox(); var points = shape.get('origin').points; var x = (box.minX + box.maxX) / 2; var y; if (points[0].y - points[1].y <= 0) { // 当顶点在零点之下 y = box.maxY; } else { y = box.minY; } var v = [x, y, 1]; shape.apply(v); shape.attr('transform', [['t', -x, -y], ['s', 1, 0.01], ['t', x, y]]); var endState = { transform: [['t', -x, -y], ['s', 1, 100], ['t', x, y]] }; var animateParam = getAnimateParam(animateCfg, index, id, endState); shape.animate(endState, animateParam.duration, animateParam.easing, animateParam.callback, animateParam.delay); } function scaleInX(shape, animateCfg) { var id = shape._id; var index = shape.get('index'); var box = shape.getBBox(); var points = shape.get('origin').points; var x; var y = (box.minY + box.maxY) / 2; if (points[0].y - points[1].y > 0) { // 当顶点在零点之下 x = box.maxX; } else { x = box.minX; } var v = [x, y, 1]; shape.apply(v); shape.attr({ transform: [['t', -x, -y], ['s', 0.01, 1], ['t', x, y]] }); var endState = { transform: [['t', -x, -y], ['s', 100, 1], ['t', x, y]] }; var animateParam = getAnimateParam(animateCfg, index, id, endState); shape.animate(endState, animateParam.duration, animateParam.easing, animateParam.callback, animateParam.delay); } function lineWidthOut(shape, animateCfg) { var endState = { lineWidth: 0, opacity: 0 }; var id = shape._id; var index = shape.get('index'); var animateParam = getAnimateParam(animateCfg, index, id, endState); shape.animate(endState, animateParam.duration, animateParam.easing, function () { shape.remove(); }, animateParam.delay); } function zoomIn(shape, animateCfg, coord) { var id = shape._id; var index = shape.get('index'); var x; var y; if (coord.isPolar && shape.name !== 'point') { x = coord.getCenter().x; y = coord.getCenter().y; } else { var box = shape.getBBox(); x = (box.minX + box.maxX) / 2; y = (box.minY + box.maxY) / 2; } var v = [x, y, 1]; shape.apply(v); shape.attr({ transform: [['t', -x, -y], ['s', 0.01, 0.01], ['t', x, y]] }); var endState = { transform: [['t', -x, -y], ['s', 100, 100], ['t', x, y]] }; var animateParam = getAnimateParam(animateCfg, index, id, endState); shape.animate(endState, animateParam.duration, animateParam.easing, animateParam.callback, animateParam.delay); } function zoomOut(shape, animateCfg, coord) { var id = shape._id; var index = shape.get('index'); var x; var y; if (coord.isPolar && shape.name !== 'point') { x = coord.getCenter().x; y = coord.getCenter().y; } else { var box = shape.getBBox(); x = (box.minX + box.maxX) / 2; y = (box.minY + box.maxY) / 2; } var v = [x, y, 1]; shape.apply(v); var endState = { transform: [['t', -x, -y], ['s', 0.01, 0.01], ['t', x, y]] }; var animateParam = getAnimateParam(animateCfg, index, id, endState); shape.animate(endState, animateParam.duration, animateParam.easing, function () { shape.remove(); }, animateParam.delay); } function pathIn(shape, animateCfg) { if (shape.get('type') !== 'path') return; var id = shape._id; var index = shape.get('index'); var path = PathUtil.pathToAbsolute(shape.attr('path')); shape.attr('path', [path[0]]); var endState = { path: path }; var animateParam = getAnimateParam(animateCfg, index, id, endState); shape.animate(endState, animateParam.duration, animateParam.easing, animateParam.callback, animateParam.delay); } function pathOut(shape, animateCfg) { if (shape.get('type') !== 'path') return; var id = shape._id; var index = shape.get('index'); var path = PathUtil.pathToAbsolute(shape.attr('path')); var endState = { path: [path[0]] }; var animateParam = getAnimateParam(animateCfg, index, id, endState); shape.animate(endState, animateParam.duration, animateParam.easing, function () { shape.remove(); }, animateParam.delay); } function clipIn(shape, animateCfg, coord, startAngle, endAngle) { var clip = getClip(coord); var canvas = shape.get('canvas'); var id = shape._id; var index = shape.get('index'); var endState; if (startAngle) { clip.attr('startAngle', startAngle); clip.attr('endAngle', startAngle); endState = { endAngle: endAngle }; } else { endState = clip.endState; } clip.set('canvas', canvas); shape.attr('clip', clip); shape.setSilent('animating', true); var animateParam = getAnimateParam(animateCfg, index, id, endState); clip.animate(endState, animateParam.duration, animateParam.easing, function () { if (shape && !shape.get('destroyed')) { shape.attr('clip', null); shape.setSilent('cacheShape', null); shape.setSilent('animating', false); clip.remove(); } }, animateParam.delay); } function fadeIn(shape, animateCfg) { var id = shape._id; var index = shape.get('index'); var fillOpacity = Util.isNil(shape.attr('fillOpacity')) ? 1 : shape.attr('fillOpacity'); var strokeOpacity = Util.isNil(shape.attr('strokeOpacity')) ? 1 : shape.attr('strokeOpacity'); shape.attr('fillOpacity', 0); shape.attr('strokeOpacity', 0); var endState = { fillOpacity: fillOpacity, strokeOpacity: strokeOpacity }; var animateParam = getAnimateParam(animateCfg, index, id, endState); shape.animate(endState, animateParam.duration, animateParam.easing, animateParam.callback, animateParam.delay); } function fadeOut(shape, animateCfg) { var id = shape._id; var index = shape.get('index'); var endState = { fillOpacity: 0, strokeOpacity: 0 }; var animateParam = getAnimateParam(animateCfg, index, id, endState); shape.animate(endState, animateParam.duration, animateParam.easing, function () { shape.remove(); }, animateParam.delay); } function fanIn(shape, animateCfg, coord) { var angle = getAngle(shape, coord); var endAngle = angle.endAngle; var startAngle = angle.startAngle; clipIn(shape, animateCfg, coord, startAngle, endAngle); } function lineSlideLeft(shape, animateCfg, coord) { if (shape.name !== 'line') { return; } var canvas = shape.get('canvas'); var cache = shape.get('cacheShape'); var id = shape._id; var index = shape.get('index'); var clip = new G.Rect({ attrs: { x: coord.start.x, y: coord.end.y, width: coord.getWidth(), height: coord.getHeight() } }); clip.isClip = true; clip.set('canvas', canvas); var lastPath = PathUtil.pathToAbsolute(cache.attrs.path); var updatePath = PathUtil.pathToAbsolute(shape.attr('path')); var gap = lastPath[1][1] - lastPath[0][1]; // 生成过渡Path var pathPatchPosX = lastPath[lastPath.length - 1][1] + gap; var pathPatchPosY = updatePath[updatePath.length - 1][2]; var transitionPath = lastPath.concat([['L', pathPatchPosX, pathPatchPosY]]); var v = [0, 0, 1]; shape.apply(v); shape.attr('clip', clip); shape.attr('path', transitionPath); var endState = { transform: [['t', -gap, 0]] }; var animateParam = getAnimateParam(animateCfg, index, id, endState); shape.animate(endState, animateParam.duration, animateParam.easing, function () { if (shape && !shape.get('destroyed')) { shape.attr('path', updatePath); shape.attr({ transform: [['t', gap, 0]] }); shape.attr('clip', null); shape.setSilent('cacheShape', null); clip.remove(); } }, animateParam.delay); } function areaSlideLeft(shape, animateCfg, coord) { if (shape.name !== 'area') { return; } var canvas = shape.get('canvas'); var cache = shape.get('cacheShape'); var id = shape._id; var index = shape.get('index'); var clip = new G.Rect({ attrs: { x: coord.start.x, y: coord.end.y, width: coord.getWidth(), height: coord.getHeight() } }); clip.isClip = true; clip.set('canvas', canvas); var lastPath = PathUtil.pathToAbsolute(cache.attrs.path); var updatePath = PathUtil.pathToAbsolute(shape.attr('path')); var gap = lastPath[1][1] - lastPath[0][1]; // 生成过渡Path var middleIndex = Math.floor(lastPath.length / 2); var pathPatchPosX = lastPath[middleIndex - 1][1] + gap; var pathPatchPosY = updatePath[middleIndex - 1][2]; var transitionPath = [].concat(lastPath.slice(0, middleIndex), [['L', pathPatchPosX, pathPatchPosY], ['L', pathPatchPosX, updatePath[middleIndex][2]]], lastPath.slice(middleIndex)); var v = [0, 0, 1]; shape.apply(v); shape.attr('clip', clip); shape.attr('path', transitionPath); var endState = { transform: [['t', -gap, 0]] }; var animateParam = getAnimateParam(animateCfg, index, id, endState); shape.animate(endState, animateParam.duration, animateParam.easing, function () { if (shape && !shape.get('destroyed')) { shape.attr('path', updatePath); shape.attr({ transform: [['t', gap, 0]] }); shape.attr('clip', null); shape.setSilent('cacheShape', null); clip.remove(); } }, animateParam.delay); } // 默认动画库 module.exports = { enter: { clipIn: clipIn, zoomIn: zoomIn, pathIn: pathIn, scaleInY: scaleInY, scaleInX: scaleInX, fanIn: fanIn, fadeIn: fadeIn }, leave: { lineWidthOut: lineWidthOut, zoomOut: zoomOut, pathOut: pathOut, fadeOut: fadeOut }, appear: { clipIn: clipIn, zoomIn: zoomIn, pathIn: pathIn, scaleInY: scaleInY, scaleInX: scaleInX, fanIn: fanIn, fadeIn: fadeIn }, update: { fadeIn: fadeIn, fanIn: fanIn, lineSlideLeft: lineSlideLeft, areaSlideLeft: areaSlideLeft } }; /***/ }), /* 329 */ /***/ (function(module, exports, __webpack_require__) { function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @fileOverview view * @author dxq613@gmail.com */ var Base = __webpack_require__(164); var Geom = __webpack_require__(23); var Util = __webpack_require__(0); var Controller = __webpack_require__(200); var Global = __webpack_require__(8); var Theme = __webpack_require__(167); var FIELD_ORIGIN = '_origin'; var Animate = __webpack_require__(413); function isFullCircle(coord) { var startAngle = coord.startAngle; var endAngle = coord.endAngle; if (!Util.isNil(startAngle) && !Util.isNil(endAngle) && endAngle - startAngle < Math.PI * 2) { return false; } return true; } function isBetween(value, start, end) { var tmp = (value - start) / (end - start); return tmp >= 0 && tmp <= 1; } function isPointInCoord(coord, point) { var result = false; if (coord) { var type = coord.type; if (type === 'theta') { var start = coord.start; var end = coord.end; result = isBetween(point.x, start.x, end.x) && isBetween(point.y, start.y, end.y); } else { var invertPoint = coord.invert(point); result = invertPoint.x >= 0 && invertPoint.y >= 0 && invertPoint.x <= 1 && invertPoint.y <= 1; } } return result; } var ViewGeoms = {}; Util.each(Geom, function (geomConstructor, className) { var methodName = Util.lowerFirst(className); ViewGeoms[methodName] = function (cfg) { var geom = new geomConstructor(cfg); this.addGeom(geom); return geom; }; }); /** * 图表中的视图 * @class View */ var View = /*#__PURE__*/function (_Base) { _inheritsLoose(View, _Base); var _proto = View.prototype; /** * 获取默认的配置属性 * @protected * @return {Object} 默认属性 */ _proto.getDefaultCfg = function getDefaultCfg() { return { viewContainer: null, coord: null, start: { x: 0, y: 0 }, end: { x: 1, y: 1 }, geoms: [], scales: {}, options: {}, scaleController: null, padding: 0, theme: null, parent: null, tooltipEnable: true, // 是否展示 tooltip animate: Global.animate, visible: true }; }; function View(cfg) { var _this; _this = _Base.call(this, cfg) || this; var self = _assertThisInitialized(_this); self._setTheme(); Util.each(Geom, function (GeomConstructor, className) { var methodName = Util.lowerFirst(className); self[methodName] = function (cfg) { if (cfg === void 0) { cfg = {}; } cfg.viewTheme = self.get('viewTheme'); var geom = new GeomConstructor(cfg); self.addGeom(geom); return geom; }; }); // Util.mix(this, ViewGeoms); self.init(); return _this; } _proto._setTheme = function _setTheme() { var self = this; var theme = self.get('theme'); var viewTheme = {}; var newTheme = {}; if (Util.isObject(theme)) { newTheme = theme; } else if (Util.indexOf(Object.keys(Theme), theme) !== -1) { newTheme = Theme[theme]; } Util.deepMix(viewTheme, Global, newTheme); self.set('viewTheme', viewTheme); } /** * @protected * 初始化 */ ; _proto.init = function init() { this._initViewPlot(); // 先创建容器 if (this.get('data')) { this._initData(this.get('data')); } this._initOptions(); this._initControllers(); this._bindEvents(); } // 初始化配置项 ; _proto._initOptions = function _initOptions() { var self = this; var options = Util.mix({}, self.get('options')); // 防止修改原始值 if (!options.scales) { options.scales = {}; } if (!options.coord) { options.coord = {}; } if (options.animate === false) { this.set('animate', false); } if (options.tooltip === false || Util.isNull(options.tooltip)) { // 配置项方式关闭 tooltip this.set('tooltipEnable', false); } if (options.geoms && options.geoms.length) { Util.each(options.geoms, function (geomOption) { self._createGeom(geomOption); }); } var scaleController = self.get('scaleController'); if (scaleController) { scaleController.defs = options.scales; } var coordController = self.get('coordController'); if (coordController) { coordController.reset(options.coord); } this.set('options', options); }; _proto._createGeom = function _createGeom(cfg) { var type = cfg.type; var geom; if (this[type]) { geom = this[type](); Util.each(cfg, function (v, k) { if (geom[k]) { if (Util.isObject(v) && v.field) { // 配置项传入 if (v === 'label') { geom[k](v.field, v.callback, v.cfg); } else { var _cfg; Util.each(v, function (value, key) { if (key !== 'field') { _cfg = value; } }); geom[k](v.field, _cfg); } } else { geom[k](v); } } }); } } // 初始化所有的控制器 ; _proto._initControllers = function _initControllers() { var self = this; var options = self.get('options'); var viewTheme = self.get('viewTheme'); var canvas = self.get('canvas'); var scaleController = new Controller.Scale({ viewTheme: viewTheme, defs: options.scales }); var coordController = new Controller.Coord(options.coord); this.set('scaleController', scaleController); this.set('coordController', coordController); var axisController = new Controller.Axis({ canvas: canvas, viewTheme: viewTheme }); this.set('axisController', axisController); var guideController = new Controller.Guide({ viewTheme: viewTheme, options: options.guides || [] }); this.set('guideController', guideController); }; _proto._initViewPlot = function _initViewPlot() { if (!this.get('viewContainer')) { // 用于 geom 的绘制 this.set('viewContainer', this.get('middlePlot')); } }; _proto._initGeoms = function _initGeoms() { var geoms = this.get('geoms'); var filteredData = this.get('filteredData'); var coord = this.get('coord'); var viewId = this.get('_id'); for (var i = 0; i < geoms.length; i++) { var geom = geoms[i]; geom.set('data', filteredData); geom.set('coord', coord); geom.set('_id', viewId + '-geom' + i); geom.set('keyFields', this.get('keyFields')); geom.init(); } }; _proto._clearGeoms = function _clearGeoms() { var self = this; var geoms = self.get('geoms'); for (var i = 0; i < geoms.length; i++) { var geom = geoms[i]; geom.clear(); } }; _proto._removeGeoms = function _removeGeoms() { var self = this; var geoms = self.get('geoms'); while (geoms.length > 0) { var geom = geoms.shift(); geom.destroy(); } }; _proto._drawGeoms = function _drawGeoms() { this.emit('beforedrawgeoms'); var geoms = this.get('geoms'); var coord = this.get('coord'); for (var i = 0; i < geoms.length; i++) { var geom = geoms[i]; geom.setCoord(coord); geom.paint(); } this.emit('afterdrawgeoms'); }; _proto.isShapeInView = function isShapeInView(shape) { var id = this.get('_id'); var shapeId = shape._id; if (shapeId) { return shapeId.split('-')[0] === id; } var parent = shape; while (parent) { if (parent.get('viewId') === id) { return true; } parent = parent.get('parent'); } return false; } /** * View 所在的范围 * @protected * @return {Object} View 所在的范围 */ ; _proto.getViewRegion = function getViewRegion() { var self = this; var parent = self.get('parent'); var start; var end; if (parent) { var region = parent.getViewRegion(); var viewRegion = self._getViewRegion(region.start, region.end); start = viewRegion.start; end = viewRegion.end; } else { start = self.get('start'); end = self.get('end'); } return { start: start, end: end }; } // 获取 range 所在的范围 ; _proto._getViewRegion = function _getViewRegion(plotStart, plotEnd) { var start = this.get('start'); var end = this.get('end'); var startX = start.x; var startY = 1 - end.y; var endX = end.x; var endY = 1 - start.y; var padding = this.get('padding'); // 转换成 上、右、下、左的模式 var allPadding = Util.toAllPadding(padding); var top = allPadding[0]; var right = allPadding[1]; var bottom = allPadding[2]; var left = allPadding[3]; var startPoint = { x: startX * (plotEnd.x - plotStart.x) + plotStart.x + left, y: startY * (plotEnd.y - plotStart.y) + plotStart.y - bottom }; var endPoint = { x: endX * (plotEnd.x - plotStart.x) + plotStart.x - right, y: endY * (plotEnd.y - plotStart.y) + plotStart.y + top }; return { start: startPoint, end: endPoint }; }; _proto._createCoord = function _createCoord() { var coordController = this.get('coordController'); var region = this.getViewRegion(); var coord = coordController.createCoord(region.start, region.end); this.set('coord', coord); }; _proto._renderAxes = function _renderAxes() { var options = this.get('options'); var axesOptions = options.axes; if (axesOptions === false) { // 不渲染坐标轴 return; } var axisController = this.get('axisController'); axisController.container = this.get('backPlot'); axisController.coord = this.get('coord'); axisController.options = axesOptions || {}; var xScale = this.getXScale(); var yScales = this.getYScales(); var viewId = this.get('_id'); axisController.createAxis(xScale, yScales, viewId); }; _proto._renderGuides = function _renderGuides() { var guideController = this.get('guideController'); if (!Util.isEmpty(guideController.options)) { var coord = this.get('coord'); guideController.view = this; guideController.backContainer = this.get('backPlot'); guideController.frontContainer = this.get('frontPlot'); guideController.xScales = this._getScales('x'); guideController.yScales = this._getScales('y'); guideController.render(coord); } } // 注册事件 ; _proto._bindEvents = function _bindEvents() { var eventController = new Controller.Event({ view: this, canvas: this.get('canvas') }); eventController.bindEvents(); this.set('eventController', eventController); } // 清理时间 ; _proto._clearEvents = function _clearEvents() { var eventController = this.get('eventController'); eventController && eventController.clearEvents(); }; _proto._getScales = function _getScales(dimType) { var geoms = this.get('geoms'); var result = {}; for (var i = 0; i < geoms.length; i++) { var geom = geoms[i]; var scale = dimType === 'x' ? geom.getXScale() : geom.getYScale(); if (scale && !result[scale.field]) { result[scale.field] = scale; } } return result; }; _proto._adjustScale = function _adjustScale() { this._setCatScalesRange(); var geoms = this.get('geoms'); var scaleController = this.get('scaleController'); var colDefs = scaleController.defs; for (var i = 0; i < geoms.length; i++) { var geom = geoms[i]; if (geom.get('type') === 'interval') { var yScale = geom.getYScale(); var field = yScale.field, min = yScale.min, max = yScale.max, type = yScale.type; if (!(colDefs[field] && colDefs[field].min) && type !== 'time') { if (min > 0) { yScale.change({ min: 0 }); } else if (max <= 0) { // 当柱状图全为负值时也需要从 0 开始生长 yScale.change({ max: 0 }); } } } } }; _proto._setCatScalesRange = function _setCatScalesRange() { var self = this; var coord = self.get('coord'); var viewTheme = self.get('viewTheme'); var xScale = self.getXScale(); var yScales = self.getYScales(); var scales = []; xScale && scales.push(xScale); scales = scales.concat(yScales); var inFullCircle = coord.isPolar && isFullCircle(coord); var scaleController = self.get('scaleController'); var colDefs = scaleController.defs; Util.each(scales, function (scale) { if ((scale.isCategory || scale.isIdentity) && scale.values && !(colDefs[scale.field] && colDefs[scale.field].range)) { var count = scale.values.length; var range; if (count === 1) { range = [0.5, 1]; // 只有一个分类时,防止计算出现 [0.5,0.5]的状态 } else { var widthRatio = 1; var offset = 0; if (inFullCircle) { if (!coord.isTransposed) { range = [0, 1 - 1 / count]; } else { widthRatio = viewTheme.widthRatio.multiplePie; offset = 1 / count * widthRatio; range = [offset / 2, 1 - offset / 2]; } } else { offset = 1 / count * 1 / 2; // 两边留下分类空间的一半 range = [offset, 1 - offset]; // 坐标轴最前面和最后面留下空白防止绘制柱状图时 } } scale.range = range; } }); }; _proto.getXScale = function getXScale() { var geoms = this.get('geoms'); // 如果进行过滤,那么 geom 默认隐藏时会出现不一致 // 默认隐藏时坐标轴不绘制,但是调用了 geom.show() 后,则图形显示了,坐标轴依然不见 /* .filter(function(geom) { return geom.get('visible'); }); */ var xScale = null; if (!Util.isEmpty(geoms)) { xScale = geoms[0].getXScale(); } return xScale; }; _proto.getYScales = function getYScales() { var geoms = this.get('geoms'); /* .filter(function(geom) { return geom.get('visible'); }); */ var rst = []; for (var i = 0; i < geoms.length; i++) { var geom = geoms[i]; var yScale = geom.getYScale(); if (yScale && Util.indexOf(rst, yScale) === -1) { rst.push(yScale); } } return rst; } /** * 获取数据对应在画布空间的坐标 * @param {Object} item 原始数据 * @return {Object} 返回对应的画布上的坐标点 */ ; _proto.getXY = function getXY(item) { var self = this; var coord = self.get('coord'); var xScales = self._getScales('x'); var yScales = self._getScales('y'); var x; var y; for (var field in item) { if (xScales[field]) { x = xScales[field].scale(item[field]); } if (yScales[field]) { y = yScales[field].scale(item[field]); } } if (!Util.isNil(x) && !Util.isNil(y)) { return coord.convert({ x: x, y: y }); } return null; } /** * 获取逼近的点的数据集合 * @param {Object} point 画布上的像素点 * @return {Array} 数据 */ ; _proto.getSnapRecords = function getSnapRecords(point) { var self = this; var geoms = self.get('geoms'); var rst = []; Util.each(geoms, function (geom) { var dataArray = geom.get('dataArray'); var record; Util.each(dataArray, function (data) { record = geom.findPoint(point, data); record && rst.push(record); }); }); return rst; } /** * @protected * 添加几何标记 * @param {Geom} geom 几何标记 */ ; _proto.addGeom = function addGeom(geom) { var self = this; var geoms = self.get('geoms'); geoms.push(geom); geom.set('view', self); var container = self.get('viewContainer'); geom.set('container', container); geom.set('animate', self.get('animate')); geom.bindEvents(); } /** * @protected * 移除几何标记 * @param {Geom} geom 几何标记 */ ; _proto.removeGeom = function removeGeom(geom) { var geoms = this.get('geoms'); Util.Array.remove(geoms, geom); geom.destroy(); }; _proto.createScale = function createScale(field, data) { var scales = this.get('scales'); var parent = this.get('parent'); var scale = scales[field]; // const filters = this._getFilters(); if (!data) { var filteredData = this.get('filteredData'); var legendFields = this._getFieldsForLegend(); // 过滤导致数据为空时,需要使用全局数据 // 参与过滤的字段的度量也根据全局数据来生成 if (filteredData.length && !legendFields.includes(field)) { data = filteredData; } else { data = this.get('data'); } } var scaleController = this.get('scaleController'); if (!scale) { scale = scaleController.createScale(field, data); if (scale.sync && parent) { var parentScale = parent.createScale(field, data); scale = this._getSyncScale(parentScale, scale); } scales[field] = scale; } else if (scale.sync) { // 防止 view 内部创建的scale,Chart 上的scale 范围更大 var newScale = scaleController.createScale(field, data); this._syncScale(scale, newScale); } return scale; }; _proto._getFieldsForLegend = function _getFieldsForLegend() { var fields = []; var geoms = this.get('geoms'); Util.each(geoms, function (geom) { var geomFields = geom.getFieldsForLegend(); fields = fields.concat(geomFields); }); return Util.uniq(fields); } // 如果需要同步度量,则使得 values,min,max的范围最大 ; _proto._getSyncScale = function _getSyncScale(parentScale, scale) { if (parentScale.type !== scale.type) { return scale; } this._syncScale(parentScale, scale); return parentScale; }; _proto._syncScale = function _syncScale(distScale, sourceScale) { var mergeValues = Util.union(distScale.values, sourceScale.values); if (sourceScale.isLinear) { var max = Math.max(distScale.max, sourceScale.max); var min = Math.min(distScale.min, sourceScale.min); if (distScale.max !== max || distScale.min !== min) { distScale.change({ min: min, max: max, values: mergeValues }); } } if (mergeValues.length !== distScale.values.length) { distScale.change({ values: mergeValues }); } } /** * @protected * 获取过滤后的值(需要显示的值) * @param {String} field 度量 * @return {Array.} 滤后的值 */ ; _proto.getFilteredValues = function getFilteredValues(field) { var scale = this.get('scales')[field]; var values = scale.values; var filters = this._getFilters(); var rst; if (filters && filters[field]) { rst = values.filter(filters[field]); } else { rst = values.slice(0); } return rst; } /** * @protected * 获取被过滤的值(不需显示的值) * @param {String} field 度量 * @return {Array.} 滤出的值 */ ; _proto.getFilteredOutValues = function getFilteredOutValues(field) { var scale = this.get('scales')[field]; var values = scale.values; var filters = this._getFilters(); var rst; if (filters && filters[field]) { rst = values.filter(function () { return !filters[field].apply(filters, arguments); }); } else { rst = []; } return rst; }; _proto.filter = function filter(field, condition) { var options = this.get('options'); if (!options.filters) { options.filters = {}; } options.filters[field] = condition; this.get('scaleController').filters = options.filters; } // 获取 filters ; _proto._getFilters = function _getFilters() { var options = this.get('options'); return options.filters; } // 执行 filter 数据 ; _proto.execFilter = function execFilter(data) { var self = this; var filters = self._getFilters(); if (filters) { data = data.filter(function (obj) { var rst = true; Util.each(filters, function (fn, k) { if (fn) { rst = fn(obj[k], obj); if (!rst) { return false; } } }); return rst; }); } return data; }; _proto.axis = function axis(field, cfg) { var options = this.get('options'); if (field === false) { options.axes = false; } else { if (!options.axes) { options.axes = {}; } var axisOptions = options.axes; axisOptions[field] = cfg; } return this; }; _proto.guide = function guide() { return this.get('guideController'); }; _proto._getKeyFields = function _getKeyFields(scaleDefs) { var keyFields = []; Util.each(scaleDefs, function (def, field) { if (def.key) { keyFields.push(field); } }); this.set('keyFields', keyFields); }; _proto.scale = function scale(field, cfg) { var options = this.get('options'); var scaleDefs = options.scales; if (Util.isObject(field)) { Util.mix(scaleDefs, field); } else { scaleDefs[field] = cfg; } this._getKeyFields(scaleDefs); return this; }; _proto.tooltip = function tooltip(visible) { this.set('tooltipEnable', visible); return this; }; _proto.animate = function animate(enable) { var options = this.get('options'); options.animate = enable; this.set('animate', enable); return this; }; _proto.changeOptions = function changeOptions(options) { this.set('options', options); this._initOptions(options); return this; } /** * @internal 查找包含指定点的视图 * @param {Object} point 点的位置 * @return {Array} 多个视图 */ ; _proto.getViewsByPoint = function getViewsByPoint(point) { var rst = []; var views = this.get('views'); if (isPointInCoord(this.get('coord'), point)) { rst.push(this); } Util.each(views, function (view) { if (view.get('visible') && isPointInCoord(view.get('coord'), point)) { rst.push(view); } }); return rst; } /** * 遍历所有的 shape ,用户更改 shape 后进行刷新 * @param {Function} fn 回调函数包含参数:record,shape,geom,view * @return {View} 当前视图 */ ; _proto.eachShape = function eachShape(fn) { var self = this; var views = self.get('views'); var canvas = self.get('canvas'); Util.each(views, function (view) { view.eachShape(fn); }); var geoms = this.get('geoms'); Util.each(geoms, function (geom) { var shapes = geom.getShapes(); Util.each(shapes, function (shape) { var origin = shape.get('origin'); if (Util.isArray(origin)) { var arr = origin.map(function (subOrigin) { return subOrigin[FIELD_ORIGIN]; }); fn(arr, shape, geom, self); } else { var obj = origin[FIELD_ORIGIN]; fn(obj, shape, geom, self); } }); }); canvas.draw(); return this; } /** * 遍历所有的 shape ,回调函数中 true / false 控制图形是否显示 * @param {Function} fn 回调函数包含参数:record,shape,geom,view * @return {View} 当前视图 */ ; _proto.filterShape = function filterShape(fn) { var callback = function callback(record, shape, geom, view) { if (!fn(record, shape, geom, view)) { shape.hide(); } else { shape.show(); } }; this.eachShape(callback); return this; }; _proto.clearInner = function clearInner() { this.set('scales', {}); this.emit('beforeclearinner'); var options = this.get('options'); options.geoms = null; this._clearGeoms(); // reset guide this.get('guideController') && this.get('guideController').reset(); // clear axis this.get('axisController') && this.get('axisController').clear(); this.emit('afterclearinner'); } /** * 清除视图内容,包括 geoms * @return {View} 当前视图 */ ; _proto.clear = function clear() { var options = this.get('options'); options.filters = null; this._removeGeoms(); // const container = this.get('viewContainer'); // container.clear(); this.clearInner(); this.get('guideController') && this.get('guideController').clear(); this.set('isUpdate', false); this.set('keyFields', []); return this; } /** * 设置坐标系信息 * @param {String} type 类型 * @param {Object} cfg 配置项 * @return {Object} coordController 坐标系的管理器 */ ; _proto.coord = function coord(type, cfg) { var coordController = this.get('coordController'); coordController.reset({ type: type, cfg: cfg }); return coordController; } /** * 当父元素边框发生改变时坐标系需要重新调整 * @protected */ ; _proto.resetCoord = function resetCoord() { this._createCoord(); }; _proto.source = function source(data, scales) { this._initData(data); if (scales) { this.scale(scales); } this.emit('setdata'); return this; }; _proto.changeData = function changeData(data) { this.emit('beforechangedata'); this._initData(data); this.emit('afterchangedata'); this.repaint(); return this; }; _proto._initData = function _initData(data) { var dataView = this.get('dataView'); if (dataView) { dataView.off('change', Util.getWrapBehavior(this, '_onViewChange')); this.set('dataView', null); } if (data && data.isDataView) { data.on('change', Util.wrapBehavior(this, '_onViewChange')); this.set('dataView', data); data = data.rows; } this.set('data', data); }; _proto._onViewChange = function _onViewChange() { this.emit('beforechangedata'); var dataView = this.get('dataView'); var rows = dataView.rows; this.set('data', rows); this.emit('afterchangedata'); this.repaint(); } // 初始化各个 view 和绘制辅助元素 ; _proto.beforeRender = function beforeRender() { var views = this.get('views'); // 如果存在 views 则初始化子 view 的方法 Util.each(views, function (view) { view.beforeRender(); }); this.initView(); } // 绘制坐标轴、图例、辅助元素等图表组件 ; _proto.drawComponents = function drawComponents() { var views = this.get('views'); // 如果存在 views 则初始化子 view 的方法 Util.each(views, function (view) { view.drawComponents(); }); this._renderAxes(); this._renderGuides(); } // 绘制图形 ; _proto.drawCanvas = function drawCanvas(stopDraw) { if (!stopDraw) { var views = this.get('views'); var backPlot = this.get('backPlot'); backPlot.sort(); var canvas = this.get('canvas'); var animate = this.get('animate'); if (animate) { var isUpdate = this.get('isUpdate'); Util.each(views, function (view) { Animate.execAnimation(view, isUpdate); }); Animate.execAnimation(this, isUpdate); } else { canvas.draw(); } } }; _proto.render = function render(stopDraw) { this.clearInner(); this.emit('beforerender'); this.beforeRender(); this.emit('beforepaint'); this.drawComponents(); this.paint(); this.emit('afterpaint'); this.drawCanvas(stopDraw); this.emit('afterrender'); this.set('rendered', true); return this; }; _proto.initView = function initView() { var data = this.get('data') || []; var filteredData = this.execFilter(data); this.set('filteredData', filteredData); // if (!Util.isEmpty(data)) { this._createCoord(); // draw geometry 前绘制区域可能会发生改变 this.emit('beforeinitgeoms'); this._initGeoms(); this._adjustScale(); // } }; _proto.paint = function paint() { var views = this.get('views'); // 绘制 Util.each(views, function (view) { view.paint(); }); var data = this.get('data'); if (!Util.isEmpty(data)) { this._drawGeoms(); } // 如果 view 隐藏了,隐藏所有的图形和坐标轴 if (!this.get('visible')) { this.changeVisible(false, true); // 隐藏所有的图形,但是不绘制 } }; _proto.changeVisible = function changeVisible(visible, stopDraw) { var geoms = this.get('geoms'); Util.each(geoms, function (geom) { // if (geom.get('visible')) { // geom 隐藏时不受 geom.changeVisible(visible, true); // } }); this.get('axisController') && this.get('axisController').changeVisible(visible); this.get('guideController') && this.get('guideController').changeVisible(visible); if (!stopDraw) { var canvas = this.get('canvas'); canvas.draw(); } }; _proto.repaint = function repaint() { this.set('isUpdate', true); this.clearInner(); this.render(); }; _proto.destroy = function destroy() { this._clearEvents(); var dataView = this.get('dataView'); dataView && dataView.off('change', Util.getWrapBehavior(this, '_onViewChange')); this.clear(); _Base.prototype.destroy.call(this); }; return View; }(Base); module.exports = View; /***/ }), /* 330 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var isNil = __webpack_require__(6); var isArray = __webpack_require__(5); var each = __webpack_require__(3); var Base = __webpack_require__(33); var Position = /*#__PURE__*/function (_Base) { _inheritsLoose(Position, _Base); function Position(cfg) { var _this; _this = _Base.call(this, cfg) || this; _this.names = ['x', 'y']; _this.type = 'position'; return _this; } var _proto = Position.prototype; _proto.mapping = function mapping(x, y) { var scales = this.scales; var coord = this.coord; var scaleX = scales[0]; var scaleY = scales[1]; var rstX; var rstY; var obj; if (isNil(x) || isNil(y)) { return []; } if (isArray(y) && isArray(x)) { rstX = []; rstY = []; for (var i = 0, j = 0, xLen = x.length, yLen = y.length; i < xLen && j < yLen; i++, j++) { obj = coord.convertPoint({ x: scaleX.scale(x[i]), y: scaleY.scale(y[j]) }); rstX.push(obj.x); rstY.push(obj.y); } } else if (isArray(y)) { x = scaleX.scale(x); rstY = []; each(y, function (yVal) { yVal = scaleY.scale(yVal); obj = coord.convertPoint({ x: x, y: yVal }); if (rstX && rstX !== obj.x) { if (!isArray(rstX)) { rstX = [rstX]; } rstX.push(obj.x); } else { rstX = obj.x; } rstY.push(obj.y); }); } else if (isArray(x)) { y = scaleY.scale(y); rstX = []; each(x, function (xVal) { xVal = scaleX.scale(xVal); obj = coord.convertPoint({ x: xVal, y: y }); if (rstY && rstY !== obj.y) { if (!isArray(rstY)) { rstY = [rstY]; } rstY.push(obj.y); } else { rstY = obj.y; } rstX.push(obj.x); }); } else { x = scaleX.scale(x); y = scaleY.scale(y); var point = coord.convertPoint({ x: x, y: y }); rstX = point.x; rstY = point.y; } return [rstX, rstY]; }; return Position; }(Base); module.exports = Position; /***/ }), /* 331 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var isString = __webpack_require__(12); var ColorUtil = __webpack_require__(165); var Base = __webpack_require__(33); var Color = /*#__PURE__*/function (_Base) { _inheritsLoose(Color, _Base); function Color(cfg) { var _this; _this = _Base.call(this, cfg) || this; _this.names = ['color']; _this.type = 'color'; _this.gradient = null; if (isString(_this.values)) { _this.linear = true; } return _this; } /** * @override */ var _proto = Color.prototype; _proto.getLinearValue = function getLinearValue(percent) { var gradient = this.gradient; if (!gradient) { var values = this.values; gradient = ColorUtil.gradient(values); this.gradient = gradient; } return gradient(percent); }; return Color; }(Base); module.exports = Color; /***/ }), /* 332 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var Base = __webpack_require__(33); var Shape = /*#__PURE__*/function (_Base) { _inheritsLoose(Shape, _Base); function Shape(cfg) { var _this; _this = _Base.call(this, cfg) || this; _this.names = ['shape']; _this.type = 'shape'; _this.gradient = null; return _this; } /** * @override */ var _proto = Shape.prototype; _proto.getLinearValue = function getLinearValue(percent) { var values = this.values; var index = Math.round((values.length - 1) * percent); return values[index]; }; return Shape; }(Base); module.exports = Shape; /***/ }), /* 333 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var Base = __webpack_require__(33); var Size = /*#__PURE__*/function (_Base) { _inheritsLoose(Size, _Base); function Size(cfg) { var _this; _this = _Base.call(this, cfg) || this; _this.names = ['size']; _this.type = 'size'; _this.gradient = null; return _this; } return Size; }(Base); module.exports = Size; /***/ }), /* 334 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var Base = __webpack_require__(33); var Opacity = /*#__PURE__*/function (_Base) { _inheritsLoose(Opacity, _Base); function Opacity(cfg) { var _this; _this = _Base.call(this, cfg) || this; _this.names = ['opacity']; _this.type = 'opacity'; _this.gradient = null; return _this; } return Opacity; }(Base); module.exports = Opacity; /***/ }), /* 335 */ /***/ (function(module, exports, __webpack_require__) { // 完整版下使用支持按照某个字段进行分组的 dodge var mix = __webpack_require__(10); var Adjust = __webpack_require__(34); var Dodge = __webpack_require__(336); var Stack = __webpack_require__(337); var AdjustMixin = __webpack_require__(166); var DodgeMixin = __webpack_require__(338); var StackMixin = __webpack_require__(339); mix(Adjust.prototype, AdjustMixin); mix(Dodge.prototype, AdjustMixin, DodgeMixin); mix(Stack.prototype, StackMixin); Adjust.Jitter = __webpack_require__(340); Adjust.Symmetric = __webpack_require__(341); Adjust.Dodge = Dodge; Adjust.Stack = Stack; module.exports = Adjust; /***/ }), /* 336 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var Adjust = __webpack_require__(34); var each = __webpack_require__(3); var MARGIN_RATIO = 1 / 2; var DODGE_RATIO = 1 / 2; var Dodge = /*#__PURE__*/function (_Adjust) { _inheritsLoose(Dodge, _Adjust); function Dodge() { return _Adjust.apply(this, arguments) || this; } var _proto = Dodge.prototype; _proto._initDefaultCfg = function _initDefaultCfg() { /** * 调整过程中,2个数据的间距 * @type {Number} */ this.marginRatio = MARGIN_RATIO; /** * 调整占单位宽度的比例,例如:占2个分类间距的 1/2 * @type {Number} */ this.dodgeRatio = DODGE_RATIO; this.adjustNames = ['x', 'y']; // 调整的维度,默认,x,y都做调整 }; _proto.getDodgeOffset = function getDodgeOffset(range, index, count) { var self = this; var pre = range.pre; var next = range.next; var tickLength = next - pre; var width = tickLength * self.dodgeRatio / count; var margin = self.marginRatio * width; var offset = 1 / 2 * (tickLength - count * width - (count - 1) * margin) + ((index + 1) * width + index * margin) - 1 / 2 * width - 1 / 2 * tickLength; return (pre + next) / 2 + offset; }; _proto.processAdjust = function processAdjust(dataArray) { var self = this; var count = dataArray.length; var xField = self.xField; each(dataArray, function (data, index) { for (var i = 0, len = data.length; i < len; i++) { var obj = data[i]; var value = obj[xField]; var range = { pre: len === 1 ? value - 1 : value - 0.5, next: len === 1 ? value + 1 : value + 0.5 }; var dodgeValue = self.getDodgeOffset(range, index, count); obj[xField] = dodgeValue; } }); }; return Dodge; }(Adjust); Adjust.Dodge = Dodge; module.exports = Dodge; /***/ }), /* 337 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var isArray = __webpack_require__(5); var isNil = __webpack_require__(6); var Adjust = __webpack_require__(34); var Stack = /*#__PURE__*/function (_Adjust) { _inheritsLoose(Stack, _Adjust); function Stack() { return _Adjust.apply(this, arguments) || this; } var _proto = Stack.prototype; _proto._initDefaultCfg = function _initDefaultCfg() { this.xField = null; // 调整对应的 x 方向对应的字段名称 this.yField = null; // 调整对应的 y 方向对应的字段名称 }; _proto.processAdjust = function processAdjust(dataArray) { this.processStack(dataArray); }; _proto.processStack = function processStack(dataArray) { var self = this; var xField = self.xField; var yField = self.yField; var count = dataArray.length; var stackCache = { positive: {}, negative: {} }; // 层叠顺序翻转 if (self.reverseOrder) { dataArray = dataArray.slice(0).reverse(); } for (var i = 0; i < count; i++) { var data = dataArray[i]; for (var j = 0, len = data.length; j < len; j++) { var item = data[j]; var x = item[xField] || 0; var y = item[yField]; var xkey = x.toString(); y = isArray(y) ? y[1] : y; if (!isNil(y)) { var direction = y >= 0 ? 'positive' : 'negative'; if (!stackCache[direction][xkey]) { stackCache[direction][xkey] = 0; } item[yField] = [stackCache[direction][xkey], y + stackCache[direction][xkey]]; stackCache[direction][xkey] += y; } } } }; return Stack; }(Adjust); Adjust.Stack = Stack; module.exports = Stack; /***/ }), /* 338 */ /***/ (function(module, exports, __webpack_require__) { var ArrayUtil = { merge: __webpack_require__(49), values: __webpack_require__(89) }; var group = __webpack_require__(160); var each = __webpack_require__(3); module.exports = { /** * @protected * @override */ processAdjust: function processAdjust(dataArray) { var self = this; var mergeData = ArrayUtil.merge(dataArray); var dodgeDim = self.dodgeBy; var adjDataArray = dataArray; if (dodgeDim) { // 如果指定了分组dim的字段 adjDataArray = group(mergeData, dodgeDim); } self.cacheMap = {}; self.adjDataArray = adjDataArray; self.mergeData = mergeData; self.adjustData(adjDataArray, mergeData); self.adjDataArray = null; self.mergeData = null; }, getDistribution: function getDistribution(dim) { var self = this; var dataArray = self.adjDataArray; var cacheMap = self.cacheMap; var map = cacheMap[dim]; if (!map) { map = {}; each(dataArray, function (data, index) { var values = ArrayUtil.values(data, dim); if (!values.length) { values.push(0); } each(values, function (val) { if (!map[val]) { map[val] = []; } map[val].push(index); }); }); cacheMap[dim] = map; } return map; }, adjustDim: function adjustDim(dim, values, data, frameCount, frameIndex) { var self = this; var map = self.getDistribution(dim); var groupData = self.groupData(data, dim); // 根据值分组 each(groupData, function (group, key) { key = parseFloat(key); var range; if (values.length === 1) { range = { pre: values[0] - 1, next: values[0] + 1 }; } else { range = self.getAdjustRange(dim, key, values); } each(group, function (record) { var value = record[dim]; var valueArr = map[value]; var valIndex = valueArr.indexOf(frameIndex); record[dim] = self.getDodgeOffset(range, valIndex, valueArr.length); }); }); } }; /***/ }), /* 339 */ /***/ (function(module, exports) { module.exports = { _initDefaultCfg: function _initDefaultCfg() { this.xField = null; // 调整对应的 x 方向对应的字段名称 this.yField = null; // 调整对应的 y 方向对应的字段名称 this.height = null; // 仅有一个维度调整时,总的高度 this.size = 10; // 单个点的大小 this.reverseOrder = false; // 是否反序进行层叠 this.adjustNames = ['y']; // Only support stack y }, processOneDimStack: function processOneDimStack(dataArray) { var self = this; var xField = self.xField; var yField = self.yField || 'y'; var height = self.height; var stackY = {}; // 如果层叠的顺序翻转 if (self.reverseOrder) { dataArray = dataArray.slice(0).reverse(); } for (var i = 0, len = dataArray.length; i < len; i++) { var data = dataArray[i]; // cates for (var j = 0, dataLen = data.length; j < dataLen; j++) { var item = data[j]; var size = item.size || self.size; var stackHeight = size * 2 / height; var x = item[xField]; if (!stackY[x]) { stackY[x] = stackHeight / 2; } item[yField] = stackY[x]; stackY[x] += stackHeight; } } }, processAdjust: function processAdjust(dataArray) { if (this.yField) { this.processStack(dataArray); } else { this.processOneDimStack(dataArray); } } }; /***/ }), /* 340 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var each = __webpack_require__(3); var mix = __webpack_require__(10); var ArrayUtil = { merge: __webpack_require__(49) }; var Adjust = __webpack_require__(34); var AdjustMixin = __webpack_require__(166); var Jitter = /*#__PURE__*/function (_Adjust) { _inheritsLoose(Jitter, _Adjust); function Jitter() { return _Adjust.apply(this, arguments) || this; } var _proto = Jitter.prototype; _proto._initDefaultCfg = function _initDefaultCfg() { this.xField = null; // 调整对应的 x 方向对应的字段名称 this.yField = null; // 调整对应的 y 方向对应的字段名称 this.adjustNames = ['x', 'y']; // 指x,y this.groupFields = null; // 参与分组的数据维度 }; _proto.processAdjust = function processAdjust(dataArray) { var self = this; var mergeData = ArrayUtil.merge(dataArray); self.adjDataArray = dataArray; self.mergeData = mergeData; self.adjustData(dataArray, mergeData); self.adjFrames = null; self.mergeData = null; }; _proto.getAdjustOffset = function getAdjustOffset(pre, next) { var r = Math.random(); // 随机位置,均匀分布 var avg = next - pre; // * length var append = avg * 0.05; return pre + append + avg * 0.9 * r; }; // adjust group data _proto._adjustGroup = function _adjustGroup(group, dim, key, values) { var self = this; var range = self.getAdjustRange(dim, key, values); each(group, function (record) { record[dim] = self.getAdjustOffset(range.pre, range.next); // 获取调整的位置 }); }; _proto.adjustDim = function adjustDim(dim, values, data) { var self = this; var groupData = self.groupData(data, dim); each(groupData, function (group, key) { key = parseFloat(key); self._adjustGroup(group, dim, key, values); }); }; return Jitter; }(Adjust); mix(Jitter.prototype, AdjustMixin); Adjust.Jitter = Jitter; module.exports = Jitter; /***/ }), /* 341 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; } var each = __webpack_require__(3); var maxBy = __webpack_require__(148); var isArray = __webpack_require__(5); var ArrayUtil = { merge: __webpack_require__(49) }; var Adjust = __webpack_require__(34); var Symmetric = /*#__PURE__*/function (_Adjust) { _inheritsLoose(Symmetric, _Adjust); function Symmetric() { return _Adjust.apply(this, arguments) || this; } var _proto = Symmetric.prototype; _proto._initDefaultCfg = function _initDefaultCfg() { this.xField = null; // 调整对应的 x 方向对应的字段名称 this.yField = null; // 调整对应的 y 方向对应的字段名称 this.cacheMax = null; // 缓存的最大值 this.adjustNames = ['y']; // Only support stack y this.groupFields = null; // 参与分组的数据维度 }; // 获取最大的y值 _proto._getMax = function _getMax(dim) { var self = this; var mergeData = self.mergeData; var maxRecord = maxBy(mergeData, function (obj) { var value = obj[dim]; if (isArray(value)) { return Math.max.apply(null, value); } return value; }); var maxValue = maxRecord[dim]; var max = isArray(maxValue) ? Math.max.apply(null, maxValue) : maxValue; return max; }; // 获取每个字段最大的值 _proto._getXValuesMax = function _getXValuesMax() { var self = this; var yField = self.yField; var xField = self.xField; var cache = {}; var mergeData = self.mergeData; each(mergeData, function (obj) { var xValue = obj[xField]; var yValue = obj[yField]; var max = isArray(yValue) ? Math.max.apply(null, yValue) : yValue; cache[xValue] = cache[xValue] || 0; if (cache[xValue] < max) { cache[xValue] = max; } }); return cache; }; // 入口函数 _proto.processAdjust = function processAdjust(dataArray) { var self = this; var mergeData = ArrayUtil.merge(dataArray); self.mergeData = mergeData; self._processSymmetric(dataArray); self.mergeData = null; }; // 处理对称 _proto._processSymmetric = function _processSymmetric(dataArray) { var self = this; var xField = self.xField; var yField = self.yField; var max = self._getMax(yField); var first = dataArray[0][0]; var cache; if (first && isArray(first[yField])) { cache = self._getXValuesMax(); } each(dataArray, function (data) { each(data, function (obj) { var value = obj[yField]; var offset; if (isArray(value)) { var xValue = obj[xField]; var valueMax = cache[xValue]; offset = (max - valueMax) / 2; var tmp = []; /* eslint-disable no-loop-func */ each(value, function (subVal) { // 多个字段 tmp.push(offset + subVal); }); /* eslint-enable no-loop-func */ obj[yField] = tmp; } else { offset = (max - value) / 2; obj[yField] = [offset, value + offset]; } }); }); }; return Symmetric; }(Adjust); Adjust.Symmetric = Symmetric; module.exports = Symmetric; /***/ }), /* 342 */ /***/ (function(module, exports, __webpack_require__) { var _html, _tooltip; /** * @fileOverview G2 3.0 dark theme * @author sima.zhang */ var Util = __webpack_require__(0); var BasicTheme = __webpack_require__(168); // tooltip 相关 dom 的 css 类名 var TOOLTIP_CONTAINER_CLASS = 'g2-tooltip'; var LEGEND_CONTAINER_CLASS = 'g2-legend'; var DarkTheme = Util.deepMix({}, BasicTheme, { background: { fill: '#1F1F1F', radius: 2 }, // 容器区域 plotBackground: { fill: '#1F1F1F' }, // 绘图区域 axis: { top: { label: { textStyle: { fill: '#A6A6A6' } }, line: { stroke: '#737373' }, tickLine: { stroke: '#737373' } }, bottom: { label: { textStyle: { fill: '#A6A6A6' } }, line: { stroke: '#737373' }, tickLine: { stroke: '#737373' } }, left: { label: { textStyle: { fill: '#A6A6A6' } }, grid: { lineStyle: { stroke: '#404040' } } }, right: { label: { textStyle: { fill: '#A6A6A6' } }, grid: { lineStyle: { stroke: '#404040' } } }, circle: { label: { textStyle: { fill: '#A6A6A6' } }, line: { stroke: '#737373' }, tickLine: { stroke: '#737373' }, grid: { lineStyle: { stroke: '#404040' } } }, radius: { label: { textStyle: { fill: '#A6A6A6' } }, line: { stroke: '#737373' }, tickLine: { stroke: '#737373' }, grid: { lineStyle: { stroke: '#404040' } } }, helix: { line: { stroke: '#737373' }, tickLine: { stroke: '#737373' } } }, label: { textStyle: { fill: '#A6A6A6' } }, legend: { right: { textStyle: { fill: '#737373' }, unCheckColor: '#bfbfbf' }, left: { textStyle: { fill: '#737373' }, // 图例项文本的样式 unCheckColor: '#bfbfbf' }, top: { textStyle: { fill: '#737373' }, // 图例项文本的样式 unCheckColor: '#bfbfbf' }, bottom: { textStyle: { fill: '#737373' }, // 图例项文本的样式 unCheckColor: '#bfbfbf' }, html: (_html = {}, _html["" + LEGEND_CONTAINER_CLASS] = { color: '#D9D9D9' }, _html), gradient: { textStyle: { fill: '#D9D9D9' }, lineStyle: { stroke: '#404040' } } }, tooltip: (_tooltip = {}, _tooltip["" + TOOLTIP_CONTAINER_CLASS] = { color: '#D9D9D9', backgroundColor: 'rgba(0, 0, 0, 0.5)', boxShadow: '0px 0px 2px #000' }, _tooltip), tooltipCrosshairsRect: { type: 'rect', rectStyle: { fill: '#fff', opacity: 0.1 } }, // tooltip 辅助背景框样式 tooltipCrosshairsLine: { lineStyle: { stroke: 'rgba(255, 255, 255, 0.45)' } }, guide: { line: { text: { style: { fill: '#A6A6A6' } } }, text: { style: { fill: '#A6A6A6' } }, region: { // TODO style: { lineWidth: 0, // 辅助框的边框宽度 fill: '#000', // 辅助框填充的颜色 fillOpacity: 0.04 // 辅助框的背景透明度 } // 辅助框的图形样式属性 } } }); module.exports = DarkTheme; /***/ }), /* 343 */ /***/ (function(module, exports, __webpack_require__) { var GeomLabels = __webpack_require__(91); var PolarLabels = __webpack_require__(198); var PieLabels = __webpack_require__(393); var IntervalLabels = __webpack_require__(394); var Labels = { getLabelsClass: function getLabelsClass(coordType, type) { var rst = GeomLabels; if (coordType === 'polar') { rst = PolarLabels; } else if (coordType === 'theta') { // pie chart rst = PieLabels; } else if (type === 'interval' || type === 'polygon') { // bar rst = IntervalLabels; } return rst; } }; module.exports = Labels; /***/ }), /* 344 */ /***/ (function(module, exports, __webpack_require__) { var Axis = __webpack_require__(35); Axis.Base = Axis; Axis.Circle = __webpack_require__(368); Axis.Grid = __webpack_require__(187); Axis.Helix = __webpack_require__(369); Axis.Line = __webpack_require__(370); Axis.Polyline = __webpack_require__(371); module.exports = Axis; /***/ }), /* 345 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Event = __webpack_require__(170); var Group = __webpack_require__(171); var Timeline = __webpack_require__(351); var renderers = __webpack_require__(352); var Canvas = function Canvas(cfg) { Canvas.superclass.constructor.call(this, cfg); }; Canvas.CFG = { eventEnable: true, /** * 像素宽度 * @type {Number} */ width: null, /** * 像素高度 * @type {Number} */ height: null, /** * 画布宽度 * @type {Number} */ widthCanvas: null, /** * 画布高度 * @type {Number} */ heightCanvas: null, /** * CSS宽 * @type {String} */ widthStyle: null, /** * CSS高 * @type {String} */ heightStyle: null, /** * 容器DOM * @type {Object} */ containerDOM: null, /** * 当前Canvas的DOM * @type {Object} */ canvasDOM: null, /** * 屏幕像素比 * @type {Number} */ pixelRatio: null, /** * 渲染器,默认是canvas * @type {String} */ renderer: 'canvas' }; Util.extend(Canvas, Group); Util.augment(Canvas, { init: function init() { Canvas.superclass.init.call(this); this._setGlobalParam(); this._setContainer(); this._initPainter(); this._scale(); if (this.get('eventEnable')) { this._registEvents(); } }, getEmitter: function getEmitter(element, event) { if (element) { if (Util.isEmpty(element._getEvents())) { var parent = element.get('parent'); if (parent && !event.propagationStopped) { return this.getEmitter(parent, event); } } else { return element; } } }, _getEventObj: function _getEventObj(type, e, point, target) { var event = new Event(type, e, true, true); event.x = point.x; event.y = point.y; event.clientX = e.clientX; event.clientY = e.clientY; event.currentTarget = target; event.target = target; return event; }, _triggerEvent: function _triggerEvent(type, e) { var point = this.getPointByClient(e.clientX, e.clientY); var shape = this.getShape(point.x, point.y, e); var el = this.get('el'); var emitObj; if (type === 'mousemove') { var preShape = this.get('preShape'); if (preShape && preShape !== shape) { var mouseleave = this._getEventObj('mouseleave', e, point, preShape); emitObj = this.getEmitter(preShape, e); emitObj && emitObj.emit('mouseleave', mouseleave); el.style.cursor = 'default'; } if (shape) { var mousemove = this._getEventObj('mousemove', e, point, shape); emitObj = this.getEmitter(shape, e); emitObj && emitObj.emit('mousemove', mousemove); if (preShape !== shape) { var mouseenter = this._getEventObj('mouseenter', e, point, shape); emitObj && emitObj.emit('mouseenter', mouseenter, e); } } else { var canvasmousemove = this._getEventObj('mousemove', e, point, this); this.emit('mousemove', canvasmousemove); } this.set('preShape', shape); } else { var event = this._getEventObj(type, e, point, shape || this); emitObj = this.getEmitter(shape, e); if (emitObj && emitObj !== this) { emitObj.emit(type, event); } this.emit(type, event); } if (shape && !shape.get('destroyed')) { el.style.cursor = shape.attr('cursor') || 'default'; } }, _registEvents: function _registEvents() { var self = this; var el = self.get('el'); var events = ['mouseout', 'mouseover', 'mousemove', 'mousedown', 'mouseleave', 'mouseup', 'click', 'dblclick']; Util.each(events, function (event) { el.addEventListener(event, function (e) { self._triggerEvent(event, e); }, false); }); // special cases el.addEventListener('touchstart', function (e) { if (!Util.isEmpty(e.touches)) { self._triggerEvent('touchstart', e.touches[0]); } }, false); el.addEventListener('touchmove', function (e) { if (!Util.isEmpty(e.touches)) { self._triggerEvent('touchmove', e.touches[0]); } }, false); el.addEventListener('touchend', function (e) { if (!Util.isEmpty(e.changedTouches)) { self._triggerEvent('touchend', e.changedTouches[0]); } }, false); }, _scale: function _scale() { var pixelRatio = this.get('pixelRatio'); this.scale(pixelRatio, pixelRatio); }, _setGlobalParam: function _setGlobalParam() { var pixelRatio = this.get('pixelRatio'); if (!pixelRatio) { this.set('pixelRatio', Util.getRatio()); } var renderer = renderers[this.get('renderer') || 'canvas']; this._cfg.renderer = renderer; this._cfg.canvas = this; var timeline = new Timeline(this); this._cfg.timeline = timeline; }, _setContainer: function _setContainer() { var containerId = this.get('containerId'); var containerDOM = this.get('containerDOM'); if (!containerDOM) { containerDOM = document.getElementById(containerId); this.set('containerDOM', containerDOM); } Util.modifyCSS(containerDOM, { position: 'relative' }); }, _initPainter: function _initPainter() { var containerDOM = this.get('containerDOM'); var painter = new this._cfg.renderer.painter(containerDOM); this._cfg.painter = painter; this._cfg.canvasDOM = this._cfg.el = painter.canvas; this.changeSize(this.get('width'), this.get('height')); }, _resize: function _resize() { var canvasDOM = this.get('canvasDOM'); var widthCanvas = this.get('widthCanvas'); var heightCanvas = this.get('heightCanvas'); var widthStyle = this.get('widthStyle'); var heightStyle = this.get('heightStyle'); canvasDOM.style.width = widthStyle; canvasDOM.style.height = heightStyle; canvasDOM.setAttribute('width', widthCanvas); canvasDOM.setAttribute('height', heightCanvas); }, getWidth: function getWidth() { var pixelRatio = this.get('pixelRatio'); var width = this.get('width'); return width * pixelRatio; }, getHeight: function getHeight() { var pixelRatio = this.get('pixelRatio'); var height = this.get('height'); return height * pixelRatio; }, changeSize: function changeSize(width, height) { var pixelRatio = this.get('pixelRatio'); var widthCanvas = width * pixelRatio; var heightCanvas = height * pixelRatio; this.set('widthCanvas', widthCanvas); this.set('heightCanvas', heightCanvas); this.set('widthStyle', width + 'px'); this.set('heightStyle', height + 'px'); this.set('width', width); this.set('height', height); this._resize(); }, /** * 将窗口坐标转变成 canvas 坐标 * @param {Number} clientX 窗口x坐标 * @param {Number} clientY 窗口y坐标 * @return {Object} canvas坐标 */ getPointByClient: function getPointByClient(clientX, clientY) { var el = this.get('el'); var pixelRatio = this.get('pixelRatio') || 1; var bbox = el.getBoundingClientRect(); return { x: (clientX - bbox.left) * pixelRatio, y: (clientY - bbox.top) * pixelRatio }; }, getClientByPoint: function getClientByPoint(x, y) { var el = this.get('el'); var bbox = el.getBoundingClientRect(); var pixelRatio = this.get('pixelRatio') || 1; return { clientX: x / pixelRatio + bbox.left, clientY: y / pixelRatio + bbox.top }; }, draw: function draw() { this._cfg.painter.draw(this); }, getShape: function getShape(x, y, e) { if (arguments.length === 3 && this._cfg.renderer.getShape) { return this._cfg.renderer.getShape.call(this, x, y, e); } return Canvas.superclass.getShape.call(this, x, y); }, _drawSync: function _drawSync() { this._cfg.painter.drawSync(this); }, destroy: function destroy() { var cfg = this._cfg; var containerDOM = cfg.containerDOM; var canvasDOM = cfg.canvasDOM; if (canvasDOM && containerDOM) { containerDOM.removeChild(canvasDOM); } cfg.timeline.stop(); Canvas.superclass.destroy.call(this); } }); module.exports = Canvas; /***/ }), /* 346 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); module.exports = { canFill: false, canStroke: false, initAttrs: function initAttrs(attrs) { this._attrs = { opacity: 1, fillOpacity: 1, strokeOpacity: 1, matrix: [1, 0, 0, 0, 1, 0, 0, 0, 1] }; this.attr(Util.assign(this.getDefaultAttrs(), attrs)); return this; }, getDefaultAttrs: function getDefaultAttrs() { return {}; }, /** * 设置或者设置属性,有以下 4 种情形: * - name 不存在, 则返回属性集合 * - name 为字符串,value 为空,获取属性值 * - name 为字符串,value 不为空,设置属性值,返回 this * - name 为键值对,value 为空,设置属性值 * * @param {String | Object} name 属性名 * @param {*} value 属性值 * @return {*} 属性值 */ attr: function attr(name, value) { var self = this; if (arguments.length === 0) { return self._attrs; } if (Util.isObject(name)) { // self._attrs = Util.deepMix(self._attrs, name); for (var k in name) { this._setAttr(k, name[k]); } self.clearBBox(); this._cfg.hasUpdate = true; return self; } if (arguments.length === 2) { this._setAttr(name, value); self.clearBBox(); this._cfg.hasUpdate = true; return self; } return self._attrs[name]; }, _setAttr: function _setAttr(name, value) { var self = this; var attrs = this._attrs; attrs[name] = value; if (name === 'fill' || name === 'stroke') { attrs[name + 'Style'] = value; return; } if (name === 'opacity') { attrs.globalAlpha = value; return; } if (name === 'clip' && value) { self._setClip(value); return; } if (name === 'path' && self._afterSetAttrPath) { self._afterSetAttrPath(value); return; } if (name === 'transform') { self.transform(value); return; } if (name === 'rotate') { self.rotateAtStart(value); } }, clearBBox: function clearBBox() { this.setSilent('box', null); }, hasFill: function hasFill() { return this.canFill && this._attrs.fillStyle; }, hasStroke: function hasStroke() { return this.canStroke && this._attrs.strokeStyle; }, _setClip: function _setClip(item) { item._cfg.renderer = this._cfg.renderer; item._cfg.canvas = this._cfg.canvas; item._cfg.parent = this._cfg.parent; item.hasFill = function () { return true; }; } }; /***/ }), /* 347 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); // 是否未改变 function isUnchanged(m) { return m[0] === 1 && m[1] === 0 && m[3] === 0 && m[4] === 1 && m[6] === 0 && m[7] === 0; } // 是否仅仅是scale function isScale(m) { return m[1] === 0 && m[3] === 0 && m[6] === 0 && m[7] === 0; } function multiple(m1, m2) { if (!isUnchanged(m2)) { if (isScale(m2)) { m1[0] *= m2[0]; m1[4] *= m2[4]; } else { Util.mat3.multiply(m1, m1, m2); } } } module.exports = { initTransform: function initTransform() {}, resetMatrix: function resetMatrix() { this.attr('matrix', [1, 0, 0, 0, 1, 0, 0, 0, 1]); }, translate: function translate(tx, ty) { var matrix = this._attrs.matrix; Util.mat3.translate(matrix, matrix, [tx, ty]); this.clearTotalMatrix(); this.attr('matrix', matrix); return this; }, rotate: function rotate(radian) { var matrix = this._attrs.matrix; Util.mat3.rotate(matrix, matrix, radian); this.clearTotalMatrix(); this.attr('matrix', matrix); return this; }, scale: function scale(s1, s2) { var matrix = this._attrs.matrix; Util.mat3.scale(matrix, matrix, [s1, s2]); this.clearTotalMatrix(); this.attr('matrix', matrix); return this; }, rotateAtStart: function rotateAtStart(rotate) { var x = this._attrs.x || this._cfg.attrs.x; var y = this._attrs.y || this._cfg.attrs.y; if (Math.abs(rotate) > Math.PI * 2) { rotate = rotate / 180 * Math.PI; } return this.transform([['t', -x, -y], ['r', rotate], ['t', x, y]]); }, move: function move(x, y) { var cx = this.get('x') || 0; // 当前的x var cy = this.get('y') || 0; // 当前的y this.translate(x - cx, y - cy); this.set('x', x); this.set('y', y); return this; }, transform: function transform(ts) { var self = this; var matrix = this._attrs.matrix; Util.each(ts, function (t) { switch (t[0]) { case 't': self.translate(t[1], t[2]); break; case 's': self.scale(t[1], t[2]); break; case 'r': self.rotate(t[1]); break; case 'm': self.attr('matrix', Util.mat3.multiply([], matrix, t[1])); self.clearTotalMatrix(); break; default: break; } }); return self; }, setTransform: function setTransform(ts) { this.attr('matrix', [1, 0, 0, 0, 1, 0, 0, 0, 1]); return this.transform(ts); }, getMatrix: function getMatrix() { return this.attr('matrix'); }, setMatrix: function setMatrix(m) { this.attr('matrix', m); this.clearTotalMatrix(); return this; }, apply: function apply(v, root) { var m; if (root) { m = this._getMatrixByRoot(root); } else { m = this.attr('matrix'); } Util.vec3.transformMat3(v, v, m); return this; }, // 获取到达指定根节点的矩阵 _getMatrixByRoot: function _getMatrixByRoot(root) { var self = this; root = root || self; var parent = self; var parents = []; while (parent !== root) { parents.unshift(parent); parent = parent.get('parent'); } parents.unshift(parent); var m = [1, 0, 0, 0, 1, 0, 0, 0, 1]; Util.each(parents, function (child) { Util.mat3.multiply(m, child.attr('matrix'), m); }); return m; }, /** * 应用到当前元素上的总的矩阵 * @return {Matrix} 矩阵 */ getTotalMatrix: function getTotalMatrix() { var m = this._cfg.totalMatrix; if (!m) { m = [1, 0, 0, 0, 1, 0, 0, 0, 1]; var parent = this._cfg.parent; if (parent) { var pm = parent.getTotalMatrix(); multiple(m, pm); } multiple(m, this.attr('matrix')); this._cfg.totalMatrix = m; } return m; }, // 清除当前的矩阵 clearTotalMatrix: function clearTotalMatrix() {// this._cfg.totalMatrix = null; }, invert: function invert(v) { var m = this.getTotalMatrix(); // 单精屏幕下大多数矩阵没变化 if (isScale(m)) { v[0] /= m[0]; v[1] /= m[4]; } else { var inm = Util.mat3.invert([], m); if (inm) { Util.vec3.transformMat3(v, v, inm); } } return this; }, resetTransform: function resetTransform(context) { var mo = this.attr('matrix'); // 不改变时 if (!isUnchanged(mo)) { context.transform(mo[0], mo[1], mo[3], mo[4], mo[6], mo[7]); } } }; /***/ }), /* 348 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var ReservedProps = { delay: 'delay', rotate: 'rotate' }; var colorRalaredProps = { fill: 'fill', stroke: 'stroke', fillStyle: 'fillStyle', strokeStyle: 'strokeStyle' }; function getFromAttrs(toAttrs, shape) { var rst = {}; var attrs = shape._attrs; for (var k in toAttrs.attrs) { rst[k] = attrs[k]; } return rst; } function getFormatProps(props, shape) { var rst = { matrix: null, attrs: {} }; var attrs = shape._attrs; for (var k in props) { if (k === 'transform') { rst.matrix = Util.transform(shape.getMatrix(), props[k]); } else if (k === 'rotate') { rst.matrix = Util.transform(shape.getMatrix(), [['r', props[k]]]); } else if (k === 'matrix') { rst.matrix = props[k]; } else if (colorRalaredProps[k] && /^[r,R,L,l]{1}[\s]*\(/.test(props[k])) { // 渐变色不支持动画 continue; } else if (!ReservedProps[k] && attrs[k] !== props[k]) { rst.attrs[k] = props[k]; } } return rst; } function checkExistedAttrs(animators, animator) { var delay = animator.delay; var hasOwnProperty = Object.prototype.hasOwnProperty; Util.each(animator.toAttrs, function (v, k) { Util.each(animators, function (animator) { if (delay < animator.startTime + animator.duration) { if (hasOwnProperty.call(animator.toAttrs, k)) { delete animator.toAttrs[k]; delete animator.fromAttrs[k]; } } }); }); if (animator.toMatrix) { Util.each(animators, function (animator) { if (delay < animator.startTime + animator.duration && animator.toMatrix) { delete animator.toMatrix; } }); } return animators; } module.exports = { /** * 执行动画 * @param {Object} toProps 动画最终状态 * @param {Number} duration 动画执行时间 * @param {String} easing 动画缓动效果 * @param {Function} callback 动画执行后的回调 * @param {Number} delay 动画延迟时间 */ animate: function animate(toProps, duration, easing, callback, delay) { if (delay === void 0) { delay = 0; } var self = this; self.set('animating', true); var timeline = self.get('timeline'); if (!timeline) { timeline = self.get('canvas').get('timeline'); self.setSilent('timeline', timeline); } var animators = self.get('animators') || []; // 初始化tick if (!timeline._timer) { timeline.initTimer(); } if (Util.isNumber(callback)) { delay = callback; callback = null; } if (Util.isFunction(easing)) { callback = easing; easing = 'easeLinear'; } else { easing = easing ? easing : 'easeLinear'; } var formatProps = getFormatProps(toProps, self); // 记录动画属性 var animator = { fromAttrs: getFromAttrs(formatProps, self), toAttrs: formatProps.attrs, fromMatrix: Util.clone(self.getMatrix()), toMatrix: formatProps.matrix, duration: duration, easing: easing, callback: callback, delay: delay, startTime: timeline.getTime(), id: Util.uniqueId() }; // 如果动画队列中已经有这个图形了 if (animators.length > 0) { // 先检查是否需要合并属性。若有相同的动画,将该属性从前一个动画中删除,直接用后一个动画中 animators = checkExistedAttrs(animators, animator); } else { // 否则将图形添加到队列 timeline.addAnimator(self); } animators.push(animator); self.setSilent('animators', animators); self.setSilent('pause', { isPaused: false }); }, stopAnimate: function stopAnimate() { var _this = this; var animators = this.get('animators'); // 将动画执行到最后一帧,执行回调 Util.each(animators, function (animator) { _this.attr(animator.toAttrs); if (animator.toMatrix) { _this.attr('matrix', animator.toMatrix); } if (animator.callback) { animator.callback(); } }); this.setSilent('animating', false); this.setSilent('animators', []); }, pauseAnimate: function pauseAnimate() { var self = this; var timeline = self.get('timeline'); // 记录下是在什么时候暂停的 self.setSilent('pause', { isPaused: true, pauseTime: timeline.getTime() }); return self; }, resumeAnimate: function resumeAnimate() { var self = this; var timeline = self.get('timeline'); var current = timeline.getTime(); var animators = self.get('animators'); var pauseTime = self.get('pause').pauseTime; // 之后更新属性需要计算动画已经执行的时长,如果暂停了,就把初始时间调后 Util.each(animators, function (animator) { animator.startTime = animator.startTime + (current - pauseTime); animator._paused = false; animator._pauseTime = null; }); self.setSilent('pause', { isPaused: false }); self.setSilent('animators', animators); return self; } }; /***/ }), /* 349 */ /***/ (function(module, exports, __webpack_require__) { var Shape = __webpack_require__(9); Shape.Arc = __webpack_require__(175); Shape.Circle = __webpack_require__(176); Shape.Dom = __webpack_require__(177); Shape.Ellipse = __webpack_require__(178); Shape.Fan = __webpack_require__(179); Shape.Image = __webpack_require__(180); Shape.Line = __webpack_require__(181); Shape.Marker = __webpack_require__(95); Shape.Path = __webpack_require__(182); Shape.Polygon = __webpack_require__(183); Shape.Polyline = __webpack_require__(184); Shape.Rect = __webpack_require__(185); Shape.Text = __webpack_require__(186); module.exports = Shape; /***/ }), /* 350 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var Inside = __webpack_require__(93); var mathUtl = { arc: __webpack_require__(53), ellipse: __webpack_require__(174), line: __webpack_require__(52) }; var canvas = Util.createDom(''); var context = canvas.getContext('2d'); function isPointInPathByContext(x, y, ctx) { ctx.createPath(context); return context.isPointInPath(x, y); } var arc = function arc(x, y) { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var r = attrs.r, startAngle = attrs.startAngle, endAngle = attrs.endAngle, clockwise = attrs.clockwise; var lineWidth = this.getHitLineWidth(); if (this.hasStroke()) { return Inside.arcline(cx, cy, r, startAngle, endAngle, clockwise, lineWidth, x, y); } return false; }; var circle = function circle(x, y) { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var r = attrs.r; var lineWidth = this.getHitLineWidth(); var fill = this.hasFill(); var stroke = this.hasStroke(); if (fill && stroke) { return Inside.circle(cx, cy, r, x, y) || Inside.arcline(cx, cy, r, 0, Math.PI * 2, false, lineWidth, x, y); } if (fill) { return Inside.circle(cx, cy, r, x, y); } if (stroke) { return Inside.arcline(cx, cy, r, 0, Math.PI * 2, false, lineWidth, x, y); } return false; }; var ellipse = function ellipse(x, y) { var attrs = this._attrs; var fill = this.hasFill(); var stroke = this.hasStroke(); var cx = attrs.x; var cy = attrs.y; var rx = attrs.rx; var ry = attrs.ry; var lineWidth = this.getHitLineWidth(); var r = rx > ry ? rx : ry; var scaleX = rx > ry ? 1 : rx / ry; var scaleY = rx > ry ? ry / rx : 1; var p = [x, y, 1]; var m = [1, 0, 0, 0, 1, 0, 0, 0, 1]; Util.mat3.scale(m, m, [scaleX, scaleY]); Util.mat3.translate(m, m, [cx, cy]); var inm = Util.mat3.invert([], m); Util.vec3.transformMat3(p, p, inm); if (fill && stroke) { return Inside.circle(0, 0, r, p[0], p[1]) || Inside.arcline(0, 0, r, 0, Math.PI * 2, false, lineWidth, p[0], p[1]); } if (fill) { return Inside.circle(0, 0, r, p[0], p[1]); } if (stroke) { return Inside.arcline(0, 0, r, 0, Math.PI * 2, false, lineWidth, p[0], p[1]); } return false; }; var fan = function fan(x, y) { var self = this; var fill = self.hasFill(); var stroke = self.hasStroke(); var attrs = self._attrs; var cx = attrs.x; var cy = attrs.y; var rs = attrs.rs; var re = attrs.re; var startAngle = attrs.startAngle; var endAngle = attrs.endAngle; var clockwise = attrs.clockwise; var v1 = [1, 0]; var subv = [x - cx, y - cy]; var angle = Util.vec2.angleTo(v1, subv); function _isPointInFill() { var angle1 = mathUtl.arc.nearAngle(angle, startAngle, endAngle, clockwise); if (Util.isNumberEqual(angle, angle1)) { var ls = Util.vec2.squaredLength(subv); if (rs * rs <= ls && ls <= re * re) { return true; } } return false; } function _isPointInStroke() { var lineWidth = self.getHitLineWidth(); var ssp = { x: Math.cos(startAngle) * rs + cx, y: Math.sin(startAngle) * rs + cy }; var sep = { x: Math.cos(startAngle) * re + cx, y: Math.sin(startAngle) * re + cy }; var esp = { x: Math.cos(endAngle) * rs + cx, y: Math.sin(endAngle) * rs + cy }; var eep = { x: Math.cos(endAngle) * re + cx, y: Math.sin(endAngle) * re + cy }; if (Inside.line(ssp.x, ssp.y, sep.x, sep.y, lineWidth, x, y)) { return true; } if (Inside.line(esp.x, esp.y, eep.x, eep.y, lineWidth, x, y)) { return true; } if (Inside.arcline(cx, cy, rs, startAngle, endAngle, clockwise, lineWidth, x, y)) { return true; } if (Inside.arcline(cx, cy, re, startAngle, endAngle, clockwise, lineWidth, x, y)) { return true; } return false; } if (fill && stroke) { return _isPointInFill() || _isPointInStroke(); } if (fill) { return _isPointInFill(); } if (stroke) { return _isPointInStroke(); } return false; }; var image = function image(x, y) { var attrs = this._attrs; if (this.get('toDraw') || !attrs.img) { return false; } if (!this._cfg.attrs || this._cfg.attrs.img !== attrs.img) { this._setAttrImg(); } var rx = attrs.x; var ry = attrs.y; var width = attrs.width; var height = attrs.height; return Inside.rect(rx, ry, width, height, x, y); }; var line = function line(x, y) { var attrs = this._attrs; var x1 = attrs.x1, y1 = attrs.y1, x2 = attrs.x2, y2 = attrs.y2; var lineWidth = this.getHitLineWidth(); if (this.hasStroke()) { return Inside.line(x1, y1, x2, y2, lineWidth, x, y); } return false; }; var path = function path(x, y) { var self = this; var segments = self.get('segments'); var fill = self.hasFill(); var stroke = self.hasStroke(); function _isPointInStroke() { if (!Util.isEmpty(segments)) { var lineWidth = self.getHitLineWidth(); for (var i = 0, l = segments.length; i < l; i++) { if (segments[i].isInside(x, y, lineWidth)) { return true; } } return false; } } if (fill && stroke) { return isPointInPathByContext(x, y, self) || _isPointInStroke(); } if (fill) { return isPointInPathByContext(x, y, self); } if (stroke) { return _isPointInStroke(); } return false; }; var polygon = function polygon(x, y) { var self = this; var fill = self.hasFill(); var stroke = self.hasStroke(); function _isPointInStroke() { var attrs = self._attrs; var points = attrs.points; if (points.length < 2) { return false; } var lineWidth = self.getHitLineWidth(); var outPoints = points.slice(0); if (points.length >= 3) { outPoints.push(points[0]); } return Inside.polyline(outPoints, lineWidth, x, y); } if (fill && stroke) { return isPointInPathByContext(x, y, self) || _isPointInStroke(); } if (fill) { return isPointInPathByContext(x, y, self); } if (stroke) { return _isPointInStroke(); } return false; }; var marker = function marker(x, y) { var attrs = this._attrs; var cx = attrs.x; var cy = attrs.y; var r = attrs.radius || attrs.r; var lineWidth = this.getHitLineWidth(); return Inside.circle(cx, cy, r + lineWidth / 2, x, y); }; var polyline = function polyline(x, y) { var self = this; var attrs = self._attrs; if (self.hasStroke()) { var points = attrs.points; if (points.length < 2) { return false; } var lineWidth = attrs.lineWidth; return Inside.polyline(points, lineWidth, x, y); } return false; }; var rect = function rect(x, y) { var self = this; var fill = self.hasFill(); var stroke = self.hasStroke(); function _isPointInStroke() { var attrs = self._attrs; var rx = attrs.x; var ry = attrs.y; var width = attrs.width; var height = attrs.height; var radius = attrs.radius; var lineWidth = self.getHitLineWidth(); if (radius === 0) { var halfWidth = lineWidth / 2; return Inside.line(rx - halfWidth, ry, rx + width + halfWidth, ry, lineWidth, x, y) || Inside.line(rx + width, ry - halfWidth, rx + width, ry + height + halfWidth, lineWidth, x, y) || Inside.line(rx + width + halfWidth, ry + height, rx - halfWidth, ry + height, lineWidth, x, y) || Inside.line(rx, ry + height + halfWidth, rx, ry - halfWidth, lineWidth, x, y); } return Inside.line(rx + radius, ry, rx + width - radius, ry, lineWidth, x, y) || Inside.line(rx + width, ry + radius, rx + width, ry + height - radius, lineWidth, x, y) || Inside.line(rx + width - radius, ry + height, rx + radius, ry + height, lineWidth, x, y) || Inside.line(rx, ry + height - radius, rx, ry + radius, lineWidth, x, y) || Inside.arcline(rx + width - radius, ry + radius, radius, 1.5 * Math.PI, 2 * Math.PI, false, lineWidth, x, y) || Inside.arcline(rx + width - radius, ry + height - radius, radius, 0, 0.5 * Math.PI, false, lineWidth, x, y) || Inside.arcline(rx + radius, ry + height - radius, radius, 0.5 * Math.PI, Math.PI, false, lineWidth, x, y) || Inside.arcline(rx + radius, ry + radius, radius, Math.PI, 1.5 * Math.PI, false, lineWidth, x, y); } if (fill && stroke) { return isPointInPathByContext(x, y, self) || _isPointInStroke(); } if (fill) { return isPointInPathByContext(x, y, self); } if (stroke) { return _isPointInStroke(); } return false; }; var text = function text(x, y) { var self = this; var box = self.getBBox(); if (self.hasFill() || self.hasStroke()) { return Inside.box(box.minX, box.maxX, box.minY, box.maxY, x, y); } }; var dom = function dom(x, y) { if (!this._cfg.el) { return false; } var box = this._cfg.el.getBBox(); return Inside.box(box.x, box.x + box.width, box.y, box.y + box.height, x, y); }; var shapes = { arc: arc, circle: circle, dom: dom, ellipse: ellipse, fan: fan, image: image, line: line, path: path, marker: marker, polygon: polygon, polyline: polyline, rect: rect, text: text }; module.exports = { isPointInPath: function isPointInPath(x, y) { var shape = shapes[this.type]; if (shape) { return shape.call(this, x, y); } return false; } }; /***/ }), /* 351 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var PathUtil = __webpack_require__(96); var d3Timer = __webpack_require__(101); var d3Ease = __webpack_require__(103); var _require = __webpack_require__(133), interpolate = _require.interpolate, interpolateArray = _require.interpolateArray; // 目前整体动画只需要数值和数组的差值计算 var Timeline = function Timeline(canvas) { // 待执行动画的队列 this._animators = []; // 当前时间 this._current = 0; // 计时器实例 this._timer = null; // 画布 this.canvas = canvas; }; function _update(self, animator, ratio) { var cProps = {}; // 此刻属性 var toAttrs = animator.toAttrs; var fromAttrs = animator.fromAttrs; var toMatrix = animator.toMatrix; if (self.get('destroyed')) { return; } var interf; // 差值函数 for (var k in toAttrs) { if (!Util.isEqual(fromAttrs[k], toAttrs[k])) { if (k === 'path') { var toPath = toAttrs[k]; var fromPath = fromAttrs[k]; if (toPath.length > fromPath.length) { toPath = PathUtil.parsePathString(toAttrs[k]); // 终点状态 fromPath = PathUtil.parsePathString(fromAttrs[k]); // 起始状态 fromPath = PathUtil.fillPathByDiff(fromPath, toPath); fromPath = PathUtil.formatPath(fromPath, toPath); animator.fromAttrs.path = fromPath; animator.toAttrs.path = toPath; } else if (!animator.pathFormatted) { toPath = PathUtil.parsePathString(toAttrs[k]); fromPath = PathUtil.parsePathString(fromAttrs[k]); fromPath = PathUtil.formatPath(fromPath, toPath); animator.fromAttrs.path = fromPath; animator.toAttrs.path = toPath; animator.pathFormatted = true; } cProps[k] = []; for (var i = 0; i < toPath.length; i++) { var toPathPoint = toPath[i]; var fromPathPoint = fromPath[i]; var cPathPoint = []; for (var j = 0; j < toPathPoint.length; j++) { if (Util.isNumber(toPathPoint[j]) && fromPathPoint && Util.isNumber(fromPathPoint[j])) { interf = interpolate(fromPathPoint[j], toPathPoint[j]); cPathPoint.push(interf(ratio)); } else { cPathPoint.push(toPathPoint[j]); } } cProps[k].push(cPathPoint); } } else { interf = interpolate(fromAttrs[k], toAttrs[k]); cProps[k] = interf(ratio); } } } if (toMatrix) { var mf = interpolateArray(animator.fromMatrix, toMatrix); var cM = mf(ratio); self.setMatrix(cM); } self.attr(cProps); } function update(shape, animator, elapsed) { var startTime = animator.startTime; // 如果还没有开始执行或暂停,先不更新 if (elapsed < startTime + animator.delay || animator.isPaused) { return false; } var ratio; var duration = animator.duration; var easing = animator.easing; // 已执行时间 elapsed = elapsed - startTime - animator.delay; if (animator.toAttrs.repeat) { ratio = elapsed % duration / duration; ratio = d3Ease[easing](ratio); } else { ratio = elapsed / duration; if (ratio < 1) { ratio = d3Ease[easing](ratio); } else { shape.attr(animator.toAttrs); if (animator.toMatrix) { shape.setMatrix(animator.toMatrix); } return true; } } _update(shape, animator, ratio); return false; } Util.augment(Timeline, { initTimer: function initTimer() { var _this = this; var self = this; var isFinished = false; var shape, animators, animator; self._timer = d3Timer.timer(function (elapsed) { self._current = elapsed; if (_this._animators.length > 0) { for (var i = _this._animators.length - 1; i >= 0; i--) { shape = _this._animators[i]; if (shape.get('destroyed')) { // 如果已经被销毁,直接移出队列 self.removeAnimator(i); continue; } if (!shape.get('pause').isPaused) { animators = shape.get('animators'); for (var j = animators.length - 1; j >= 0; j--) { animator = animators[j]; isFinished = update(shape, animator, elapsed); if (isFinished) { animators.splice(j, 1); isFinished = false; if (animator.callback) { animator.callback(); } } } } if (animators.length === 0) { self.removeAnimator(i); } } _this.canvas.draw(); } }); }, addAnimator: function addAnimator(shape) { this._animators.push(shape); }, removeAnimator: function removeAnimator(index) { this._animators.splice(index, 1); }, isAnimating: function isAnimating() { return !!this._animators.length; }, stop: function stop() { if (this._timer) { this._timer.stop(); } }, stopAllAnimations: function stopAllAnimations() { this._animators.forEach(function (animator) { animator.stopAnimate(); }); this._animators = []; this.canvas.draw(); }, getTime: function getTime() { return this._current; } }); module.exports = Timeline; /***/ }), /* 352 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { canvas: __webpack_require__(353), svg: __webpack_require__(356) }; /***/ }), /* 353 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { painter: __webpack_require__(354) }; /***/ }), /* 354 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var renderUtil = __webpack_require__(355); var SHAPE_ATTRS = ['fillStyle', 'font', 'globalAlpha', 'lineCap', 'lineWidth', 'lineJoin', 'miterLimit', 'shadowBlur', 'shadowColor', 'shadowOffsetX', 'shadowOffsetY', 'strokeStyle', 'textAlign', 'textBaseline', 'lineDash', 'lineDashOffset']; var Painter = /*#__PURE__*/function () { function Painter(dom) { if (!dom) { return null; } var canvasId = Util.uniqueId('canvas_'); var canvasDom = Util.createDom(''); dom.appendChild(canvasDom); this.type = 'canvas'; this.canvas = canvasDom; this.context = canvasDom.getContext('2d'); this.toDraw = false; return this; } var _proto = Painter.prototype; _proto.beforeDraw = function beforeDraw() { var el = this.canvas; this.context && this.context.clearRect(0, 0, el.width, el.height); }; _proto.draw = function draw(model) { var self = this; function drawInner() { self.animateHandler = Util.requestAnimationFrame(function () { self.animateHandler = undefined; if (self.toDraw) { drawInner(); } }); self.beforeDraw(); try { self._drawGroup(model); } catch (ev) { // 绘制时异常,中断重绘 console.warn('error in draw canvas, detail as:'); console.warn(ev); self.toDraw = false; } self.toDraw = false; } if (self.animateHandler) { self.toDraw = true; } else { drawInner(); } }; _proto.drawSync = function drawSync(model) { this.beforeDraw(); this._drawGroup(model); }; _proto._drawGroup = function _drawGroup(group) { if (group._cfg.removed || group._cfg.destroyed || !group._cfg.visible) { return; } var self = this; var children = group._cfg.children; var child = null; this.setContext(group); for (var i = 0; i < children.length; i++) { child = children[i]; if (children[i].isGroup) { self._drawGroup(child); } else { self._drawShape(child); } } this.restoreContext(group); }; _proto._drawShape = function _drawShape(shape) { if (shape._cfg.removed || shape._cfg.destroyed || !shape._cfg.visible) { return; } this.setContext(shape); shape.drawInner(this.context); this.restoreContext(shape); shape._cfg.attrs = shape._attrs; shape._cfg.hasUpdate = false; }; _proto.setContext = function setContext(shape) { var context = this.context; var clip = shape._attrs.clip; context.save(); if (clip) { // context.save(); clip.resetTransform(context); clip.createPath(context); context.clip(); // context.restore(); } this.resetContext(shape); shape.resetTransform(context); }; _proto.restoreContext = function restoreContext() { this.context.restore(); }; _proto.resetContext = function resetContext(shape) { var context = this.context; var elAttrs = shape._attrs; // var canvas = this.get('canvas'); if (!shape.isGroup) { for (var k in elAttrs) { if (SHAPE_ATTRS.indexOf(k) > -1) { // 非canvas属性不附加 var v = elAttrs[k]; if (k === 'fillStyle') { v = renderUtil.parseStyle(v, shape, context); } if (k === 'strokeStyle') { v = renderUtil.parseStyle(v, shape, context); } if (k === 'lineDash' && context.setLineDash) { if (Util.isArray(v)) { context.setLineDash(v); } else if (Util.isString(v)) { context.setLineDash(v.split(' ')); } } else { context[k] = v; } } } } }; return Painter; }(); module.exports = Painter; /***/ }), /* 355 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var regexTags = /[MLHVQTCSAZ]([^MLHVQTCSAZ]*)/ig; var regexDot = /[^\s\,]+/ig; var regexLG = /^l\s*\(\s*([\d.]+)\s*\)\s*(.*)/i; var regexRG = /^r\s*\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)\s*(.*)/i; var regexPR = /^p\s*\(\s*([axyn])\s*\)\s*(.*)/i; var regexColorStop = /[\d.]+:(#[^\s]+|[^\)]+\))/ig; var numColorCache = {}; function addStop(steps, gradient) { var arr = steps.match(regexColorStop); Util.each(arr, function (item) { item = item.split(':'); gradient.addColorStop(item[0], item[1]); }); } function parseLineGradient(color, self, context) { var arr = regexLG.exec(color); var angle = Util.mod(Util.toRadian(parseFloat(arr[1])), Math.PI * 2); var steps = arr[2]; var box = self.getBBox(); var start; var end; if (angle >= 0 && angle < 0.5 * Math.PI) { start = { x: box.minX, y: box.minY }; end = { x: box.maxX, y: box.maxY }; } else if (0.5 * Math.PI <= angle && angle < Math.PI) { start = { x: box.maxX, y: box.minY }; end = { x: box.minX, y: box.maxY }; } else if (Math.PI <= angle && angle < 1.5 * Math.PI) { start = { x: box.maxX, y: box.maxY }; end = { x: box.minX, y: box.minY }; } else { start = { x: box.minX, y: box.maxY }; end = { x: box.maxX, y: box.minY }; } var tanTheta = Math.tan(angle); var tanTheta2 = tanTheta * tanTheta; var x = (end.x - start.x + tanTheta * (end.y - start.y)) / (tanTheta2 + 1) + start.x; var y = tanTheta * (end.x - start.x + tanTheta * (end.y - start.y)) / (tanTheta2 + 1) + start.y; var gradient = context.createLinearGradient(start.x, start.y, x, y); addStop(steps, gradient); return gradient; } function parseRadialGradient(color, self, context) { var arr = regexRG.exec(color); var fx = parseFloat(arr[1]); var fy = parseFloat(arr[2]); var fr = parseFloat(arr[3]); var steps = arr[4]; // 环半径为0时,默认无渐变,取渐变序列的最后一个颜色 if (fr === 0) { var colors = steps.match(regexColorStop); return colors[colors.length - 1].split(':')[1]; } var box = self.getBBox(); var width = box.maxX - box.minX; var height = box.maxY - box.minY; var r = Math.sqrt(width * width + height * height) / 2; var gradient = context.createRadialGradient(box.minX + width * fx, box.minY + height * fy, fr * r, box.minX + width / 2, box.minY + height / 2, r); addStop(steps, gradient); return gradient; } function parsePattern(color, self, context) { if (self.get('patternSource') && self.get('patternSource') === color) { return self.get('pattern'); } var pattern; var img; var arr = regexPR.exec(color); var repeat = arr[1]; var source = arr[2]; // Function to be called when pattern loads function onload() { // Create pattern pattern = context.createPattern(img, repeat); self.setSilent('pattern', pattern); // be a cache self.setSilent('patternSource', color); } switch (repeat) { case 'a': repeat = 'repeat'; break; case 'x': repeat = 'repeat-x'; break; case 'y': repeat = 'repeat-y'; break; case 'n': repeat = 'no-repeat'; break; default: repeat = 'no-repeat'; } img = new Image(); // If source URL is not a data URL if (!source.match(/^data:/i)) { // Set crossOrigin for this image img.crossOrigin = 'Anonymous'; } img.src = source; if (img.complete) { onload(); } else { img.onload = onload; // Fix onload() bug in IE9 img.src = img.src; } return pattern; } module.exports = { parsePath: function parsePath(path) { path = path || []; if (Util.isArray(path)) { return path; } if (Util.isString(path)) { path = path.match(regexTags); Util.each(path, function (item, index) { item = item.match(regexDot); if (item[0].length > 1) { var tag = item[0].charAt(0); item.splice(1, 0, item[0].substr(1)); item[0] = tag; } Util.each(item, function (sub, i) { if (!isNaN(sub)) { item[i] = +sub; } }); path[index] = item; }); return path; } }, parseStyle: function parseStyle(color, self, context) { if (Util.isString(color)) { if (color[1] === '(' || color[2] === '(') { if (color[0] === 'l') { // regexLG.test(color) return parseLineGradient(color, self, context); } else if (color[0] === 'r') { // regexRG.test(color) return parseRadialGradient(color, self, context); } else if (color[0] === 'p') { // regexPR.test(color) return parsePattern(color, self, context); } } return color; } }, numberToColor: function numberToColor(num) { // 增加缓存 var color = numColorCache[num]; if (!color) { var str = num.toString(16); for (var i = str.length; i < 6; i++) { str = '0' + str; } color = '#' + str; numColorCache[num] = color; } return color; } }; /***/ }), /* 356 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { painter: __webpack_require__(357), getShape: __webpack_require__(364) }; /***/ }), /* 357 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(2); var _require = __webpack_require__(37), parseRadius = _require.parseRadius; var Marker = __webpack_require__(95); var Defs = __webpack_require__(358); var SHAPE_TO_TAGS = { rect: 'path', circle: 'circle', line: 'line', path: 'path', marker: 'path', text: 'text', polygon: 'polygon', image: 'image', ellipse: 'ellipse', dom: 'foreignObject', fan: 'path', group: 'g' }; var LETTER_SPACING = 0.3; var SVG_ATTR_MAP = { opacity: 'opacity', fillStyle: 'fill', strokeOpacity: 'stroke-opacity', fillOpacity: 'fill-opacity', strokeStyle: 'stroke', x: 'x', y: 'y', r: 'r', width: 'width', height: 'height', x1: 'x1', x2: 'x2', y1: 'y1', y2: 'y2', lineCap: 'stroke-linecap', lineJoin: 'stroke-linejoin', lineWidth: 'stroke-width', lineDash: 'stroke-dasharray', lineDashOffset: 'stroke-dashoffset', miterLimit: 'stroke-miterlimit', font: 'font', fontSize: 'font-size', fontStyle: 'font-style', fontVariant: 'font-variant', fontWeight: 'font-weight', fontFamily: 'font-family', startArrow: 'marker-start', endArrow: 'marker-end', path: 'd', class: 'class', id: 'id', style: 'style', preserveAspectRatio: 'preserveAspectRatio' }; var BASELINE_MAP = { top: 'before-edge', middle: 'central', bottom: 'after-edge', alphabetic: 'baseline', hanging: 'hanging' }; var ANCHOR_MAP = { left: 'left', start: 'left', center: 'middle', right: 'end', end: 'end' }; var Painter = /*#__PURE__*/function () { function Painter(dom) { if (!dom) { return null; } var svgId = Util.uniqueId('canvas_'); var canvasDom = Util.createDom(""); dom.appendChild(canvasDom); this.type = 'svg'; this.canvas = canvasDom; this.context = new Defs(canvasDom); this.toDraw = false; return this; } var _proto = Painter.prototype; _proto.draw = function draw(model) { var self = this; function drawInner() { self.animateHandler = Util.requestAnimationFrame(function () { self.animateHandler = undefined; if (self.toDraw) { drawInner(); } }); try { model.resetMatrix(); self._drawGroup(model, false); } catch (ev) { // 绘制时异常,中断重绘 console.warn('error in draw canvas, detail as:'); console.warn(ev); self.toDraw = false; } self.toDraw = false; } if (self.animateHandler) { self.toDraw = true; } else { drawInner(); } }; _proto.drawSync = function drawSync(model) { this._drawChildren(model, false); }; _proto._drawGroup = function _drawGroup(model, redraw) { var cfg = model._cfg; if (cfg.removed || cfg.destroyed) { return; } /** * FIXME redraw: 为了使元素置顶的临时解决方案 * 如果直接将dom元素重排可以解决部分问题。但是如果重排后的group中有新增的shape,置顶效果就没有了 * 所以只能删除原有节点,新增节点以及所有子节点。这时候哪怕shape有el,也需要判断一下是否需要重绘 */ if (!cfg.el && cfg.attrs) { redraw = true; } if (cfg.tobeRemoved) { Util.each(cfg.tobeRemoved, function (item) { if (item.parentNode) { item.parentNode.removeChild(item); } }); cfg.tobeRemoved = []; } this._drawShape(model, redraw); if (cfg.children && cfg.children.length > 0) { this._drawChildren(model, redraw); } }; _proto._drawChildren = function _drawChildren(parent, redraw) { var self = this; var children = parent._cfg.children; var shape; // 防止在画children的时候,父group已经被destroy if (!children) { return; } if (parent._cfg.el && !redraw) { // FIXME 这边是为了解决一个group中有元素已经生成el,还有一些没生成el时,没生成el的置底效果不work var childLen = parent._cfg.el.childNodes.length + 1; if (childLen !== 0 && childLen !== children.length) { redraw = true; } } for (var i = 0; i < children.length; i++) { shape = children[i]; if (shape.isGroup) { self._drawGroup(shape, redraw); } else { self._drawShape(shape, redraw); } } }; _proto._drawShape = function _drawShape(model, redraw) { var self = this; var attrs = model._attrs; var cfg = model._cfg; var el = cfg.el; // 删除 if (cfg.removed || cfg.destroyed) { if (el) { el.parentNode.removeChild(cfg.el); } return; } // 重绘节点 if (redraw && el) { el.parentNode && el.parentNode.removeChild(el); el = null; } // 新增节点 if (!el && cfg.parent) { self._createDom(model); self._updateShape(model); } el = cfg.el; if (cfg.visible === false) { el.setAttribute('visibility', 'hidden'); return; } if (cfg.visible && el.hasAttribute('visibility')) { el.removeAttribute('visibility'); } // 更新 if (cfg.hasUpdate) { self._updateShape(model); } if (attrs.clip && attrs.clip._cfg.hasUpdate) { self._updateShape(attrs.clip); } }; _proto._updateShape = function _updateShape(model) { var self = this; var attrs = model._attrs; var formerAttrs = model._cfg.attrs; if (!formerAttrs) { return; } if (!model._cfg.el) { self._createDom(model); } if ('clip' in attrs) { this._setClip(model, attrs.clip); } if ('shadowOffsetX' in attrs || 'shadowOffsetY' in attrs || 'shadowBlur' in attrs || 'shadowColor' in attrs) { this._setShadow(model); } if (model.type === 'text') { self._updateText(model); return; } if (model.type === 'fan') { self._updateFan(model); } if (model.type === 'marker') { model._cfg.el.setAttribute('d', self._assembleMarker(attrs)); } if (model.type === 'rect') { model._cfg.el.setAttribute('d', self._assembleRect(attrs)); } for (var key in attrs) { if (attrs[key] !== formerAttrs[key]) { self._setAttribute(model, key, attrs[key]); } } model._cfg.attrs = Util.deepMix({}, model._attrs); model._cfg.hasUpdate = false; }; _proto._setAttribute = function _setAttribute(model, name, value) { var type = model.type; var attrs = model._attrs; var el = model._cfg.el; var defs = this.context; // 计算marker路径 if ((type === 'marker' || type === 'rect') && ~['x', 'y', 'radius', 'r'].indexOf(name)) { return; } // 圆和椭圆不是x, y, 是cx, cy。 marker的x,y 用于计算marker的路径,不需要写到dom if (~['circle', 'ellipse'].indexOf(type) && ~['x', 'y'].indexOf(name)) { el.setAttribute('c' + name, parseInt(value, 10)); return; } // 多边形 if (type === 'polygon' && name === 'points') { if (!value || value.length === 0) { value = ''; } if (Util.isArray(value)) { value = value.map(function (point) { return point[0] + ',' + point[1]; }); value = value.join(' '); } el.setAttribute('points', value); return; } // 设置path if (name === 'path' && Util.isArray(value)) { el.setAttribute('d', this._formatPath(value)); return; } // 设置图片 if (name === 'img') { this._setImage(model, value); return; } if (name === 'transform') { if (!value) { el.removeAttribute('transform'); return; } this._setTransform(model); return; } if (name === 'rotate') { if (!value) { el.removeAttribute('transform'); return; } this._setTransform(model); return; } if (name === 'matrix') { this._setTransform(model); return; } if (name === 'fillStyle' || name === 'strokeStyle') { this._setColor(model, name, value); return; } if (name === 'clip') { return; } if (~name.indexOf('Arrow')) { name = SVG_ATTR_MAP[name]; if (!value) { model._cfg[name] = null; el.removeAttribute(name); } else { var id = null; if (typeof value === 'boolean') { id = defs.getDefaultArrow(attrs, name); } else { id = defs.addArrow(attrs, name); } el.setAttribute(name, "url(#" + id + ")"); model._cfg[name] = id; } return; } // foreignObject if (name === 'html') { if (typeof value === 'string') { el.innerHTML = value; } else { el.innerHTML = ''; el.appendChild(value); } } if (SVG_ATTR_MAP[name]) { el.setAttribute(SVG_ATTR_MAP[name], value); } }; _proto._createDom = function _createDom(model) { var type = SHAPE_TO_TAGS[model.type]; var attrs = model._attrs; if (!type) { throw new Error('the type' + model.type + 'is not supported by svg'); } var shape = document.createElementNS('http://www.w3.org/2000/svg', type); model._cfg.el = shape; if (model._cfg.parent) { model._cfg.parent.get('el').appendChild(shape); } model._cfg.attrs = {}; if (model.type === 'text') { shape.setAttribute('paint-order', 'stroke'); shape.setAttribute('style', 'stroke-linecap:butt; stroke-linejoin:miter;'); } else { if (!attrs.stroke && !attrs.strokeStyle) { shape.setAttribute('stroke', 'none'); } if (!attrs.fill && !attrs.fillStyle) { shape.setAttribute('fill', 'none'); } } return shape; }; _proto._assembleMarker = function _assembleMarker(attrs) { var r = attrs.r; if (typeof attrs.r === 'undefined') { r = attrs.radius; } if (isNaN(Number(attrs.x)) || isNaN(Number(attrs.y)) || isNaN(Number(r))) { return ''; } var d = ''; if (typeof attrs.symbol === 'function') { d = attrs.symbol(attrs.x, attrs.y, r); } else { d = Marker.Symbols[attrs.symbol || 'circle'](attrs.x, attrs.y, r); } if (Util.isArray(d)) { d = d.map(function (path) { return path.join(' '); }).join(''); } return d; }; _proto._assembleRect = function _assembleRect(attrs) { var x = attrs.x; var y = attrs.y; var w = attrs.width; var h = attrs.height; var radius = attrs.radius; if (!radius) { return "M " + x + "," + y + " l " + w + ",0 l 0," + h + " l" + -w + " 0 z"; } var r = parseRadius(radius); if (Util.isArray(radius)) { if (radius.length === 1) { r.r1 = r.r2 = r.r3 = r.r4 = radius[0]; } else if (radius.length === 2) { r.r1 = r.r3 = radius[0]; r.r2 = r.r4 = radius[1]; } else if (radius.length === 3) { r.r1 = radius[0]; r.r2 = r.r4 = radius[1]; r.r3 = radius[2]; } else { r.r1 = radius[0]; r.r2 = radius[1]; r.r3 = radius[2]; r.r4 = radius[3]; } } else { r.r1 = r.r2 = r.r3 = r.r4 = radius; } var d = [["M " + (x + r.r1) + "," + y], ["l " + (w - r.r1 - r.r2) + ",0"], ["a " + r.r2 + "," + r.r2 + ",0,0,1," + r.r2 + "," + r.r2], ["l 0," + (h - r.r2 - r.r3)], ["a " + r.r3 + "," + r.r3 + ",0,0,1," + -r.r3 + "," + r.r3], ["l " + (r.r3 + r.r4 - w) + ",0"], ["a " + r.r4 + "," + r.r4 + ",0,0,1," + -r.r4 + "," + -r.r4], ["l 0," + (r.r4 + r.r1 - h)], ["a " + r.r1 + "," + r.r1 + ",0,0,1," + r.r1 + "," + -r.r1], ['z']]; return d.join(' '); }; _proto._formatPath = function _formatPath(value) { value = value.map(function (path) { return path.join(' '); }).join(''); if (~value.indexOf('NaN')) { return ''; } return value; }; _proto._setTransform = function _setTransform(model) { var matrix = model._attrs.matrix; var el = model._cfg.el; var transform = []; for (var i = 0; i < 9; i += 3) { transform.push(matrix[i] + ',' + matrix[i + 1]); } transform = transform.join(','); if (transform.indexOf('NaN') === -1) { el.setAttribute('transform', "matrix(" + transform + ")"); } else { console.warn('invalid matrix:', matrix); } }; _proto._setImage = function _setImage(model, img) { var attrs = model._attrs; var el = model._cfg.el; if (Util.isString(img)) { el.setAttribute('href', img); } else if (img instanceof Image) { if (!attrs.width) { el.setAttribute('width', img.width); model._attrs.width = img.width; } if (!attrs.height) { el.setAttribute('height', img.height); model._attrs.height = img.height; } el.setAttribute('href', img.src); } else if (img instanceof HTMLElement && Util.isString(img.nodeName) && img.nodeName.toUpperCase() === 'CANVAS') { el.setAttribute('href', img.toDataURL()); } else if (img instanceof ImageData) { var canvas = document.createElement('canvas'); canvas.setAttribute('width', img.width); canvas.setAttribute('height', img.height); canvas.getContext('2d').putImageData(img, 0, 0); if (!attrs.width) { el.setAttribute('width', img.width); model._attrs.width = img.width; } if (!attrs.height) { el.setAttribute('height', img.height); model._attrs.height = img.height; } el.setAttribute('href', canvas.toDataURL()); } }; _proto._updateFan = function _updateFan(model) { function getPoint(angle, radius, center) { return { x: radius * Math.cos(angle) + center.x, y: radius * Math.sin(angle) + center.y }; } var attrs = model._attrs; var cfg = model._cfg; var center = { x: attrs.x, y: attrs.y }; var d = []; var startAngle = attrs.startAngle; var endAngle = attrs.endAngle; if (Util.isNumberEqual(endAngle - startAngle, Math.PI * 2)) { endAngle -= 0.00001; } var outerStart = getPoint(startAngle, attrs.re, center); var outerEnd = getPoint(endAngle, attrs.re, center); var fa = endAngle > startAngle ? 1 : 0; var fs = Math.abs(endAngle - startAngle) > Math.PI ? 1 : 0; var rs = attrs.rs; var re = attrs.re; var innerStart = getPoint(startAngle, attrs.rs, center); var innerEnd = getPoint(endAngle, attrs.rs, center); if (attrs.rs > 0) { d.push("M " + outerEnd.x + "," + outerEnd.y); d.push("L " + innerEnd.x + "," + innerEnd.y); d.push("A " + rs + "," + rs + ",0," + fs + "," + (fa === 1 ? 0 : 1) + "," + innerStart.x + "," + innerStart.y); d.push("L " + outerStart.x + " " + outerStart.y); } else { d.push("M " + center.x + "," + center.y); d.push("L " + outerStart.x + "," + outerStart.y); } d.push("A " + re + "," + re + ",0," + fs + "," + fa + "," + outerEnd.x + "," + outerEnd.y); if (attrs.rs > 0) { d.push("L " + innerEnd.x + "," + innerEnd.y); } else { d.push('Z'); } cfg.el.setAttribute('d', d.join(' ')); }; _proto._updateText = function _updateText(model) { var self = this; var attrs = model._attrs; var formerAttrs = model._cfg.attrs; var el = model._cfg.el; this._setFont(model); for (var attr in attrs) { if (attrs[attr] !== formerAttrs[attr]) { if (attr === 'text') { self._setText(model, "" + attrs[attr]); continue; } if (attr === 'fillStyle' || attr === 'strokeStyle') { this._setColor(model, attr, attrs[attr]); continue; } if (attr === 'matrix') { this._setTransform(model); continue; } if (SVG_ATTR_MAP[attr]) { el.setAttribute(SVG_ATTR_MAP[attr], attrs[attr]); } } } model._cfg.attrs = Object.assign({}, model._attrs); model._cfg.hasUpdate = false; }; _proto._setFont = function _setFont(model) { var el = model.get('el'); var attrs = model._attrs; var fontSize = attrs.fontSize; el.setAttribute('alignment-baseline', BASELINE_MAP[attrs.textBaseline] || 'baseline'); el.setAttribute('text-anchor', ANCHOR_MAP[attrs.textAlign] || 'left'); if (fontSize && +fontSize < 12) { // 小于 12 像素的文本进行 scale 处理 attrs.matrix = [1, 0, 0, 0, 1, 0, 0, 0, 1]; model.transform([['t', -attrs.x, -attrs.y], ['s', +fontSize / 12, +fontSize / 12], ['t', attrs.x, attrs.y]]); } }; _proto._setText = function _setText(model, text) { var el = model._cfg.el; var baseline = model._attrs.textBaseline || 'bottom'; if (!text) { el.innerHTML = ''; } else if (~text.indexOf('\n')) { var x = model._attrs.x; var textArr = text.split('\n'); var textLen = textArr.length - 1; var arr = ''; Util.each(textArr, function (segment, i) { if (i === 0) { if (baseline === 'alphabetic') { arr += "" + segment + ""; } else if (baseline === 'top') { arr += "" + segment + ""; } else if (baseline === 'middle') { arr += "" + segment + ""; } else if (baseline === 'bottom') { arr += "" + segment + ""; } else if (baseline === 'hanging') { arr += "" + segment + ""; } } else { arr += "" + segment + ""; } }); el.innerHTML = arr; } else { el.innerHTML = text; } }; _proto._setClip = function _setClip(model, value) { var el = model._cfg.el; if (!value) { el.removeAttribute('clip-path'); return; } if (!el.hasAttribute('clip-path')) { this._createDom(value); this._updateShape(value); var id = this.context.addClip(value); el.setAttribute('clip-path', "url(#" + id + ")"); } else if (value._cfg.hasUpdate) { this._updateShape(value); } }; _proto._setColor = function _setColor(model, name, value) { var el = model._cfg.el; var defs = this.context; if (!value) { el.setAttribute(SVG_ATTR_MAP[name], 'none'); return; } value = value.trim(); if (/^[r,R,L,l]{1}[\s]*\(/.test(value)) { var id = defs.find('gradient', value); if (!id) { id = defs.addGradient(value); } el.setAttribute(SVG_ATTR_MAP[name], "url(#" + id + ")"); } else if (/^[p,P]{1}[\s]*\(/.test(value)) { var _id = defs.find('pattern', value); if (!_id) { _id = defs.addPattern(value); } el.setAttribute(SVG_ATTR_MAP[name], "url(#" + _id + ")"); } else { el.setAttribute(SVG_ATTR_MAP[name], value); } }; _proto._setShadow = function _setShadow(model) { var el = model._cfg.el; var attrs = model._attrs; var cfg = { dx: attrs.shadowOffsetX, dy: attrs.shadowOffsetY, blur: attrs.shadowBlur, color: attrs.shadowColor }; if (!cfg.dx && !cfg.dy && !cfg.blur && !cfg.color) { el.removeAttribute('filter'); } else { var id = this.context.find('filter', cfg); if (!id) { id = this.context.addShadow(cfg, this); } el.setAttribute('filter', "url(#" + id + ")"); } }; return Painter; }(); module.exports = Painter; /***/ }), /* 358 */ /***/ (function(module, exports, __webpack_require__) { /** * Created by Elaine on 2018/5/9. */ var Util = __webpack_require__(2); var Gradient = __webpack_require__(359); var Shadow = __webpack_require__(360); var Arrow = __webpack_require__(361); var Clip = __webpack_require__(362); var Pattern = __webpack_require__(363); var Defs = /*#__PURE__*/function () { function Defs(canvas) { var el = document.createElementNS('http://www.w3.org/2000/svg', 'defs'); var id = Util.uniqueId('defs_'); el.id = id; canvas.appendChild(el); this.children = []; this.defaultArrow = {}; this.el = el; this.canvas = canvas; } var _proto = Defs.prototype; _proto.find = function find(type, attr) { var children = this.children; var result = null; for (var i = 0; i < children.length; i++) { if (children[i].match(type, attr)) { result = children[i].id; break; } } return result; }; _proto.findById = function findById(id) { var children = this.children; var flag = null; for (var i = 0; i < children.length; i++) { if (children[i].id === id) { flag = children[i]; break; } } return flag; }; _proto.add = function add(item) { this.children.push(item); item.canvas = this.canvas; item.parent = this; }; _proto.getDefaultArrow = function getDefaultArrow(attrs, name) { var stroke = attrs.stroke || attrs.strokeStyle; if (this.defaultArrow[stroke]) { return this.defaultArrow[stroke].id; } var arrow = new Arrow(attrs, name); this.defaultArrow[stroke] = arrow; this.el.appendChild(arrow.el); return arrow.id; }; _proto.addGradient = function addGradient(cfg) { var gradient = new Gradient(cfg); this.el.appendChild(gradient.el); this.add(gradient); return gradient.id; }; _proto.addArrow = function addArrow(attrs, name) { var arrow = new Arrow(attrs, name); this.el.appendChild(arrow.el); return arrow.id; }; _proto.addShadow = function addShadow(cfg) { var shadow = new Shadow(cfg); this.el.appendChild(shadow.el); this.add(shadow); return shadow.id; }; _proto.addPattern = function addPattern(cfg) { var pattern = new Pattern(cfg); this.el.appendChild(pattern.el); this.add(pattern); return pattern.id; }; _proto.addClip = function addClip(cfg) { var clip = new Clip(cfg); this.el.appendChild(clip.el); this.add(clip); return clip.id; }; return Defs; }(); module.exports = Defs; /***/ }), /* 359 */ /***/ (function(module, exports, __webpack_require__) { /** * Created by Elaine on 2018/5/9. */ var Util = __webpack_require__(2); var regexLG = /^l\s*\(\s*([\d.]+)\s*\)\s*(.*)/i; var regexRG = /^r\s*\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\s*\)\s*(.*)/i; var regexColorStop = /[\d.]+:(#[^\s]+|[^\)]+\))/ig; function addStop(steps) { var arr = steps.match(regexColorStop); if (!arr) { return ''; } var stops = ''; arr.sort(function (a, b) { a = a.split(':'); b = b.split(':'); return Number(a[0]) - Number(b[0]); }); Util.each(arr, function (item) { item = item.split(':'); stops += ""; }); return stops; } function parseLineGradient(color, el) { var arr = regexLG.exec(color); var angle = Util.mod(Util.toRadian(parseFloat(arr[1])), Math.PI * 2); var steps = arr[2]; var start; var end; if (angle >= 0 && angle < 0.5 * Math.PI) { start = { x: 0, y: 0 }; end = { x: 1, y: 1 }; } else if (0.5 * Math.PI <= angle && angle < Math.PI) { start = { x: 1, y: 0 }; end = { x: 0, y: 1 }; } else if (Math.PI <= angle && angle < 1.5 * Math.PI) { start = { x: 1, y: 1 }; end = { x: 0, y: 0 }; } else { start = { x: 0, y: 1 }; end = { x: 1, y: 0 }; } var tanTheta = Math.tan(angle); var tanTheta2 = tanTheta * tanTheta; var x = (end.x - start.x + tanTheta * (end.y - start.y)) / (tanTheta2 + 1) + start.x; var y = tanTheta * (end.x - start.x + tanTheta * (end.y - start.y)) / (tanTheta2 + 1) + start.y; el.setAttribute('x1', start.x); el.setAttribute('y1', start.y); el.setAttribute('x2', x); el.setAttribute('y2', y); el.innerHTML = addStop(steps); } function parseRadialGradient(color, self) { var arr = regexRG.exec(color); var cx = parseFloat(arr[1]); var cy = parseFloat(arr[2]); var r = parseFloat(arr[3]); var steps = arr[4]; self.setAttribute('cx', cx); self.setAttribute('cy', cy); self.setAttribute('r', r); self.innerHTML = addStop(steps); } var Gradient = /*#__PURE__*/function () { function Gradient(cfg) { var el = null; var id = Util.uniqueId('gradient_'); if (cfg.toLowerCase()[0] === 'l') { el = document.createElementNS('http://www.w3.org/2000/svg', 'linearGradient'); parseLineGradient(cfg, el); } else { el = document.createElementNS('http://www.w3.org/2000/svg', 'radialGradient'); parseRadialGradient(cfg, el); } el.setAttribute('id', id); this.el = el; this.id = id; this.cfg = cfg; return this; } var _proto = Gradient.prototype; _proto.match = function match(type, attr) { return this.cfg === attr; }; return Gradient; }(); module.exports = Gradient; /***/ }), /* 360 */ /***/ (function(module, exports, __webpack_require__) { /** * Created by Elaine on 2018/5/10. */ var Util = __webpack_require__(2); var ATTR_MAP = { shadowColor: 'color', shadowOpacity: 'opacity', shadowBlur: 'blur', shadowOffsetX: 'dx', shadowOffsetY: 'dy' }; var SHADOW_DIMENSION = { x: '-40%', y: '-40%', width: '200%', height: '200%' }; var Shadow = /*#__PURE__*/function () { function Shadow(cfg) { this.type = 'filter'; var el = document.createElementNS('http://www.w3.org/2000/svg', 'filter'); // expand the filter region to fill in shadows Util.each(SHADOW_DIMENSION, function (v, k) { el.setAttribute(k, v); }); this.el = el; this.id = Util.uniqueId('filter_'); this.el.id = this.id; this.cfg = cfg; this._parseShadow(cfg, el); return this; } var _proto = Shadow.prototype; _proto.match = function match(type, cfg) { if (this.type !== type) { return false; } var flag = true; var config = this.cfg; Util.each(Object.keys(config), function (attr) { if (config[attr] !== cfg[attr]) { flag = false; return false; } }); return flag; }; _proto.update = function update(name, value) { var config = this.cfg; config[ATTR_MAP[name]] = value; this._parseShadow(config, this.el); return this; }; _proto._parseShadow = function _parseShadow(config, el) { var child = ""; el.innerHTML = child; }; return Shadow; }(); module.exports = Shadow; /***/ }), /* 361 */ /***/ (function(module, exports, __webpack_require__) { /** * Created by Elaine on 2018/5/11. */ var Util = __webpack_require__(2); var Arrow = /*#__PURE__*/function () { function Arrow(attrs, type) { var el = document.createElementNS('http://www.w3.org/2000/svg', 'marker'); var id = Util.uniqueId('marker_'); el.setAttribute('id', id); var shape = document.createElementNS('http://www.w3.org/2000/svg', 'path'); shape.setAttribute('stroke', 'none'); shape.setAttribute('fill', attrs.stroke || '#000'); el.appendChild(shape); el.setAttribute('overflow', 'visible'); el.setAttribute('orient', 'auto-start-reverse'); this.el = el; this.child = shape; this.id = id; this.cfg = attrs[type === 'marker-start' ? 'startArrow' : 'endArrow']; this.stroke = attrs.stroke || '#000'; if (this.cfg === true) { this._setDefaultPath(type, shape); } else { this._setMarker(attrs.lineWidth, shape); } return this; } var _proto = Arrow.prototype; _proto.match = function match() { return false; }; _proto._setDefaultPath = function _setDefaultPath(type, el) { var parent = this.el; el.setAttribute('d', 'M0,0 L6,3 L0,6 L3,3Z'); parent.setAttribute('refX', 3); parent.setAttribute('refY', 3); }; _proto._setMarker = function _setMarker(r, el) { var parent = this.el; var path = this.cfg.path; var d = this.cfg.d; if (Util.isArray(path)) { path = path.map(function (segment) { return segment.join(' '); }).join(''); } el.setAttribute('d', path); parent.appendChild(el); if (d) { parent.setAttribute('refX', d / r); } }; _proto.update = function update(fill) { var child = this.child; if (child.attr) { child.attr('fill', fill); } else { child.setAttribute('fill', fill); } }; return Arrow; }(); module.exports = Arrow; /***/ }), /* 362 */ /***/ (function(module, exports, __webpack_require__) { /** * Created by Elaine on 2018/5/14. */ var Util = __webpack_require__(2); var Clip = /*#__PURE__*/function () { function Clip(cfg) { this.type = 'clip'; var el = document.createElementNS('http://www.w3.org/2000/svg', 'clipPath'); this.el = el; this.id = Util.uniqueId('clip_'); el.id = this.id; var shapeEl = cfg._cfg.el; // just in case the clip shape is also a shape needs to be drawn el.appendChild(shapeEl.cloneNode(true)); this.cfg = cfg; return this; } var _proto = Clip.prototype; _proto.match = function match() { return false; }; _proto.remove = function remove() { var el = this.el; el.parentNode.removeChild(el); }; return Clip; }(); module.exports = Clip; /***/ }), /* 363 */ /***/ (function(module, exports, __webpack_require__) { /** * Created by Elaine on 2018/5/9. */ var Util = __webpack_require__(2); var regexPR = /^p\s*\(\s*([axyn])\s*\)\s*(.*)/i; var Pattern = /*#__PURE__*/function () { function Pattern(cfg) { var el = document.createElementNS('http://www.w3.org/2000/svg', 'pattern'); el.setAttribute('patternUnits', 'userSpaceOnUse'); var child = document.createElementNS('http://www.w3.org/2000/svg', 'image'); el.appendChild(child); var id = Util.uniqueId('pattern_'); el.id = id; this.el = el; this.id = id; this.cfg = cfg; var arr = regexPR.exec(cfg); var source = arr[2]; child.setAttribute('href', source); var img = new Image(); if (!source.match(/^data:/i)) { img.crossOrigin = 'Anonymous'; } img.src = source; function onload() { console.log(img.width, img.height); el.setAttribute('width', img.width); el.setAttribute('height', img.height); } if (img.complete) { onload(); } else { img.onload = onload; // Fix onload() bug in IE9 img.src = img.src; } return this; } var _proto = Pattern.prototype; _proto.match = function match(type, attr) { return this.cfg === attr; }; return Pattern; }(); module.exports = Pattern; /***/ }), /* 364 */ /***/ (function(module, exports) { var TAG_MAP = { svg: 'svg', circle: 'circle', rect: 'rect', text: 'text', path: 'path', foreignObject: 'foreignObject', polygon: 'polygon', ellipse: 'ellipse', image: 'image' }; module.exports = function getShape(x, y, e) { var target = e.target || e.srcElement; if (!TAG_MAP[target.tagName]) { var parent = target.parentNode; while (parent && !TAG_MAP[parent.tagName]) { parent = parent.parentNode; } target = parent; } if (this._cfg.el === target) { return this; } return this.find(function (item) { return item._cfg && item._cfg.el === target; }); }; /***/ }), /* 365 */ /***/ (function(module, exports, __webpack_require__) { var Greedy = __webpack_require__(189); /* * 根据如下规则尝试放置label * 5 * ------------------ * | 1 | 0 | * 8 —————————4———————— 7 * | 2 | 3 | * —————————————————— * 6 */ function adjustLabelPosition(label, x, y, index) { var bbox = label.getBBox(); var width = bbox.width; var height = bbox.height; var attrs = { x: x, y: y, textAlign: 'center' }; switch (index) { case 0: attrs.y -= height / 2; attrs.textAlign = 'left'; break; case 1: attrs.y -= height / 2; attrs.textAlign = 'right'; break; case 2: attrs.y += height / 2; attrs.textAlign = 'right'; break; case 3: attrs.y += height / 2; attrs.textAlign = 'left'; break; case 5: attrs.y -= height / 2; break; case 6: attrs.y += height / 2; break; case 7: attrs.x += width / 2; attrs.textAlign = 'left'; break; case 8: attrs.x -= width / 2; attrs.textAlign = 'right'; break; default: break; } label.attr(attrs); return label.getBBox(); } module.exports = function (labels) { var greedy = new Greedy(); var toBeRemoved = []; var bbox, label, x, y, canFill; for (var i = 0; i < labels.length; i++) { label = labels[i]; x = label.attr('x'); y = label.attr('y'); canFill = false; for (var _i = 0; _i < 8; _i++) { bbox = adjustLabelPosition(label, x, y, _i); if (greedy.hasGap(bbox)) { greedy.fillGap(bbox); canFill = true; break; } } if (!canFill) { toBeRemoved.push(label); } } for (var _i2 = 0; _i2 < toBeRemoved.length; _i2++) { toBeRemoved[_i2].remove(); } return canFill; }; /***/ }), /* 366 */ /***/ (function(module, exports, __webpack_require__) { var Greedy = __webpack_require__(189); var MAX_TIMES = 20; function spiralFill(label, greedy) { var dt = -1; var x = label.attr('x'), y = label.attr('y'); var bbox = label.getBBox(); var maxDelta = Math.sqrt(bbox.width * bbox.width + bbox.height * bbox.height); var dxdy, t = -dt, dx = 0, dy = 0; var f = function f(t) { return [(t *= 0.1) * Math.cos(t), t * Math.sin(t)]; }; if (greedy.hasGap(bbox)) { greedy.fillGap(bbox); return true; } var canFill = false, times = 0; while (Math.min(Math.abs(dx), Math.abs(dy)) < maxDelta && times < MAX_TIMES) { dxdy = f(t += dt); dx = ~~dxdy[0]; dy = ~~dxdy[1]; label.attr({ x: x + dx, y: y + dy }); times++; if (greedy.hasGap(label.getBBox())) { greedy.fillGap(bbox); canFill = true; break; } } return canFill; } module.exports = function (labels) { var label; var greedy = new Greedy(); var toBeRemoved = []; for (var i = 0; i < labels.length; i++) { label = labels[i]; if (!spiralFill(label, greedy)) { toBeRemoved.push(label); } } for (var _i = 0; _i < toBeRemoved.length; _i++) { toBeRemoved[_i].remove(); } }; /***/ }), /* 367 */ /***/ (function(module, exports) { module.exports = function bboxAdjust(labels, shapes) { var labelBBox, shapeBBox; var toBeRemoved = []; for (var i = 0; i < labels.length; i++) { labelBBox = labels[i].getBBox(); shapeBBox = shapes[i].getBBox(); if (labelBBox.width > shapeBBox.width || labelBBox.height > shapeBBox.height) { toBeRemoved.push(labels[i]); } else if (labelBBox.width * labelBBox.height > shapeBBox.width * shapeBBox.height) { toBeRemoved.push(labels[i]); } } for (var _i = 0; _i < toBeRemoved.length; _i++) { toBeRemoved[_i].remove(); } }; /***/ }), /* 368 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var Base = __webpack_require__(35); var vec2 = Util.MatrixUtil.vec2; var Circle = /*#__PURE__*/function (_Base) { _inheritsLoose(Circle, _Base); function Circle() { return _Base.apply(this, arguments) || this; } var _proto = Circle.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Base.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * 坐标轴的类型 * @type {String} */ type: 'circle', /** * 指定刻度之间的间距 * @type {Number} */ tickInterval: null, /** * 开始弧度 * @type {Number} */ startAngle: -Math.PI / 2, /** * 结束弧度 * @type {Number} */ endAngle: Math.PI * 3 / 2, line: { // @type {Attrs} 坐标轴线的图形属性,如果设置成null,则不显示轴线 lineWidth: 1, stroke: '#C0D0E0' }, tickLine: { // @type {Attrs} 标注坐标线的图形属性 lineWidth: 1, stroke: '#C0D0E0', length: 5 }, /** * 默认文本距离轴线的距离 * @type {Number} */ _labelOffset: 5 }); }; _proto.parseTick = function parseTick(tick, index, length) { return { text: tick, value: index / length }; }; _proto._getCirclePoint = function _getCirclePoint(angle, radius) { var self = this; var center = self.get('center'); radius = radius || self.get('radius'); return { x: center.x + Math.cos(angle) * radius, y: center.y + Math.sin(angle) * radius }; }; _proto.getTickPoint = function getTickPoint(value) { var self = this; var startAngle = self.get('startAngle'); var endAngle = self.get('endAngle'); var angle = startAngle + (endAngle - startAngle) * value; return self._getCirclePoint(angle); }; _proto.getSideVector = function getSideVector(offset, point) { var self = this; var center = self.get('center'); var vector = [point.x - center.x, point.y - center.y]; if (!Util.isNil(offset)) { var vecLen = vec2.length(vector); vec2.scale(vector, vector, offset / vecLen); } return vector; }; _proto.getSidePoint = function getSidePoint(point, offset) { var self = this; var vector = self.getSideVector(offset, point); return { x: point.x + vector[0], y: point.y + vector[1] }; }; _proto.getTickEnd = function getTickEnd(start, length) { var self = this; var tickLine = self.get('tickLine'); length = length ? length : tickLine.length; return self.getSidePoint(start, length); }; _proto.getTextAnchor = function getTextAnchor(vector) { var align; if (Util.snapEqual(vector[0], 0)) { align = 'center'; } else if (vector[0] > 0) { align = 'left'; } else if (vector[0] < 0) { align = 'right'; } return align; }; _proto.getLinePath = function getLinePath() { var self = this; var center = self.get('center'); var x = center.x; var y = center.y; var rx = self.get('radius'); var ry = rx; var startAngle = self.get('startAngle'); var endAngle = self.get('endAngle'); var inner = self.get('inner'); var path = []; if (Math.abs(endAngle - startAngle) === Math.PI * 2) { path = [['M', x, y], ['m', 0, -ry], ['a', rx, ry, 0, 1, 1, 0, 2 * ry], ['a', rx, ry, 0, 1, 1, 0, -2 * ry], ['z']]; } else { var startPoint = self._getCirclePoint(startAngle); var endPoint = self._getCirclePoint(endAngle); var large = Math.abs(endAngle - startAngle) > Math.PI ? 1 : 0; var sweep = startAngle > endAngle ? 0 : 1; if (!inner) { path = [['M', x, y], ['L', startPoint.x, startPoint.y], ['A', rx, ry, 0, large, sweep, endPoint.x, endPoint.y], ['L', x, y]]; } else { var innerStartVector = self.getSideVector(inner * rx, startPoint); var innerEndVector = self.getSideVector(inner * rx, endPoint); var innerStartPoint = { x: innerStartVector[0] + x, y: innerStartVector[1] + y }; var innerEndPoint = { x: innerEndVector[0] + x, y: innerEndVector[1] + y }; path = [['M', innerStartPoint.x, innerStartPoint.y], ['L', startPoint.x, startPoint.y], ['A', rx, ry, 0, large, sweep, endPoint.x, endPoint.y], ['L', innerEndPoint.x, innerEndPoint.y], ['A', rx * inner, ry * inner, 0, large, Math.abs(sweep - 1), innerStartPoint.x, innerStartPoint.y]]; } } return path; }; _proto.addLabel = function addLabel(tick, point, index) { var self = this; var offset = self.get('label').offset || self.get('_labelOffset') || 0.001; point = self.getSidePoint(point, offset); _Base.prototype.addLabel.call(this, tick, point, index); }; _proto.autoRotateLabels = function autoRotateLabels() { var self = this; var ticks = self.get('ticks'); var labelRenderer = self.get('labelRenderer'); if (labelRenderer && ticks.length > 12) { // 小于12个文本时文本不旋转 var radius = self.get('radius'); var startAngle = self.get('startAngle'); var endAngle = self.get('endAngle'); var totalAngle = endAngle - startAngle; var avgAngle = totalAngle / (ticks.length - 1); var avgWidth = Math.sin(avgAngle / 2) * radius * 2; var maxLength = self.getMaxLabelWidth(labelRenderer); Util.each(labelRenderer.get('group').get('children'), function (label, index) { var tick = ticks[index]; var angle = tick.value * totalAngle + startAngle; var mode = angle % (Math.PI * 2); if (maxLength < avgWidth) { // 文本的最大宽度大于 if (mode <= 0) { angle = angle + Math.PI; } if (mode > Math.PI) { angle = angle - Math.PI; } angle = angle - Math.PI / 2; label.attr('textAlign', 'center'); } else { if (mode > Math.PI / 2) { angle = angle - Math.PI; } else if (mode < Math.PI / 2 * -1) { angle = angle + Math.PI; } } label.rotateAtStart(angle); }); } }; return Circle; }(Base); module.exports = Circle; /***/ }), /* 369 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var Base = __webpack_require__(35); var MatrixUtil = Util.MatrixUtil, PathUtil = Util.PathUtil; var vec2 = MatrixUtil.vec2; var Helix = /*#__PURE__*/function (_Base) { _inheritsLoose(Helix, _Base); function Helix() { return _Base.apply(this, arguments) || this; } var _proto = Helix.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Base.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { inner: 0, type: 'helix', line: { // @type {Attrs} 坐标轴线的图形属性,如果设置成null,则不显示轴线 lineWidth: 1, stroke: '#C0D0E0' }, tickLine: { // @type {Attrs} 标注坐标线的图形属性 lineWidth: 1, stroke: '#C0D0E0', length: 5 }, startAngle: 1.25 * Math.PI, endAngle: 7.25 * Math.PI, // 螺旋系数 a: 0, // 画布中心坐标 center: null, // 坐标轴绘制起点 axisStart: null, // 坐标轴的n个坐标点 crp: [] }); }; _proto.getLinePath = function getLinePath() { var self = this; var crp = self.get('crp'); var axisStart = self.get('axisStart'); var path = PathUtil.catmullRomToBezier(crp); path.unshift(['M', axisStart.x, axisStart.y]); return path; }; _proto.getTickPoint = function getTickPoint(value) { var self = this; var startAngle = self.get('startAngle'); var endAngle = self.get('endAngle'); var angle = startAngle + (endAngle - startAngle) * value; return self._getHelixPoint(angle); }; _proto._getHelixPoint = function _getHelixPoint(angle) { var self = this; var center = self.get('center'); var a = self.get('a'); // 螺线系数 var radius = a * angle + self.get('inner'); // 螺线方程 return { x: center.x + Math.cos(angle) * radius, y: center.y + Math.sin(angle) * radius }; }; _proto.getSideVector = function getSideVector(offset, point) { var self = this; var center = self.get('center'); var vector = [point.x - center.x, point.y - center.y]; if (offset) { var vecLen = vec2.length(vector); vec2.scale(vector, vector, offset / vecLen); } return vector; }; _proto.getSidePoint = function getSidePoint(point, offset) { var self = this; var vector = self.getSideVector(offset, point); return { x: point.x + vector[0], y: point.y + vector[1] }; }; _proto.getTickEnd = function getTickEnd(start, length) { var self = this; var tickLine = self.get('tickLine'); length = length ? length : tickLine.length; return self.getSidePoint(start, length); }; return Helix; }(Base); module.exports = Helix; /***/ }), /* 370 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Base = __webpack_require__(35); var Util = __webpack_require__(4); var MatrixUtil = Util.MatrixUtil; var vec2 = MatrixUtil.vec2; var Line = /*#__PURE__*/function (_Base) { _inheritsLoose(Line, _Base); function Line() { return _Base.apply(this, arguments) || this; } var _proto = Line.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Base.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { x: null, // @type {Number} 距离初始位置的x轴偏移量,仅对于左侧、右侧的纵向坐标有效 y: null, // @type {Number} 距离初始位置的y轴偏移量,仅对顶部、底部的横向坐标轴有效 line: { // @type {Attrs} 坐标轴线的图形属性,如果设置成null,则不显示轴线 lineWidth: 1, stroke: '#C0D0E0' }, tickLine: { // @type {Attrs} 标注坐标线的图形属性 lineWidth: 1, stroke: '#C0D0E0', length: 5 }, isVertical: false, start: null, // @type {Object} 起点 end: null // @type {Object} 终点 }); }; _proto._getAvgLabelLength = function _getAvgLabelLength(labelRenderer) { var labels = labelRenderer.get('group').get('children'); return labels[1].attr('x') - labels[0].attr('x'); }; _proto._getAvgLabelHeightSpace = function _getAvgLabelHeightSpace(labelRenderer) { var labels = labelRenderer.get('group').get('children'); return labels[1].attr('y') - labels[0].attr('y'); } /** * 获取距离坐标轴的向量 * @override * @param {Number} offset 偏移值 * @return {Array} 返回二维向量 */ ; _proto.getSideVector = function getSideVector(offset) { var self = this; var isVertical = self.get('isVertical'); var factor = self.get('factor'); // if (Util.isArray(offset)) { // return offset.map(value => value * factor); // } if (!Util.isNumber(offset)) { return [0, 0]; } var start = self.get('start'); var end = self.get('end'); var axisVector = self.getAxisVector(); var normal = vec2.normalize([], axisVector); var direction = false; if (isVertical && start.y < end.y || !isVertical && start.x > end.x) { direction = true; } var verticalVector = vec2.vertical([], normal, direction); return vec2.scale([], verticalVector, offset * factor); }; _proto.getAxisVector = function getAxisVector() { var start = this.get('start'); var end = this.get('end'); return [end.x - start.x, end.y - start.y]; }; _proto.getLinePath = function getLinePath() { var self = this; var start = self.get('start'); var end = self.get('end'); var path = []; path.push(['M', start.x, start.y]); path.push(['L', end.x, end.y]); return path; }; _proto.getTickEnd = function getTickEnd(start, value) { var self = this; var offsetVector = self.getSideVector(value); return { x: start.x + offsetVector[0], y: start.y + offsetVector[1] }; }; _proto.getTickPoint = function getTickPoint(tickValue) { var self = this; var start = self.get('start'); var end = self.get('end'); var rangeX = end.x - start.x; var rangeY = end.y - start.y; return { x: start.x + rangeX * tickValue, y: start.y + rangeY * tickValue }; }; _proto.renderTitle = function renderTitle() { var self = this; var title = self.get('title'); var offsetPoint = self.getTickPoint(0.5); var titleOffset = title.offset; if (Util.isNil(titleOffset)) { // 没有指定 offset 则自动计算 titleOffset = 20; var labelsGroup = self.get('labelsGroup'); if (labelsGroup) { var labelLength = self.getMaxLabelWidth(labelsGroup); var labelOffset = self.get('label').offset || self.get('_labelOffset'); titleOffset += labelLength + labelOffset; } } var textStyle = title.textStyle; var cfg = Util.mix({}, textStyle); if (title.text) { var vector = self.getAxisVector(); // 坐标轴方向的向量 if (title.autoRotate && Util.isNil(textStyle.rotate)) { // 自动旋转并且用户没有指定标题的旋转角度 var angle = 0; if (!Util.snapEqual(vector[1], 0)) { // 所有水平坐标轴,文本不转置 var v1 = [1, 0]; var v2 = [vector[0], vector[1]]; angle = vec2.angleTo(v2, v1, true); } cfg.rotate = angle * (180 / Math.PI); } else if (!Util.isNil(textStyle.rotate)) { // 用户设置了旋转角度就以用户设置的为准 cfg.rotate = textStyle.rotate / 180 * Math.PI; // 将角度转换为弧度 } var sideVector = self.getSideVector(titleOffset); var point; var position = title.position; if (position === 'start') { point = { x: this.get('start').x + sideVector[0], y: this.get('start').y + sideVector[1] }; } else if (position === 'end') { point = { x: this.get('end').x + sideVector[0], y: this.get('end').y + sideVector[1] }; } else { point = { x: offsetPoint.x + sideVector[0], y: offsetPoint.y + sideVector[1] }; } cfg.x = point.x; cfg.y = point.y; cfg.text = title.text; var group = self.get('group'); var titleShape = group.addShape('Text', { zIndex: 2, attrs: cfg }); titleShape.name = 'axis-title'; self.get('appendInfo') && titleShape.setSilent('appendInfo', self.get('appendInfo')); } }; _proto.autoRotateLabels = function autoRotateLabels() { var self = this; var labelRenderer = self.get('labelRenderer'); var title = self.get('title'); if (labelRenderer) { var labelGroup = labelRenderer.get('group'); var labels = labelGroup.get('children'); var offset = self.get('label').offset; var append = 12; var titleOffset = title ? title.offset : 48; if (titleOffset < 0) { // 如果是负的的话就不旋转 return; } var vector = self.getAxisVector(); // 坐标轴的向量,仅处理水平或者垂直的场景 var angle; var maxWidth; if (Util.snapEqual(vector[0], 0) && title && title.text) { // 坐标轴垂直,由于不知道边距,只能防止跟title重合,如果title不存在,则不自动旋转 maxWidth = self.getMaxLabelWidth(labelRenderer); if (maxWidth > titleOffset - offset - append) { angle = Math.acos((titleOffset - offset - append) / maxWidth) * -1; } } else if (Util.snapEqual(vector[1], 0) && labels.length > 1) { // 坐标轴水平,不考虑边距,根据最长的和平均值进行翻转 var avgWidth = Math.abs(self._getAvgLabelLength(labelRenderer)); maxWidth = self.getMaxLabelWidth(labelRenderer); if (maxWidth > avgWidth) { angle = Math.asin((titleOffset - offset - append) * 1.25 / maxWidth); } } if (angle) { var factor = self.get('factor'); Util.each(labels, function (label) { label.rotateAtStart(angle); if (Util.snapEqual(vector[1], 0)) { if (factor > 0) { label.attr('textAlign', 'left'); } else { label.attr('textAlign', 'right'); } } }); } } }; _proto.autoHideLabels = function autoHideLabels() { var self = this; var labelRenderer = self.get('labelRenderer'); var labelSpace; var tickStep; var append = 8; if (labelRenderer) { var labelGroup = labelRenderer.get('group'); var labels = labelGroup.get('children'); var vector = self.getAxisVector(); // 坐标轴的向量,仅处理水平或者垂直的场景 if (labels.length < 2) { return; } if (Util.snapEqual(vector[0], 0)) { // 坐标轴垂直 var maxHeight = self.getMaxLabelHeight(labelRenderer) + append; var avgHeight = Math.abs(self._getAvgLabelHeightSpace(labelRenderer)); if (maxHeight > avgHeight) { labelSpace = maxHeight; tickStep = avgHeight; } } else if (Util.snapEqual(vector[1], 0) && labels.length > 1) { // 坐标轴水平 var maxWidth = self.getMaxLabelWidth(labelRenderer) + append; var avgWidth = Math.abs(self._getAvgLabelLength(labelRenderer)); if (maxWidth > avgWidth) { labelSpace = maxWidth; tickStep = avgWidth; } } if (labelSpace && tickStep) { var ratio = Math.ceil(labelSpace / tickStep); Util.each(labels, function (label, i) { if (i % ratio !== 0) { label.attr('text', ''); } }); } } }; return Line; }(Base); module.exports = Line; /***/ }), /* 371 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var Base = __webpack_require__(35); var MatrixUtil = Util.MatrixUtil, PathUtil = Util.PathUtil; var vec2 = MatrixUtil.vec2; var Polyline = /*#__PURE__*/function (_Base) { _inheritsLoose(Polyline, _Base); function Polyline() { return _Base.apply(this, arguments) || this; } var _proto = Polyline.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Base.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { type: 'polyline' }); }; _proto.getLinePath = function getLinePath() { var self = this; var tickPoints = self.get('tickPoints'); var start = self.get('start'); var end = self.get('end'); var points = []; points.push(start.x); points.push(start.y); Util.each(tickPoints, function (tick) { points.push(tick.x); points.push(tick.y); }); points.push(end.x); points.push(end.y); var path = PathUtil.catmullRomToBezier(points); path.unshift(['M', start.x, start.y]); return path; }; _proto.getTickPoint = function getTickPoint(value, index) { var tickPoints = this.get('tickPoints'); return tickPoints[index]; }; _proto.getTickEnd = function getTickEnd(start, value, index) { var self = this; var lineAttrs = self.get('tickLine'); var tickLength = value ? value : lineAttrs.length; var offsetVector = self.getSideVector(tickLength, start, index); return { x: start.x + offsetVector[0], y: start.y + offsetVector[1] }; }; _proto.getSideVector = function getSideVector(offset, point, index) { var self = this; var preTickPoint; if (index === 0) { preTickPoint = self.get('start'); if (preTickPoint.x === point.x && preTickPoint.y === point.y) { return [0, 0]; } } else { var tickPoints = self.get('tickPoints'); preTickPoint = tickPoints[index - 1]; } var vector = [point.x - preTickPoint.x, point.y - preTickPoint.y]; var normal = vec2.normalize([], vector); var verticalVector = vec2.vertical([], normal, false); return vec2.scale([], verticalVector, offset); }; return Polyline; }(Base); module.exports = Polyline; /***/ }), /* 372 */ /***/ (function(module, exports, __webpack_require__) { module.exports = { Guide: __webpack_require__(17), Arc: __webpack_require__(373), DataMarker: __webpack_require__(374), DataRegion: __webpack_require__(375), Html: __webpack_require__(376), Image: __webpack_require__(377), Line: __webpack_require__(378), Region: __webpack_require__(379), Text: __webpack_require__(380) }; /***/ }), /* 373 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var Guide = __webpack_require__(17); var PI = Math.PI; var atan = Math.atan; function calculateAngle(point, center) { var x = point.x - center.x; var y = point.y - center.y; var deg; if (y === 0) { if (x < 0) { deg = PI / 2; } else { deg = 270 * PI / 180; } } else if (x >= 0 && y > 0) { deg = PI * 2 - atan(x / y); } else if (x <= 0 && y < 0) { deg = PI - atan(x / y); } else if (x > 0 && y < 0) { deg = PI + atan(-x / y); } else if (x < 0 && y > 0) { deg = atan(x / -y); } return deg; } var Arc = /*#__PURE__*/function (_Guide) { _inheritsLoose(Arc, _Guide); function Arc() { return _Guide.apply(this, arguments) || this; } var _proto = Arc.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Guide.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * 辅助元素类型 * @type {String} */ name: 'arc', /** * 辅助弧线的起始点 * @type {Object | Function | Array} */ start: null, /** * 辅助弧线的终止点 * @type {Object | Function | Array} */ end: null, /** * 辅助文本的样式配置 * @type {Object} */ style: { stroke: '#999', lineWidth: 1 } }); }; _proto.render = function render(coord, group) { var self = this; var start = self.parsePoint(coord, self.get('start')); var end = self.parsePoint(coord, self.get('end')); // 只要有一个点无意义,则不绘制 if (!start || !end) { return; } var coordCenter = coord.getCenter(); var radius = Math.sqrt((start.x - coordCenter.x) * (start.x - coordCenter.x) + (start.y - coordCenter.y) * (start.y - coordCenter.y)); var path; // 处理整圆的情况 var startAngle = calculateAngle(start, coordCenter); var endAngle = calculateAngle(end, coordCenter); if (endAngle < startAngle) { endAngle += PI * 2; } if (Util.isNumberEqual(start.x, end.x) && Util.isNumberEqual(start.y, end.y) && (self.get('start')[0] !== self.get('end')[0] || self.get('start')[1] !== self.get('end')[1])) { path = [['M', start.x, start.y], ['A', radius, radius, 0, 1, 1, 2 * coordCenter.x - start.x, 2 * coordCenter.y - start.y], ['A', radius, radius, 0, 1, 1, start.x, start.y]]; } else { var dAngle = (endAngle - startAngle) % (PI * 2); var largeArc = dAngle > PI ? 1 : 0; path = [['M', start.x, start.y], ['A', radius, radius, 0, largeArc, 1, end.x, end.y]]; } var arcShape = group.addShape('path', { zIndex: self.get('zIndex'), attrs: Util.mix({ path: path }, self.get('style')) }); arcShape.name = 'guide-arc'; self.get('appendInfo') && arcShape.setSilent('appendInfo', self.get('appendInfo')); self.set('el', arcShape); }; return Arc; }(Guide); module.exports = Arc; /***/ }), /* 374 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var Guide = __webpack_require__(17); var DataMarker = /*#__PURE__*/function (_Guide) { _inheritsLoose(DataMarker, _Guide); function DataMarker() { return _Guide.apply(this, arguments) || this; } var _proto = DataMarker.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Guide.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { name: 'dataMarker', zIndex: 1, top: true, position: null, style: { point: { r: 3, fill: '#FFFFFF', stroke: '#1890FF', lineWidth: 2 }, line: { stroke: '#A3B1BF', lineWidth: 1 }, text: { fill: '#000000', opacity: 0.65, fontSize: 12, textAlign: 'start' } }, // end of style display: { point: true, line: true, text: true }, lineLength: 20, direction: 'upward', autoAdjust: true }); }; _proto.render = function render(coord, group) { var self = this; var point = self.parsePoint(coord, self.get('position')); if (!point) { return; } // container var markerGroup = group.addGroup(); markerGroup.name = 'guide-data-marker'; // markerGroup.translate(point.x, point.y); var positions = self._getElementPosition(point); var display = self.get('display'); var lineShape; var textShape; // add line if (display.line) { var lineData = positions.line; lineShape = self._drawLine(lineData, markerGroup); } // add text if (display.text && self.get('content')) { var textPosition = positions.text; textShape = self._drawText(textPosition, markerGroup); } // add circle if (display.point) { var pointPoisition = positions.point; self._drawPoint(pointPoisition, markerGroup); } if (self.get('autoAdjust')) { var bbox = markerGroup.getBBox(); var minX = bbox.minX, minY = bbox.minY, maxX = bbox.maxX, maxY = bbox.maxY; var start = coord.start, end = coord.end; if (textShape) { if (minX <= start.x) { // 左侧超出 textShape.attr('textAlign', 'start'); } if (maxX >= end.x) { // 右侧超出 textShape.attr('textAlign', 'end'); } var direction = self.get('direction'); if (direction === 'upward' && minY <= end.y || direction !== 'upward' && maxY >= start.y) { // 上方或者下方超出 var textBaseline; var dir; if (direction === 'upward' && minY <= end.y) { textBaseline = 'top'; dir = 1; } else { textBaseline = 'bottom'; dir = -1; } textShape.attr('textBaseline', textBaseline); var lineLength = 0; if (self.get('display').line) { lineLength = self.get('lineLength'); var linePath = [['M', point.x, point.y], ['L', point.x, point.y + lineLength * dir]]; lineShape.attr('path', linePath); } var newY = point.y + (lineLength + 2) * dir; textShape.attr('y', newY); } } } self.get('appendInfo') && markerGroup.setSilent('appendInfo', self.get('appendInfo')); self.set('el', markerGroup); }; _proto._getElementPosition = function _getElementPosition(position) { var self = this; var x = position.x, y = position.y; var lineLength = self.get('display').line ? self.get('lineLength') : 0; var direction = self.get('direction'); var textStyle = self.get('style').text; textStyle.textBaseline = direction === 'upward' ? 'bottom' : 'top'; var dir = direction === 'upward' ? -1 : 1; var pointPoisition = { x: x, y: y }; var lineStart = { x: x, y: y }; var lineEnd = { x: x, y: lineLength * dir + y }; var textPosition = { x: x, y: (lineLength + 2) * dir + y }; return { point: pointPoisition, line: [lineStart, lineEnd], text: textPosition }; }; _proto._drawLine = function _drawLine(lineData, g) { var self = this; var lineStyle = self.get('style').line; var linePath = [['M', lineData[0].x, lineData[0].y], ['L', lineData[1].x, lineData[1].y]]; var lineShape = g.addShape('path', { attrs: Util.mix({ path: linePath }, lineStyle) }); return lineShape; }; _proto._drawText = function _drawText(position, g) { var self = this; var textStyle = this.get('style').text; var textShape = g.addShape('text', { attrs: Util.mix({ text: self.get('content') }, textStyle, position) }); return textShape; }; _proto._drawPoint = function _drawPoint(position, g) { var self = this; var pointStyle = self.get('style').point; var pointShape = g.addShape('circle', { attrs: Util.mix({}, pointStyle, position) }); return pointShape; }; return DataMarker; }(Guide); module.exports = DataMarker; /***/ }), /* 375 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var Helper = __webpack_require__(190); var Guide = __webpack_require__(17); var DataRegion = /*#__PURE__*/function (_Guide) { _inheritsLoose(DataRegion, _Guide); function DataRegion() { return _Guide.apply(this, arguments) || this; } var _proto = DataRegion.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Guide.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { name: 'dataRegion', start: null, // 只支持数值 end: null, // 只支持数值 content: '', // 文本内容 style: { region: { lineWidth: 0, fill: '#000000', opacity: 0.04 }, text: { textAlign: 'center', textBaseline: 'bottom', fontSize: 12, fill: 'rgba(0, 0, 0, .65)' } } }); }; _proto.render = function render(coord, group, data) { var self = this; // draw region var lineLength = self.get('lineLength') || 0; // TODO: 如何命名 var regionData = self._getRegionData(coord, data); if (!regionData.length) return; var regionBBox = self._getBBox(regionData); var path = []; path.push(['M', regionData[0].x, regionBBox.yMin - lineLength]); for (var i = 0, len = regionData.length; i < len; i++) { var p = ['L', regionData[i].x, regionData[i].y]; path.push(p); } path.push(['L', regionData[regionData.length - 1].x, regionBBox.yMin - lineLength]); // draw var style = self.get('style'); var regionStyle = style.region; // 兼容之前的写法 var textStyle = style.text; var regionGroup = group.addGroup(); regionGroup.name = 'guide-data-region'; regionGroup.addShape('path', { attrs: Util.mix({ path: path }, regionStyle) }); var content = self.get('content'); if (content) { regionGroup.addShape('Text', { attrs: Util.mix({ x: (regionBBox.xMin + regionBBox.xMax) / 2, y: regionBBox.yMin - lineLength, text: content }, textStyle) }); } self.get('appendInfo') && regionGroup.setSilent('appendInfo', self.get('appendInfo')); self.set('el', regionGroup); }; _proto._getRegionData = function _getRegionData(coord, data) { var self = this; var start = self.get('start'); var end = self.get('end'); var xField = Helper.getFirstScale(self.get('xScales')).field; var yField = Helper.getFirstScale(self.get('yScales')).field; var startXValue = Util.isArray(start) ? start[0] : start[xField]; var endXValue = Util.isArray(end) ? end[0] : end[xField]; var startIndex; var arr = []; for (var i = 0, len = data.length; i < len; i++) { var item = data[i]; if (item[xField] === startXValue) { startIndex = i; } if (i >= startIndex) { var point = self.parsePoint(coord, [item[xField], item[yField]]); // 判断是否是有效点 point && arr.push(point); } if (item[xField] === endXValue) { break; } } return arr; }; _proto._getBBox = function _getBBox(data) { var xs = []; var ys = []; for (var i = 0; i < data.length; i++) { xs.push(data[i].x); ys.push(data[i].y); } var xRange = Util.arrayUtil.getRange(xs); var yRange = Util.arrayUtil.getRange(ys); return { xMin: xRange.min, xMax: xRange.max, yMin: yRange.min, yMax: yRange.max }; }; return DataRegion; }(Guide); module.exports = DataRegion; /***/ }), /* 376 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var DomUtil = Util.DomUtil; var Guide = __webpack_require__(17); var Html = /*#__PURE__*/function (_Guide) { _inheritsLoose(Html, _Guide); function Html() { return _Guide.apply(this, arguments) || this; } var _proto = Html.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Guide.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { name: 'html', zIndex: 7, position: null, /** * Horizontal alignment, can be 'left'、'middle'、'right' * @type {String} */ alignX: 'middle', /** * vertical alignment, can be 'top'、'middle'、'bottom' * @type {String} */ alignY: 'middle', /** * Horizontal offset * @type {Number} */ offsetX: null, /** * Vertical offset * @type {Number} */ offsetY: null, /** * html content *@type {String | Function} */ html: null }); } /** * render Html Guide * @override * @param {Coordinate} coord the instance of Coordinate class * @param {Container} container the container which contain the guide component */ ; _proto.render = function render(coord, container) { var self = this; var position = self.parsePoint(coord, self.get('position')); if (!position) { return; } var parentNode = container.get('canvas').get('el').parentNode; var wrapperNode = DomUtil.createDom('
    '); parentNode.appendChild(wrapperNode); var html = self.get('htmlContent') || self.get('html'); if (Util.isFunction(html)) { var xScales = self.get('xScales'); var yScales = self.get('yScales'); html = html(xScales, yScales); } var htmlNode = DomUtil.createDom(html); wrapperNode.appendChild(htmlNode); DomUtil.modifyCSS(wrapperNode, { position: 'absolute' // to fix dom in the document stream to get the true width }); self._setDomPosition(wrapperNode, htmlNode, position); self.set('el', wrapperNode); }; _proto._setDomPosition = function _setDomPosition(parentDom, childDom, point) { var self = this; var alignX = self.get('alignX'); var alignY = self.get('alignY'); var domWidth = DomUtil.getOuterWidth(childDom); var domHeight = DomUtil.getOuterHeight(childDom); var position = { x: point.x, y: point.y }; if (alignX === 'middle' && alignY === 'top') { position.x -= Math.round(domWidth / 2); } else if (alignX === 'middle' && alignY === 'bottom') { position.x -= Math.round(domWidth / 2); position.y -= Math.round(domHeight); } else if (alignX === 'left' && alignY === 'bottom') { position.y -= Math.round(domHeight); } else if (alignX === 'left' && alignY === 'middle') { position.y -= Math.round(domHeight / 2); } else if (alignX === 'left' && alignY === 'top') { position.x = point.x; position.y = point.y; } else if (alignX === 'right' && alignY === 'bottom') { position.x -= Math.round(domWidth); position.y -= Math.round(domHeight); } else if (alignX === 'right' && alignY === 'middle') { position.x -= Math.round(domWidth); position.y -= Math.round(domHeight / 2); } else if (alignX === 'right' && alignY === 'top') { position.x -= Math.round(domWidth); } else { // 默认位于中心点 position.x -= Math.round(domWidth / 2); position.y -= Math.round(domHeight / 2); } var offsetX = self.get('offsetX'); if (offsetX) { position.x += offsetX; } var offsetY = self.get('offsetY'); if (offsetY) { position.y += offsetY; } DomUtil.modifyCSS(parentDom, { top: Math.round(position.y) + 'px', left: Math.round(position.x) + 'px', visibility: 'visible', zIndex: self.get('zIndex') }); } /** * clear html guide * @override */ ; _proto.clear = function clear() { var self = this; var el = self.get('el'); el && el.parentNode && el.parentNode.removeChild(el); }; return Html; }(Guide); module.exports = Html; /***/ }), /* 377 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var Guide = __webpack_require__(17); var Image = /*#__PURE__*/function (_Guide) { _inheritsLoose(Image, _Guide); function Image() { return _Guide.apply(this, arguments) || this; } var _proto = Image.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Guide.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { type: 'image', /** * the start of image * @type {Object | Function | Array} */ start: null, /** * the end of image * @type {Object | Function | Array} */ end: null, /** * image url * @type {String} */ src: null, /** * Horizontal offset * @type {Number} */ offsetX: null, /** * Vertical offset * @type {Number} */ offsetY: null }); }; _proto.render = function render(coord, group) { var self = this; var start = self.parsePoint(coord, self.get('start')); if (!start) { return; } var cfg = { x: start.x, y: start.y }; cfg.img = self.get('src'); if (!self.get('end')) { // 如果咩有指定结束点,则 start 为图片的左上角坐标 cfg.width = self.get('width') || 32; cfg.height = self.get('height') || 32; } else { var end = self.parsePoint(coord, self.get('end')); if (!end) { return; } // cfg.width = Math.abs(end.x - start.x); // cfg.height = Math.abs(end.y - start.y); cfg.width = end.x - start.x; cfg.height = end.y - start.y; } if (self.get('offsetX')) { cfg.x += self.get('offsetX'); } if (self.get('offsetY')) { cfg.y += self.get('offsetY'); } var imgGuide = group.addShape('Image', { zIndex: 1, attrs: cfg }); imgGuide.name = 'guide-image'; self.get('appendInfo') && imgGuide.setSilent('appendInfo', self.get('appendInfo')); self.set('el', imgGuide); }; return Image; }(Guide); module.exports = Image; /***/ }), /* 378 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var Guide = __webpack_require__(17); var vec2 = Util.MatrixUtil.vec2; var _require = __webpack_require__(16), FONT_FAMILY = _require.FONT_FAMILY; var Line = /*#__PURE__*/function (_Guide) { _inheritsLoose(Line, _Guide); function Line() { return _Guide.apply(this, arguments) || this; } var _proto = Line.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Guide.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * 辅助元素类型 * @type {String} */ name: 'line', /** * 辅助线的起点位置 * @type {Object | Function | Array} */ start: null, /** * 辅助线的终点位置 * @type {Object | Function | Array} */ end: null, /** * 辅助线的图形样式 * @type {Object} */ lineStyle: { stroke: '#000', lineWidth: 1 }, /** * 辅助文本配置 * @type {Object} */ text: { position: 'end', // 文本的显示位置: start / center / end / 百分比 autoRotate: true, // 文本是否沿着辅助线的方向自动旋转 style: { fill: '#999', fontSize: 12, fontWeight: 500, fontFamily: FONT_FAMILY }, // 辅助文本的样式 content: null // 辅助文本的文字 } }); }; _proto.render = function render(coord, group) { var self = this; var start = self.parsePoint(coord, self.get('start')); var end = self.parsePoint(coord, self.get('end')); if (!start || !end) { return; } var guideLineGroup = group.addGroup({ viewId: group.get('viewId') }); self._drawLines(start, end, guideLineGroup); var text = self.get('text'); if (text && text.content) { self._drawText(start, end, guideLineGroup); } self.set('el', guideLineGroup); }; _proto._drawLines = function _drawLines(start, end, group) { var path = [['M', start.x, start.y], ['L', end.x, end.y]]; var guideLine = group.addShape('Path', { attrs: Util.mix({ path: path }, this.get('lineStyle')) }); guideLine.name = 'guide-line'; this.get('appendInfo') && guideLine.setSilent('appendInfo', this.get('appendInfo')); }; _proto._drawText = function _drawText(start, end, group) { var textCfg = this.get('text'); var position = textCfg.position; var textStyle = textCfg.style || {}; var percent; if (position === 'start') { percent = 0; } else if (position === 'center') { percent = 0.5; } else if (Util.isString(position) && position.indexOf('%') !== -1) { percent = parseInt(position, 10) / 100; } else if (Util.isNumber(position)) { percent = position; } else { percent = 1; } if (percent > 1 || percent < 0) { percent = 1; } var cfg = { x: start.x + (end.x - start.x) * percent, y: start.y + (end.y - start.y) * percent }; if (textCfg.offsetX) { // 设置了偏移量 cfg.x += textCfg.offsetX; } if (textCfg.offsetY) { // 设置了偏移量 cfg.y += textCfg.offsetY; } cfg.text = textCfg.content; cfg = Util.mix({}, cfg, textStyle); if (textCfg.autoRotate && Util.isNil(textStyle.rotate)) { // 自动旋转且用户没有设置旋转角度 var angle = vec2.angleTo([end.x - start.x, end.y - start.y], [1, 0], 1); cfg.rotate = angle; } else if (!Util.isNil(textStyle.rotate)) { // 用户设置了旋转角度 cfg.rotate = textStyle.rotate * Math.PI / 180; } var shape = group.addShape('Text', { attrs: cfg }); shape.name = 'guide-line-text'; this.get('appendInfo') && shape.setSilent('appendInfo', this.get('appendInfo')); }; return Line; }(Guide); module.exports = Line; /***/ }), /* 379 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var Guide = __webpack_require__(17); var Region = /*#__PURE__*/function (_Guide) { _inheritsLoose(Region, _Guide); function Region() { return _Guide.apply(this, arguments) || this; } var _proto = Region.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Guide.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { name: 'region', zIndex: 1, start: null, end: null, style: { lineWidth: 0, fill: '#CCD7EB', opacity: 0.4 } }); }; _proto.render = function render(coord, group) { var self = this; var rectStyle = self.get('style'); var path = self._getPath(coord); if (!path.length) { // path 为空时不绘制 return; } var regionGroup = group.addShape('path', { zIndex: self.get('zIndex'), attrs: Util.mix({ path: path }, rectStyle) }); regionGroup.name = 'guide-region'; self.get('appendInfo') && regionGroup.setSilent('appendInfo', self.get('appendInfo')); self.set('el', regionGroup); }; _proto._getPath = function _getPath(coord) { var self = this; var start = self.parsePoint(coord, self.get('start')); var end = self.parsePoint(coord, self.get('end')); if (!start || !end) { return []; } var path = [['M', start.x, start.y], ['L', end.x, start.y], ['L', end.x, end.y], ['L', start.x, end.y], ['z']]; return path; }; return Region; }(Guide); module.exports = Region; /***/ }), /* 380 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var Guide = __webpack_require__(17); var Text = /*#__PURE__*/function (_Guide) { _inheritsLoose(Text, _Guide); function Text() { return _Guide.apply(this, arguments) || this; } var _proto = Text.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Guide.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * 辅助元素类型 * @type {String} */ name: 'text', /** * 辅助文本的位置 * @type {Object | Function | Array} */ position: null, /** * 辅助文本的显示文字 * @type {String} */ content: null, /** * 辅助文本的样式配置 * @type {Object} */ style: { fill: '#999', fontSize: 12, fontWeight: 500, textAlign: 'center' }, /** * x 方向的偏移量 * @type {Number} */ offsetX: null, /** * y 方向的偏移量 * @type {Number} */ offsetY: null, top: true }); }; _proto.render = function render(coord, group) { var self = this; var point = self.parsePoint(coord, self.get('position')); if (!point) { return; } var textStyle = Util.mix({}, self.get('style')); var offsetX = self.get('offsetX'); var offsetY = self.get('offsetY'); if (offsetX) { point.x += offsetX; } if (offsetY) { point.y += offsetY; } if (textStyle.rotate) { textStyle.rotate = textStyle.rotate * Math.PI / 180; // 将角度转换为弧度 } var guideText = group.addShape('Text', { zIndex: self.get('zIndex'), attrs: Util.mix({ text: self.get('content') }, textStyle, point) }); guideText.name = 'guide-text'; self.get('appendInfo') && guideText.setSilent('appendInfo', self.get('appendInfo')); self.set('el', guideText); }; return Text; }(Guide); module.exports = Text; /***/ }), /* 381 */ /***/ (function(module, exports, __webpack_require__) { var Label = __webpack_require__(188); module.exports = Label; /***/ }), /* 382 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview The entry of legend * @author sima.zhang */ module.exports = { Category: __webpack_require__(191), // 分类图例 CatHtml: __webpack_require__(193), // 分类图例 CatPageHtml: __webpack_require__(383), // 分类图例 // Tail: require('./tail'), // 尾部跟随图例 Color: __webpack_require__(384), // 颜色图例 Size: __webpack_require__(386), // 大小图例(适用于除映射点大小以外的其他大小) CircleSize: __webpack_require__(387) // 点大小图例 }; /***/ }), /* 383 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var CatHtml = __webpack_require__(193); var _require = __webpack_require__(16), FONT_FAMILY = _require.FONT_FAMILY; var DomUtil = Util.DomUtil; var LIST_CLASS = 'g2-legend-list'; var SLIP_CLASS = 'g2-slip'; var CARET_UP_CLASS = 'g2-caret-up'; var CARET_DOWN_CLASS = 'g2-caret-down'; var ENABLED_CARET_COLOR = 'rgba(0,0,0,0.65)'; var DISABLED_CARET_COLOR = 'rgba(0,0,0,0.25)'; function findNodeByClass(node, className) { return node.getElementsByClassName(className)[0]; } var CatPageHtml = /*#__PURE__*/function (_CatHtml) { _inheritsLoose(CatPageHtml, _CatHtml); function CatPageHtml() { return _CatHtml.apply(this, arguments) || this; } var _proto = CatPageHtml.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _CatHtml.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * type标识 * @type {String} */ type: 'category-page-legend', /** * html 容器 * @type {DOM} */ container: null, /** * 向上 / 下翻页图标的样式 * @type {ATTRS} */ caretStyle: { fill: 'rgba(0,0,0,0.65)' }, /** * 页码文字的样式 * @type {ATTRS} */ pageNumStyle: { display: 'inline-block', fontSize: '12px', fontFamily: FONT_FAMILY, cursor: 'default' }, /** * 翻页块 DOM 的样式 * @type {ATTRS} */ slipDomStyle: { width: 'auto', height: 'auto', position: 'absolute' }, /** * 翻页块 DOM * @type {String} */ slipTpl: '
    ' + '' + '

    1

    ' + '

    /2

    ' + '' + '
    ', /** * 翻页块的宽度,用于设置翻页块相对于 legend 的位置 * @type {Number} */ slipWidth: 65, /** * legend 内容超出容器的处理方式 * @type {String} */ legendOverflow: 'unset' }); }; _proto.render = function render() { _CatHtml.prototype._renderHTML.call(this); this._renderFlipPage(); }; _proto._renderFlipPage = function _renderFlipPage() { var legendWrapper = this.get('legendWrapper'); // ul var itemListDom = findNodeByClass(legendWrapper, LIST_CLASS); var position = this.get('position'); var layout = this.get('layout'); var isVertical = position === 'right' || position === 'left' || layout === 'vertical'; var itemDisplay = isVertical ? 'block' : 'inline-block'; var legengWrapperHeight = legendWrapper.offsetHeight; // 翻页 if (legendWrapper.scrollHeight > legengWrapperHeight) { // append a slip div var slipTpl = this.get('slipTpl'); var slipDom = DomUtil.createDom(slipTpl); var caretUpDom = findNodeByClass(slipDom, CARET_UP_CLASS); var caretDownDom = findNodeByClass(slipDom, CARET_DOWN_CLASS); DomUtil.modifyCSS(caretUpDom, this.get('caretStyle')); DomUtil.modifyCSS(caretUpDom, { fill: 'rgba(0,0,0,0.25)' }); DomUtil.modifyCSS(caretDownDom, this.get('caretStyle')); var curPageNumDom = findNodeByClass(slipDom, 'cur-pagenum'); var totalPageNumDom = findNodeByClass(slipDom, 'next-pagenum'); var pageNumStyle = this.get('pageNumStyle'); DomUtil.modifyCSS(curPageNumDom, Util.mix({}, pageNumStyle, { paddingLeft: '10px' })); DomUtil.modifyCSS(totalPageNumDom, Util.mix({}, pageNumStyle, { opacity: 0.3, paddingRight: '10px' })); // layout at the center-bottom of the legendWrapper DomUtil.modifyCSS(slipDom, Util.mix({}, this.get('slipDomStyle'), isVertical ? { top: legengWrapperHeight + 'px' } : { right: 0, top: '50%', // 横向布局的时候,分页在右侧居中对齐 transform: 'translate(0, -50%)' })); legendWrapper.style.overflow = this.get('legendOverflow'); legendWrapper.appendChild(slipDom); if (!isVertical) { var legendListMaxWidth = Math.max(legendWrapper.offsetWidth - 10 - slipDom.offsetWidth, 0); // 横向布局的时候更新list的宽度 DomUtil.modifyCSS(itemListDom, { maxWidth: legendListMaxWidth + "px" }); } var li = itemListDom.childNodes; var curHeight = 0; // find the total page number var pages = 1; var blockLi = []; for (var i = 0; i < li.length; i++) { li[i].style.display = itemDisplay; curHeight = li[i].offsetTop + li[i].offsetHeight; if (curHeight > legengWrapperHeight) { pages++; blockLi.forEach(function (bl) { bl.style.display = 'none'; }); blockLi = []; } blockLi.push(li[i]); } totalPageNumDom.innerText = '/' + pages; // initialize the page li.forEach(function (l) { l.style.display = itemDisplay; curHeight = l.offsetTop + l.offsetHeight; if (curHeight > legengWrapperHeight) { l.style.display = 'none'; } }); // 上翻事件 caretUpDom.addEventListener('click', function () { // it is the 1st page if (li[0].style.display === itemDisplay) return; // otherwise var firstDisplayItemIdx = -1; li.forEach(function (l, i) { if (l.style.display === itemDisplay) { firstDisplayItemIdx = firstDisplayItemIdx === -1 ? i : firstDisplayItemIdx; l.style.display = 'none'; } }); for (var _i = firstDisplayItemIdx - 1; _i >= 0; _i--) { li[_i].style.display = itemDisplay; curHeight = li[firstDisplayItemIdx - 1].offsetTop + li[firstDisplayItemIdx - 1].offsetHeight; li[_i].style.display = 'none'; if (curHeight <= legengWrapperHeight) { li[_i].style.display = itemDisplay; } else break; } // change the page number var currentPage = Number.parseInt(curPageNumDom.innerText, 10) - 1; if (currentPage === 1) { caretUpDom.style.fill = DISABLED_CARET_COLOR; } else { caretUpDom.style.fill = ENABLED_CARET_COLOR; } caretDownDom.style.fill = ENABLED_CARET_COLOR; curPageNumDom.innerText = currentPage; }); // 下翻事件 caretDownDom.addEventListener('click', function () { // it is the last page if (li[li.length - 1].style.display === itemDisplay) return; // otherwise var lastDisplayItemIdx = -1; li.forEach(function (l, i) { if (l.style.display === itemDisplay) { lastDisplayItemIdx = i; l.style.display = 'none'; } }); for (var _i2 = lastDisplayItemIdx + 1; _i2 < li.length; _i2++) { li[_i2].style.display = itemDisplay; curHeight = li[_i2].offsetTop + li[_i2].offsetHeight; li[_i2].style.display = 'none'; if (curHeight <= legengWrapperHeight) li[_i2].style.display = itemDisplay;else break; } // change the page number var currentPage = Number.parseInt(curPageNumDom.innerText, 10) + 1; if (currentPage === pages) { caretDownDom.style.fill = DISABLED_CARET_COLOR; } else { caretDownDom.style.fill = ENABLED_CARET_COLOR; } caretUpDom.style.fill = ENABLED_CARET_COLOR; curPageNumDom.innerText = currentPage; }); this.set('slipDom', slipDom); } }; _proto.destroy = function destroy() { var slipDom = this.get('slipDom'); if (slipDom && slipDom.parentNode) { slipDom.parentNode.removeChild(slipDom); } _CatHtml.prototype.destroy.call(this); }; return CatPageHtml; }(CatHtml); module.exports = CatPageHtml; /***/ }), /* 384 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @fileOverview The class of the gradient color legend * @author sima.zhang */ var _require = __webpack_require__(104), ColorUtil = _require.ColorUtil; // TODO:ColorUtil 包需要从 attr 包中抽离 var Util = __webpack_require__(4); var Continuous = __webpack_require__(97); var Color = /*#__PURE__*/function (_Continuous) { _inheritsLoose(Color, _Continuous); function Color() { return _Continuous.apply(this, arguments) || this; } var _proto = Color.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Continuous.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * 类型 * @type {String} */ type: 'color-legend', /** * 布局方式 * horizontal 水平 * vertical 垂直 * @type {String} */ layout: 'vertical', /** * 两头滑块的样式 * @type {object} */ triggerAttr: { fill: '#fff', shadowOffsetX: -2, shadowOffsetY: 2, shadowBlur: 10, shadowColor: '#ccc', radius: 3 }, /** * 同一分段是否使用相同颜色而不使用渐变色,在 slidable = false 时生效 * @type {boolean} */ isSegment: false }); }; _proto._setPercentage = function _setPercentage() { var items = this.get('items'); if (items[0].percentage) return; var min = items[0].value; var max = items[items.length - 1].value; Util.each(items, function (it) { it.percentage = (it.value - min) / (max - min); }); return; } // render the slider while slidable === true ; _proto._renderSliderShape = function _renderSliderShape() { this._setPercentage(); var slider = this.get('slider'); var backgroundElement = slider.get('backgroundElement'); var width = this.get('width'); var height = this.get('height'); var layout = this.get('layout'); var items = this.get('items'); var fill = ''; var rgbColor; // gradient color distributed according to the percentage if (layout === 'vertical') { fill += 'l (90) '; Util.each(items, function (v) { rgbColor = ColorUtil.toRGB(v.color); fill += 1 - v.percentage + ':' + rgbColor + ' '; }); } else { fill += 'l (0) '; Util.each(items, function (v) { rgbColor = ColorUtil.toRGB(v.color); fill += v.percentage + ':' + rgbColor + ' '; }); } return this._addMiddleBar(backgroundElement, 'Rect', { x: 0, y: 0, width: width, height: height, fill: fill, strokeOpacity: 0 }); } // render the silder while slidable === false ; _proto._renderUnslidable = function _renderUnslidable() { this._setPercentage(); var titleShape = this.get('titleShape'); var titleGap = this.get('titleGap'); titleGap = titleShape ? titleShape.getBBox().height + titleGap : titleGap; var width = this.get('width'); var height = this.get('height'); var layout = this.get('layout'); var items = this.get('items'); var fill = ''; var rgbColor; var path = []; var group = this.get('group'); var bgGroup = group.addGroup(); var isize = items.length; // gradient color distributed according to the percentage if (layout === 'vertical') { fill += 'l (90) '; for (var i = 0; i < isize; i += 1) { if (i !== 0 && i !== isize - 1) { path.push(['M', 0, height - items[i].percentage * height]); path.push(['L', width, height - items[i].percentage * height]); } rgbColor = ColorUtil.toRGB(items[i].color); fill += 1 - items[i].percentage + ':' + rgbColor + ' '; if (this.get('isSegment') && i > 0) { // one color instead of gradient color for a block while isSegment === true var preRgbColor = ColorUtil.toRGB(items[i - 1].color); fill += 1 - items[i].percentage + ':' + preRgbColor + ' '; } bgGroup.addShape('text', { attrs: Util.mix({}, { x: width + this.get('textOffset') / 2, y: height - items[i].percentage * height, text: this._formatItemValue(items[i].value) + '' // 以字符串格式展示 }, this.get('textStyle'), { textAlign: 'start' }) }); } } else { // horizontal fill += 'l (0) '; for (var _i = 0; _i < isize; _i += 1) { if (_i !== 0 && _i !== isize - 1) { path.push(['M', items[_i].percentage * width, 0]); path.push(['L', items[_i].percentage * width, height]); } rgbColor = ColorUtil.toRGB(items[_i].color); if (this.get('isSegment') && _i > 0) { var _preRgbColor = ColorUtil.toRGB(items[_i - 1].color); fill += items[_i].percentage + ':' + _preRgbColor + ' '; } fill += items[_i].percentage + ':' + rgbColor + ' '; bgGroup.addShape('text', { attrs: Util.mix({}, { x: items[_i].percentage * width, y: height + 5 + this.get('textOffset'), text: this._formatItemValue(items[_i].value) + '' // 以字符串格式展示 }, this.get('textStyle')) }); } } bgGroup.addShape('rect', { attrs: { x: 0, y: 0, width: width, height: height, fill: fill, strokeOpacity: 0 } }); // the white line segment to seperate color blocks bgGroup.addShape('path', { attrs: Util.mix({ path: path }, this.get('lineStyle')) }); bgGroup.move(0, titleGap); }; return Color; }(Continuous); module.exports = Color; /***/ }), /* 385 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview The class of slider * @author sima.zhang */ var Util = __webpack_require__(4); var DomUtil = Util.DomUtil; var Group = Util.Group; var Slider = function Slider(cfg) { Slider.superclass.constructor.call(this, cfg); }; Util.extend(Slider, Group); Util.augment(Slider, { getDefaultCfg: function getDefaultCfg() { return { /** * 范围 * @type {Array} */ range: null, /** * 中滑块属性 * 透明的,用于用户交互 * @type {ATTRS} */ middleAttr: { fill: '#fff', fillOpacity: 0 }, /** * 背景 * @type {G-Element} */ backgroundElement: null, /** * 下滑块 * @type {G-Element} */ minHandleElement: null, /** * 上滑块 * @type {G-Element} */ maxHandleElement: null, /** * 中块, * 透明的,用于用户交互 * @type {G-Element} */ middleHandleElement: null, /** * 当前的激活的元素 * @type {G-Element} */ currentTarget: null, /** * 布局方式: horizontal,vertical * @type {String} */ layout: 'vertical', /** * 宽 * @type {Number} */ width: null, /** * 高 * @type {Number} */ height: null, /** * 当前的PageX * @type {Number} */ pageX: null, /** * 当前的PageY * @type {Number} */ pageY: null }; }, // arrange the zindex and cursors of each element _beforeRenderUI: function _beforeRenderUI() { var layout = this.get('layout'); var backgroundElement = this.get('backgroundElement'); var minHandleElement = this.get('minHandleElement'); var maxHandleElement = this.get('maxHandleElement'); var middleHandleElement = this.addShape('rect', { attrs: this.get('middleAttr') }); var trigerCursor = layout === 'vertical' ? 'ns-resize' : 'ew-resize'; this.add([backgroundElement, minHandleElement, maxHandleElement]); this.set('middleHandleElement', middleHandleElement); backgroundElement.set('zIndex', 0); middleHandleElement.set('zIndex', 1); minHandleElement.set('zIndex', 2); maxHandleElement.set('zIndex', 2); middleHandleElement.attr('cursor', 'move'); minHandleElement.attr('cursor', trigerCursor); maxHandleElement.attr('cursor', trigerCursor); this.sort(); }, // rendering _renderUI: function _renderUI() { if (this.get('layout') === 'horizontal') { this._renderHorizontal(); } else { this._renderVertical(); } }, _transform: function _transform(layout) { var range = this.get('range'); var minRatio = range[0] / 100; var maxRatio = range[1] / 100; var width = this.get('width'); var height = this.get('height'); var minHandleElement = this.get('minHandleElement'); var maxHandleElement = this.get('maxHandleElement'); var middleHandleElement = this.get('middleHandleElement'); minHandleElement.resetMatrix(); maxHandleElement.resetMatrix(); if (layout === 'horizontal') { middleHandleElement.attr({ x: width * minRatio, y: 0, width: (maxRatio - minRatio) * width, height: height }); minHandleElement.translate(minRatio * width, height); maxHandleElement.translate(maxRatio * width, height); } else { middleHandleElement.attr({ x: 0, y: height * (1 - maxRatio), width: width, height: (maxRatio - minRatio) * height }); minHandleElement.translate(1, (1 - minRatio) * height); maxHandleElement.translate(1, (1 - maxRatio) * height); } }, _renderHorizontal: function _renderHorizontal() { this._transform('horizontal'); }, _renderVertical: function _renderVertical() { this._transform('vertical'); }, _bindUI: function _bindUI() { this.on('mousedown', Util.wrapBehavior(this, '_onMouseDown')); }, // if the target matches name _isElement: function _isElement(target, name) { var element = this.get(name); if (target === element) { return true; } if (element.isGroup) { var elementChildren = element.get('children'); return elementChildren.indexOf(target) > -1; } return false; }, // get the result range after adding diff to range // insure that the result out of the interval [0, 100] _getRange: function _getRange(diff, range) { var rst = diff + range; rst = rst > 100 ? 100 : rst; rst = rst < 0 ? 0 : rst; return rst; }, _updateStatus: function _updateStatus(dim, ev) { var totalLength = dim === 'x' ? this.get('width') : this.get('height'); dim = Util.upperFirst(dim); var range = this.get('range'); var page = this.get('page' + dim); var currentTarget = this.get('currentTarget'); var rangeStash = this.get('rangeStash'); var layout = this.get('layout'); var sign = layout === 'vertical' ? -1 : 1; var currentPage = ev['page' + dim]; // the distance of the mouse dragging var diffPage = currentPage - page; var diffRange = diffPage / totalLength * 100 * sign; var diffStashRange; // the min and max trigger overlap, range[0] and range[1] change together if (range[1] <= range[0]) { if (this._isElement(currentTarget, 'minHandleElement') || this._isElement(currentTarget, 'maxHandleElement')) { range[0] = this._getRange(diffRange, range[0]); range[1] = this._getRange(diffRange, range[0]); } } else { // user drags the min trigger if (this._isElement(currentTarget, 'minHandleElement')) { range[0] = this._getRange(diffRange, range[0]); } // user drags the max trigger if (this._isElement(currentTarget, 'maxHandleElement')) { range[1] = this._getRange(diffRange, range[1]); } } // the user drags the middle bar if (this._isElement(currentTarget, 'middleHandleElement')) { // the diffrence between min and max trigger while mouse down diffStashRange = rangeStash[1] - rangeStash[0]; range[0] = this._getRange(diffRange, range[0]); // keep the diffStashRange range[1] = range[0] + diffStashRange; if (range[1] > 100) { range[1] = 100; range[0] = range[1] - diffStashRange; } } this.emit('sliderchange', { range: range }); this.set('page' + dim, currentPage); this._renderUI(); this.get('canvas').draw(); // need delete return; }, // the listener of mouse down _onMouseDown: function _onMouseDown(ev) { var currentTarget = ev.currentTarget; var originEvent = ev.event; var range = this.get('range'); originEvent.stopPropagation(); originEvent.preventDefault(); this.set('pageX', originEvent.pageX); this.set('pageY', originEvent.pageY); this.set('currentTarget', currentTarget); // stash the range this.set('rangeStash', [range[0], range[1]]); this._bindCanvasEvents(); }, _bindCanvasEvents: function _bindCanvasEvents() { var containerDOM = this.get('canvas').get('containerDOM'); // this.on('mousemove', Util.wrapBehavior(this, '_onCanvasMouseMove')); this.onMouseMoveListener = DomUtil.addEventListener(containerDOM, 'mousemove', Util.wrapBehavior(this, '_onCanvasMouseMove')); this.onMouseUpListener = DomUtil.addEventListener(containerDOM, 'mouseup', Util.wrapBehavior(this, '_onCanvasMouseUp')); this.onMouseLeaveListener = DomUtil.addEventListener(containerDOM, 'mouseleave', Util.wrapBehavior(this, '_onCanvasMouseUp')); }, // listener of mouse click and move = drag _onCanvasMouseMove: function _onCanvasMouseMove(ev) { if (!this._mouseOutArea(ev)) { var layout = this.get('layout'); if (layout === 'horizontal') { this._updateStatus('x', ev); } else { this._updateStatus('y', ev); } } }, // listener of mouse up _onCanvasMouseUp: function _onCanvasMouseUp() { this._removeDocumentEvents(); }, // remove listeners _removeDocumentEvents: function _removeDocumentEvents() { this.onMouseMoveListener.remove(); this.onMouseUpListener.remove(); }, // if the mouse is out of the area _mouseOutArea: function _mouseOutArea(ev) { var el = this.get('canvas').get('el'); var el_bbox = el.getBoundingClientRect(); var parent = this.get('parent'); var bbox = parent.getBBox(); var left = parent.attr('matrix')[6]; var top = parent.attr('matrix')[7]; var right = left + bbox.width; var bottom = top + bbox.height; var mouseX = ev.clientX - el_bbox.x; var mouseY = ev.clientY - el_bbox.y; if (mouseX < left || mouseX > right || mouseY < top || mouseY > bottom) { return true; } return false; } }); module.exports = Slider; /***/ }), /* 386 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @fileOverview The class of the gradient color legend * @author sima.zhang */ var Util = __webpack_require__(4); var Continuous = __webpack_require__(97); var Size = /*#__PURE__*/function (_Continuous) { _inheritsLoose(Size, _Continuous); function Size() { return _Continuous.apply(this, arguments) || this; } var _proto = Size.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Continuous.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * 类型 * @type {String} */ type: 'size-legend', width: 100, height: 200, /** * 不能滑动时圈的样式 * @type {ATTRS} */ _unslidableElementStyle: { fill: '#4E7CCC', fillOpacity: 1 }, /** * 中间 bar 的前景颜色 * @type {ATTRS} */ frontMiddleBarStyle: { fill: 'rgb(64, 141, 251)' } }); } // render the slider shape ; _proto._renderSliderShape = function _renderSliderShape() { var slider = this.get('slider'); var backgroundElement = slider.get('backgroundElement'); var layout = this.get('layout'); var width = this.get('width'); var height = this.get('height'); // const x = minRadius; var y = this.get('height') / 2; var frontMiddleBarStyle = this.get('frontMiddleBarStyle'); // background of middle bar var points = layout === 'vertical' ? [[0, 0], [width, 0], [width, height], [width - 4, height]] : [[0, y + height / 2], [0, y + height / 2 - 4], [width, y - height / 2], [width, y + height / 2]]; return this._addMiddleBar(backgroundElement, 'Polygon', Util.mix({ points: points }, frontMiddleBarStyle)); } // render the middle bar while slidable === false, // there are no triggers for this situation ; _proto._renderUnslidable = function _renderUnslidable() { var layout = this.get('layout'); var width = this.get('width'); var height = this.get('height'); var frontMiddleBarStyle = this.get('frontMiddleBarStyle'); var points = layout === 'vertical' ? [[0, 0], [width, 0], [width, height], [width - 4, height]] : [[0, height], [0, height - 4], [width, 0], [width, height]]; var group = this.get('group'); var bgGroup = group.addGroup(); bgGroup.addShape('Polygon', { attrs: Util.mix({ points: points }, frontMiddleBarStyle) }); var minText = this._formatItemValue(this.get('firstItem').value); var maxText = this._formatItemValue(this.get('lastItem').value); if (this.get('layout') === 'vertical') { this._addText(width + 10, height - 3, minText); // min this._addText(width + 10, 3, maxText); // max } else { this._addText(0, height, minText); // min this._addText(width, height, maxText); // max } } // add min and max text while slidable === false ; _proto._addText = function _addText(x, y, text) { var group = this.get('group'); var textGroup = group.addGroup(); var textStyle = this.get('textStyle'); var titleShape = this.get('titleShape'); var titleGap = this.get('titleGap'); if (titleShape) { titleGap += titleShape.getBBox().height; } if (this.get('layout') === 'vertical') { textGroup.addShape('text', { attrs: Util.mix({ x: x + this.get('textOffset'), y: y, text: text === 0 ? '0' : text }, textStyle) }); } else { y += titleGap + this.get('textOffset') - 20; if (!titleShape) y += 10; textGroup.addShape('text', { attrs: Util.mix({ x: x, y: y, text: text === 0 ? '0' : text }, textStyle) }); } }; return Size; }(Continuous); module.exports = Size; /***/ }), /* 387 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @fileOverview The class of the size legend * @author sima.zhang * @author ye liu */ var Util = __webpack_require__(4); // const Global = require('../../global'); var Continuous = __webpack_require__(97); var SLIDER_HEIGHT = 2; var CIRCLE_GAP = 16; var MAX_SIZE = 16; var MIN_SIZE = 5; var CircleSize = /*#__PURE__*/function (_Continuous) { _inheritsLoose(CircleSize, _Continuous); function CircleSize() { return _Continuous.apply(this, arguments) || this; } var _proto = CircleSize.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Continuous.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * 类型 * @type {String} */ type: 'size-circle-legend', width: 100, height: 200, /** * 不能滑动时圈的样式 * @type {ATTRS} */ _unslidableCircleStyle: { stroke: 'rgb(99, 161, 248)', fill: 'rgb(99, 161, 248)', fillOpacity: 0.3, lineWidth: 1.5 }, /** * 滑块的样式 * @type {ATTRS} */ triggerAttr: { fill: 'white', shadowOffsetX: -2, shadowOffsetY: 2, shadowBlur: 10, shadowColor: '#ccc' }, /** * 中间 bar 的前景颜色 * @type {ATTRS} */ frontMiddleBarStyle: { fill: 'rgb(64, 141, 251)' } }); } // render the slider shape ; _proto._renderSliderShape = function _renderSliderShape() { var minRadius = MIN_SIZE; var slider = this.get('slider'); var backgroundElement = slider.get('backgroundElement'); var layout = this.get('layout'); var width = layout === 'vertical' ? SLIDER_HEIGHT : this.get('width'); var height = layout === 'vertical' ? this.get('height') : SLIDER_HEIGHT; var x = minRadius; var y = this.get('height') / 2; var frontMiddleBarStyle = this.get('frontMiddleBarStyle'); // background of middle bar var points = layout === 'vertical' ? [[0, 0], [width, 0], [width, height], [0, height]] : [[0, y + height], [0, y - height], [x + width - 4, y - height], [x + width - 4, y + height]]; return this._addMiddleBar(backgroundElement, 'Polygon', Util.mix({ points: points }, frontMiddleBarStyle)); } // triggers while layout === horizontal ; _proto._addHorizontalTrigger = function _addHorizontalTrigger(type, blockAttr, textAttr, radius) { var slider = this.get('slider'); var trigger = slider.get(type + 'HandleElement'); var y = -this.get('height') / 2; var button = trigger.addShape('circle', { attrs: Util.mix({ x: 0, y: y, r: radius }, blockAttr) }); var text = trigger.addShape('text', { attrs: Util.mix(textAttr, { x: 0, y: y + radius + 10, textAlign: 'center', textBaseline: 'middle' }) }); var layout = this.get('layout'); var trigerCursor = layout === 'vertical' ? 'ns-resize' : 'ew-resize'; button.attr('cursor', trigerCursor); text.attr('cursor', trigerCursor); this.set(type + 'ButtonElement', button); this.set(type + 'TextElement', text); } // triggers while layout === vertical ; _proto._addVerticalTrigger = function _addVerticalTrigger(type, blockAttr, textAttr, radius) { var slider = this.get('slider'); var trigger = slider.get(type + 'HandleElement'); var button = trigger.addShape('circle', { attrs: Util.mix({ x: 0, y: 0, r: radius }, blockAttr) }); var text = trigger.addShape('text', { attrs: Util.mix(textAttr, { x: radius + 10, y: 0, textAlign: 'start', textBaseline: 'middle' }) }); var layout = this.get('layout'); var trigerCursor = layout === 'vertical' ? 'ns-resize' : 'ew-resize'; button.attr('cursor', trigerCursor); text.attr('cursor', trigerCursor); this.set(type + 'ButtonElement', button); this.set(type + 'TextElement', text); } // render the triggers ; _proto._renderTrigger = function _renderTrigger() { var min = this.get('firstItem'); var max = this.get('lastItem'); var layout = this.get('layout'); var textStyle = this.get('textStyle'); var triggerAttr = this.get('triggerAttr'); var minBlockAttr = Util.mix({}, triggerAttr); var maxBlockAttr = Util.mix({}, triggerAttr); var minRadius = MIN_SIZE; var maxRadius = MAX_SIZE; var minTextAttr = Util.mix({ text: this._formatItemValue(min.value) + '' }, textStyle); var maxTextAttr = Util.mix({ text: this._formatItemValue(max.value) + '' }, textStyle); if (layout === 'vertical') { this._addVerticalTrigger('min', minBlockAttr, minTextAttr, minRadius); this._addVerticalTrigger('max', maxBlockAttr, maxTextAttr, maxRadius); } else { this._addHorizontalTrigger('min', minBlockAttr, minTextAttr, minRadius); this._addHorizontalTrigger('max', maxBlockAttr, maxTextAttr, maxRadius); } } // user interactions ; _proto._bindEvents = function _bindEvents() { var _this = this; if (this.get('slidable')) { var slider = this.get('slider'); slider.on('sliderchange', function (ev) { var range = ev.range; var firstItemValue = _this.get('firstItem').value; var lastItemValue = _this.get('lastItem').value; var minValue = firstItemValue + range[0] / 100 * (lastItemValue - firstItemValue); var maxValue = firstItemValue + range[1] / 100 * (lastItemValue - firstItemValue); var minRadius = MIN_SIZE + range[0] / 100 * (MAX_SIZE - MIN_SIZE); var maxRadius = MIN_SIZE + range[1] / 100 * (MAX_SIZE - MIN_SIZE); _this._updateElement(minValue, maxValue, minRadius, maxRadius); var itemFiltered = new Event('itemfilter', ev, true, true); itemFiltered.range = [minValue, maxValue]; _this.emit('itemfilter', itemFiltered); }); } } // update the triggers ; _proto._updateElement = function _updateElement(min, max, minR, maxR) { // update the text of the triggers _Continuous.prototype._updateElement.call(this, min, max); var minTextElement = this.get('minTextElement'); var maxTextElement = this.get('maxTextElement'); var minCircleElement = this.get('minButtonElement'); var maxCircleElement = this.get('maxButtonElement'); // update the radius of the triggers minCircleElement.attr('r', minR); maxCircleElement.attr('r', maxR); // update the text position of the triggers var layout = this.get('layout'); if (layout === 'vertical') { minTextElement.attr('x', minR + 10); maxTextElement.attr('x', maxR + 10); } else { var y = -this.get('height') / 2; minTextElement.attr('y', y + minR + 10); maxTextElement.attr('y', y + maxR + 10); } } // add a circle for slidable === false ; _proto._addCircle = function _addCircle(x, y, r, text, maxWidth) { var group = this.get('group'); var circleGroup = group.addGroup(); var circleStyle = this.get('_unslidableCircleStyle'); var textStyle = this.get('textStyle'); var titleShape = this.get('titleShape'); var titleGap = this.get('titleGap'); if (titleShape) { titleGap += titleShape.getBBox().height; } circleGroup.addShape('circle', { attrs: Util.mix({ x: x, y: y + titleGap, r: r === 0 ? 1 : r }, circleStyle) }); if (this.get('layout') === 'vertical') { circleGroup.addShape('text', { attrs: Util.mix({ x: maxWidth + 20 + this.get('textOffset'), y: y + titleGap, text: text === 0 ? '0' : text }, textStyle) }); } else { circleGroup.addShape('text', { attrs: Util.mix({ x: x, y: y + titleGap + maxWidth + 13 + this.get('textOffset'), text: text === 0 ? '0' : text }, textStyle) }); } } // the circles while slidable === false ; _proto._renderUnslidable = function _renderUnslidable() { var firstItemValue = this.get('firstItem').value; var lastItemValue = this.get('lastItem').value; if (firstItemValue > lastItemValue) { var tmp = lastItemValue; lastItemValue = firstItemValue; firstItemValue = tmp; } var minText = this._formatItemValue(firstItemValue); var maxText = this._formatItemValue(lastItemValue); var minRadius = firstItemValue < MIN_SIZE ? MIN_SIZE : firstItemValue; var maxRadius = lastItemValue > MAX_SIZE ? MAX_SIZE : lastItemValue; if (minRadius > maxRadius) { minRadius = MIN_SIZE; maxRadius = MAX_SIZE; } if (this.get('layout') === 'vertical') { this._addCircle(maxRadius, maxRadius, minRadius, minText, 2 * maxRadius); // min this._addCircle(maxRadius, maxRadius * 2 + CIRCLE_GAP + minRadius, maxRadius, maxText, 2 * maxRadius); // max } else { this._addCircle(maxRadius, maxRadius, minRadius, minText, 2 * maxRadius); // min this._addCircle(maxRadius * 2 + CIRCLE_GAP + minRadius, maxRadius, maxRadius, maxText, 2 * maxRadius); // max } }; _proto.activate = function activate(value) { if (!this.get('slidable')) { return; } _Continuous.prototype.activate.call(this, value); }; return CircleSize; }(Continuous); module.exports = CircleSize; /***/ }), /* 388 */ /***/ (function(module, exports, __webpack_require__) { var Tooltip = __webpack_require__(98); Tooltip.Html = __webpack_require__(389); Tooltip.Canvas = __webpack_require__(197); Tooltip.Mini = __webpack_require__(391); module.exports = Tooltip; /***/ }), /* 389 */ /***/ (function(module, exports, __webpack_require__) { function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var G = __webpack_require__(51); var Tooltip = __webpack_require__(98); var Util = __webpack_require__(4); var DomUtil = Util.DomUtil; var TooltipTheme = __webpack_require__(390); var Crosshair = __webpack_require__(194); var PositionMixin = __webpack_require__(195); var MarkerGroupMixin = __webpack_require__(196); var CONTAINER_CLASS = 'g2-tooltip'; var TITLE_CLASS = 'g2-tooltip-title'; var LIST_CLASS = 'g2-tooltip-list'; var MARKER_CLASS = 'g2-tooltip-marker'; var VALUE_CLASS = 'g2-tooltip-value'; var LIST_ITEM_CLASS = 'g2-tooltip-list-item'; var MARKER_SIZE = 5; var Marker = G.Marker; function find(dom, cls) { return dom.getElementsByClassName(cls)[0]; } function mergeStyles(styles, cfg) { Object.keys(styles).forEach(function (k) { if (cfg[k]) { styles[k] = Util.mix(styles[k], cfg[k]); } }); return styles; } var HtmlTooltip = /*#__PURE__*/function (_Tooltip) { _inheritsLoose(HtmlTooltip, _Tooltip); var _proto = HtmlTooltip.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Tooltip.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * tooltip 容器模板 * @type {String} */ containerTpl: '
    ' + '
    ' + '
      ' + '
      ', /** * tooltip 列表项模板 * @type {String} */ itemTpl: "
    • \n \n {name}{value}
    • ", /** * tooltip html内容 * @type {String} */ htmlContent: null, /** * tooltip 内容跟随鼠标移动 * @type {Boolean} */ follow: true, /** * 是否允许鼠标停留在 tooltip 上,默认不允许 * @type {Boolean} */ enterable: false }); }; function HtmlTooltip(cfg) { var _this; _this = _Tooltip.call(this, cfg) || this; Util.assign(_assertThisInitialized(_this), PositionMixin); Util.assign(_assertThisInitialized(_this), MarkerGroupMixin); var style = TooltipTheme; _this.style = mergeStyles(style, cfg); _this._init_(); if (_this.get('items')) { _this.render(); } // crosshair var crosshair = _this.get('crosshairs'); if (crosshair) { var plot = crosshair.type === 'rect' ? _this.get('backPlot') : _this.get('frontPlot'); var crosshairGroup = new Crosshair(Util.mix({ plot: plot, plotRange: _this.get('plotRange'), canvas: _this.get('canvas') }, _this.get('crosshairs'))); crosshairGroup.hide(); _this.set('crosshairGroup', crosshairGroup); } return _this; } _proto._init_ = function _init_() { var self = this; var containerTpl = self.get('containerTpl'); var outterNode = self.get('canvas').get('el').parentNode; var container; if (!this.get('htmlContent')) { if (/^\#/.test(containerTpl)) { // 如果传入 dom 节点的 id var id = containerTpl.replace('#', ''); container = document.getElementById(id); } else { container = DomUtil.createDom(containerTpl); DomUtil.modifyCSS(container, self.style[CONTAINER_CLASS]); outterNode.appendChild(container); outterNode.style.position = 'relative'; } self.set('container', container); } }; _proto.render = function render() { var self = this; self.clear(); if (self.get('htmlContent')) { var outterNode = self.get('canvas').get('el').parentNode; var container = self._getHtmlContent(); outterNode.appendChild(container); self.set('container', container); } else { self._renderTpl(); } }; _proto._renderTpl = function _renderTpl() { var self = this; var showTitle = self.get('showTitle'); var titleContent = self.get('titleContent'); var container = self.get('container'); var titleDom = find(container, TITLE_CLASS); var listDom = find(container, LIST_CLASS); var items = self.get('items'); if (titleDom && showTitle) { DomUtil.modifyCSS(titleDom, self.style[TITLE_CLASS]); titleDom.innerHTML = titleContent; } if (listDom) { DomUtil.modifyCSS(listDom, self.style[LIST_CLASS]); Util.each(items, function (item, index) { listDom.appendChild(self._addItem(item, index)); }); } }; _proto.clear = function clear() { var container = this.get('container'); if (this.get('htmlContent')) { container && container.remove(); } else { var titleDom = find(container, TITLE_CLASS); var listDom = find(container, LIST_CLASS); if (titleDom) { titleDom.innerHTML = ''; } if (listDom) { listDom.innerHTML = ''; } } }; _proto.show = function show() { var container = this.get('container'); if (!container || this.destroyed) { // 防止容器不存在或者被销毁时报错 return; } container.style.visibility = 'visible'; container.style.display = 'block'; var crosshairGroup = this.get('crosshairGroup'); crosshairGroup && crosshairGroup.show(); var markerGroup = this.get('markerGroup'); markerGroup && markerGroup.show(); _Tooltip.prototype.show.call(this); this.get('canvas').draw(); }; _proto.hide = function hide() { var container = this.get('container'); // relative: https://github.com/antvis/g2/issues/1221 if (!container || this.destroyed) { return; } container.style.visibility = 'hidden'; container.style.display = 'none'; var crosshairGroup = this.get('crosshairGroup'); crosshairGroup && crosshairGroup.hide(); var markerGroup = this.get('markerGroup'); markerGroup && markerGroup.hide(); _Tooltip.prototype.hide.call(this); this.get('canvas').draw(); }; _proto.destroy = function destroy() { var self = this; var container = self.get('container'); var containerTpl = self.get('containerTpl'); if (container && !/^\#/.test(containerTpl)) { container.parentNode.removeChild(container); } var crosshairGroup = this.get('crosshairGroup'); crosshairGroup && crosshairGroup.destroy(); var markerGroup = this.get('markerGroup'); markerGroup && markerGroup.remove(); _Tooltip.prototype.destroy.call(this); }; _proto._getMarkerSvg = function _getMarkerSvg(item) { var marker = item.marker || {}; var symbol = marker.activeSymbol || marker.symbol; var method; if (Util.isFunction(symbol)) { method = symbol; } else if (Util.isString(symbol)) { method = Marker.Symbols[symbol]; } method = Util.isFunction(method) ? method : Marker.Symbols.circle; var pathArr = method(MARKER_SIZE / 2, MARKER_SIZE / 2, MARKER_SIZE / 2); var path = pathArr.reduce(function (res, arr) { return "" + res + arr[0] + arr.slice(1).join(','); }, ''); return ""; }; _proto._addItem = function _addItem(item, index) { var itemTpl = this.get('itemTpl'); // TODO: 有可能是个回调函数 var itemDiv = Util.substitute(itemTpl, Util.mix({ index: index }, item)); var itemDOM = DomUtil.createDom(itemDiv); DomUtil.modifyCSS(itemDOM, this.style[LIST_ITEM_CLASS]); var markerDom = find(itemDOM, MARKER_CLASS); if (markerDom) { DomUtil.modifyCSS(markerDom, _extends({}, this.style[MARKER_CLASS], { borderRadius: 'unset' })); var markerPath = this._getMarkerSvg(item); markerDom.innerHTML = markerPath; } var valueDom = find(itemDOM, VALUE_CLASS); if (valueDom) { DomUtil.modifyCSS(valueDom, this.style[VALUE_CLASS]); } return itemDOM; }; _proto._getHtmlContent = function _getHtmlContent() { var htmlContent = this.get('htmlContent'); var title = this.get('titleContent'); var items = this.get('items'); var htmlString = htmlContent(title, items); var ele = DomUtil.createDom(htmlString); return ele; }; _proto.setPosition = function setPosition(x, y, target) { var container = this.get('container'); var outterNode = this.get('canvas').get('el'); var viewWidth = DomUtil.getWidth(outterNode); var viewHeight = DomUtil.getHeight(outterNode); var containerWidth = container.clientWidth; var containerHeight = container.clientHeight; var endx = x; var endy = y; var position; var prePosition = this.get('prePosition') || { x: 0, y: 0 }; // @2019-01-30 by blue.lb 由于display:none的元素获取clientWidth和clientHeight的值为0,这里强制显隐一下,其实直接在show和hide中去掉display设置最好,猜测为了更好的兼容浏览器 if (!containerWidth) { container.style.display = 'block'; containerWidth = container.clientWidth; containerHeight = container.clientHeight; container.style.display = 'none'; } if (this.get('enterable')) { y = y - container.clientHeight / 2; position = [x, y]; if (prePosition && x - prePosition.x > 0) { // 留 1px 防止鼠标点击事件无法在画布上触发 x -= container.clientWidth + 1; } else { x += 1; } } else if (this.get('position')) { // @2019-01-30 by blue.lb 这里应该是多余代码 // const containerWidth = container.clientWidth; // const containerHeight = container.clientHeight; position = this._calcTooltipPosition(x, y, this.get('position'), containerWidth, containerHeight, target); x = position[0]; y = position[1]; } else { position = this._constraintPositionInBoundary(x, y, containerWidth, containerHeight, viewWidth, viewHeight); x = position[0]; y = position[1]; } if (this.get('inPlot')) { // tooltip 必须限制在绘图区域内 var plotRange = this.get('plotRange'); position = this._constraintPositionInPlot(x, y, containerWidth, containerHeight, plotRange, this.get('enterable')); x = position[0]; y = position[1]; } var markerItems = this.get('markerItems'); if (!Util.isEmpty(markerItems)) { endx = markerItems[0].x; endy = markerItems[0].y; } this.set('prePosition', position); // 记录上次的位置 var follow = this.get('follow'); if (follow) { container.style.left = x + 'px'; container.style.top = y + 'px'; } var crosshairGroup = this.get('crosshairGroup'); if (crosshairGroup) { var items = this.get('items'); crosshairGroup.setPosition(endx, endy, items); } _Tooltip.prototype.setPosition.call(this, x, y); }; return HtmlTooltip; }(Tooltip); module.exports = HtmlTooltip; /***/ }), /* 390 */ /***/ (function(module, exports, __webpack_require__) { var _TooltipTheme; var _require = __webpack_require__(16), FONT_FAMILY = _require.FONT_FAMILY; // tooltip 相关 dom 的 css 类名 var TOOLTIP_CONTAINER_CLASS = 'g2-tooltip'; var TOOLTIP_TITLE_CLASS = 'g2-tooltip-title'; var TOOLTIP_LIST_CLASS = 'g2-tooltip-list'; var TOOLTIP_LIST_ITEM_CLASS = 'g2-tooltip-list-item'; var TOOLTIP_MARKER_CLASS = 'g2-tooltip-marker'; var TOOLTIP_VALUE_CLASS = 'g2-tooltip-value'; var TooltipTheme = (_TooltipTheme = { crosshairs: false, offset: 15 }, _TooltipTheme["" + TOOLTIP_CONTAINER_CLASS] = { position: 'absolute', visibility: 'hidden', // @2018-07-25 by blue.lb 这里去掉浮动,火狐上存在样式错位 // whiteSpace: 'nowrap', zIndex: 8, transition: 'visibility 0.2s cubic-bezier(0.23, 1, 0.32, 1), left 0.4s cubic-bezier(0.23, 1, 0.32, 1), top 0.4s cubic-bezier(0.23, 1, 0.32, 1)', backgroundColor: 'rgba(255, 255, 255, 0.9)', boxShadow: '0px 0px 10px #aeaeae', borderRadius: '3px', color: 'rgb(87, 87, 87)', fontSize: '12px', fontFamily: FONT_FAMILY, lineHeight: '20px', padding: '10px 10px 6px 10px' }, _TooltipTheme["" + TOOLTIP_TITLE_CLASS] = { marginBottom: '4px' }, _TooltipTheme["" + TOOLTIP_LIST_CLASS] = { margin: 0, listStyleType: 'none', padding: 0 }, _TooltipTheme["" + TOOLTIP_LIST_ITEM_CLASS] = { marginBottom: '4px' }, _TooltipTheme["" + TOOLTIP_MARKER_CLASS] = { width: '5px', height: '5px', borderRadius: '50%', display: 'inline-block', marginRight: '8px' }, _TooltipTheme["" + TOOLTIP_VALUE_CLASS] = { display: 'inline-block', float: 'right', marginLeft: '30px' }, _TooltipTheme); module.exports = TooltipTheme; /***/ }), /* 391 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(4); var CanvasTooltip = __webpack_require__(197); var _require = __webpack_require__(16), FONT_FAMILY = _require.FONT_FAMILY; var DomUtil = Util.DomUtil; var MatrixUtil = Util.MatrixUtil; var MiniTooltip = /*#__PURE__*/function (_CanvasTooltip) { _inheritsLoose(MiniTooltip, _CanvasTooltip); function MiniTooltip() { return _CanvasTooltip.apply(this, arguments) || this; } var _proto = MiniTooltip.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _CanvasTooltip.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * 默认背景板样式 * @type {Object} */ boardStyle: { x: 0, y: 0, width: 0, height: 0, // fill: 'rgba(50, 50, 50, 1)', radius: 3 }, /** * 默认value样式 * @type {Object} * */ valueStyle: { x: 0, y: 0, text: '', fontFamily: FONT_FAMILY, fontSize: 12, stroke: '#fff', lineWidth: 2, fill: 'black', textBaseline: 'top', textAlign: 'start' }, /** * 默认padding值 * @type {Object} */ padding: { top: 5, right: 5, bottom: 0, left: 5 }, triangleWidth: 10, triangleHeight: 4 }); }; _proto._init_ = function _init_() { var self = this; var padding = self.get('padding'); var parent = self.get('frontPlot'); // container var container = parent.addGroup(); self.set('container', container); // board var board = container.addShape('rect', { attrs: Util.mix({}, self.get('boardStyle')) }); self.set('board', board); // triangleShpe var triangleShape = container.addShape('path', { attrs: { fill: self.get('boardStyle').fill } }); self.set('triangleShape', triangleShape); // itemGroup var itemGroup = container.addGroup(); itemGroup.move(padding.left, padding.top); // value var valueShape = itemGroup.addShape('text', { attrs: Util.mix({}, self.get('valueStyle')) }); self.set('valueShape', valueShape); }; _proto.render = function render() { var self = this; self.clear(); var board = self.get('board'); var valueShape = self.get('valueShape'); var padding = self.get('padding'); var item = self.get('items')[0]; if (valueShape) { valueShape.attr('text', item.value); } // update board based on bbox var bbox = valueShape ? valueShape.getBBox() : { width: 80, height: 30 }; var width = padding.left + bbox.width + padding.right; var height = padding.top + bbox.height + padding.bottom; board.attr('width', width); board.attr('height', height); // update triangle shape self._centerTriangleShape(); }; _proto.clear = function clear() { var valueShape = this.get('valueShape'); valueShape.attr('text', ''); }; _proto.setPosition = function setPosition(x, y, target) { var self = this; var container = self.get('container'); var plotRange = self.get('plotRange'); var bbox = container.getBBox(); var width = bbox.width; var height = bbox.height; x -= width / 2; if (target && (target.name === 'point' || target.name === 'interval')) { var targetY = target.getBBox().y; y = targetY; } y -= height; if (this.get('inPlot')) { // constrain in plot if (x < plotRange.tl.x) { x = plotRange.tl.x; self._leftTriangleShape(); } else if (x + width / 2 > plotRange.tr.x) { x = plotRange.tr.x - width; self._rightTriangleShape(); } else { self._centerTriangleShape(); } if (y < plotRange.tl.y) { y = plotRange.tl.y; } else if (y + height > plotRange.bl.y) { y = plotRange.bl.y - height; } } else { // constrain in dom var outterNode = this.get('canvas').get('el'); var viewWidth = DomUtil.getWidth(outterNode); var viewHeight = DomUtil.getHeight(outterNode); if (x < 0) { x = 0; self._leftTriangleShape(); } else if (x + width / 2 > viewWidth) { x = viewWidth - width; self._rightTriangleShape(); } else { self._centerTriangleShape(); } if (y < 0) { y = 0; } else if (y + height > viewHeight) { y = viewHeight - height; } } var ulMatrix = [1, 0, 0, 0, 1, 0, 0, 0, 1]; var mat = MatrixUtil.transform(ulMatrix, [['t', x, y]]); container.stopAnimate(); container.animate({ matrix: mat }, this.get('animationDuration')); }; _proto._centerTriangleShape = function _centerTriangleShape() { var triangle = this.get('triangleShape'); var width = this.get('triangleWidth'); var height = this.get('triangleHeight'); var boardBBox = this.get('board').getBBox(); var boardWidth = boardBBox.width; var boardHeight = boardBBox.height; var pathArray = [['M', 0, 0], ['L', width, 0], ['L', width / 2, height], ['L', 0, 0], ['Z']]; triangle.attr('path', pathArray); triangle.move(boardWidth / 2 - width / 2, boardHeight - 1); }; _proto._leftTriangleShape = function _leftTriangleShape() { var triangle = this.get('triangleShape'); var width = this.get('triangleWidth'); var height = this.get('triangleHeight'); var boardBBox = this.get('board').getBBox(); var boardHeight = boardBBox.height; var pathArray = [['M', 0, 0], ['L', width, 0], ['L', 0, height + 3], ['L', 0, 0], ['Z']]; triangle.attr('path', pathArray); triangle.move(0, boardHeight - 3); }; _proto._rightTriangleShape = function _rightTriangleShape() { var triangle = this.get('triangleShape'); var width = this.get('triangleWidth'); var height = this.get('triangleHeight'); var boardBBox = this.get('board').getBBox(); var boardWidth = boardBBox.width; var boardHeight = boardBBox.height; var pathArray = [['M', 0, 0], ['L', width, 0], ['L', width, height + 4], ['L', 0, 0], ['Z']]; triangle.attr('path', pathArray); triangle.move(boardWidth - width - 1, boardHeight - 4); }; return MiniTooltip; }(CanvasTooltip); module.exports = MiniTooltip; /***/ }), /* 392 */ /***/ (function(module, exports, __webpack_require__) { var MatrixUtil = __webpack_require__(0).MatrixUtil; var Vector2 = MatrixUtil.vec2; function smoothBezier(points, smooth, isLoop, constraint) { var cps = []; var prevPoint; var nextPoint; var hasConstraint = !!constraint; var min, max; if (hasConstraint) { min = [Infinity, Infinity]; max = [-Infinity, -Infinity]; for (var i = 0, l = points.length; i < l; i++) { var point = points[i]; min = Vector2.min([], min, point); max = Vector2.max([], max, point); } min = Vector2.min([], min, constraint[0]); max = Vector2.max([], max, constraint[1]); } for (var _i = 0, len = points.length; _i < len; _i++) { var _point = points[_i]; if (isLoop) { prevPoint = points[_i ? _i - 1 : len - 1]; nextPoint = points[(_i + 1) % len]; } else { if (_i === 0 || _i === len - 1) { cps.push(_point); continue; } else { prevPoint = points[_i - 1]; nextPoint = points[_i + 1]; } } var v = []; v = Vector2.sub(v, nextPoint, prevPoint); v = Vector2.scale(v, v, smooth); var d0 = Vector2.distance(_point, prevPoint); var d1 = Vector2.distance(_point, nextPoint); var sum = d0 + d1; if (sum !== 0) { d0 /= sum; d1 /= sum; } var v1 = Vector2.scale([], v, -d0); var v2 = Vector2.scale([], v, d1); var cp0 = Vector2.add([], _point, v1); var cp1 = Vector2.add([], _point, v2); if (hasConstraint) { cp0 = Vector2.max([], cp0, min); cp0 = Vector2.min([], cp0, max); cp1 = Vector2.max([], cp1, min); cp1 = Vector2.min([], cp1, max); } cps.push(cp0); cps.push(cp1); } if (isLoop) { cps.push(cps.shift()); } return cps; } function catmullRom2bezier(crp, z, constraint) { var isLoop = !!z; var pointList = []; for (var i = 0, l = crp.length; i < l; i += 2) { pointList.push([crp[i], crp[i + 1]]); } var controlPointList = smoothBezier(pointList, 0.4, isLoop, constraint); var len = pointList.length; var d1 = []; var cp1; var cp2; var p; for (var _i2 = 0; _i2 < len - 1; _i2++) { cp1 = controlPointList[_i2 * 2]; cp2 = controlPointList[_i2 * 2 + 1]; p = pointList[_i2 + 1]; d1.push(['C', cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]]); } if (isLoop) { cp1 = controlPointList[len]; cp2 = controlPointList[len + 1]; p = pointList[0]; d1.push(['C', cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]]); } return d1; } module.exports = { catmullRom2bezier: catmullRom2bezier }; /***/ }), /* 393 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(0); var PolarLabels = __webpack_require__(198); var PathUtil = __webpack_require__(25); var Global = __webpack_require__(8); var MARGIN = 5; function getEndPoint(center, angle, r) { return { x: center.x + r * Math.cos(angle), y: center.y + r * Math.sin(angle) }; } function antiCollision(labels, lineHeight, plotRange, center, isRight) { // adjust y position of labels to avoid overlapping var overlapping = true; var start = plotRange.start; var end = plotRange.end; var startY = Math.min(start.y, end.y); var totalHeight = Math.abs(start.y - end.y); var i; var maxY = 0; var minY = Number.MIN_VALUE; var boxes = labels.map(function (label) { if (label.y > maxY) { maxY = label.y; } if (label.y < minY) { minY = label.y; } return { size: lineHeight, targets: [label.y - startY] }; }); minY -= startY; if (maxY - startY > totalHeight) { totalHeight = maxY - startY; } while (overlapping) { /* eslint no-loop-func: 0 */ boxes.forEach(function (box) { var target = (Math.min.apply(minY, box.targets) + Math.max.apply(minY, box.targets)) / 2; box.pos = Math.min(Math.max(minY, target - box.size / 2), totalHeight - box.size); // box.pos = Math.max(0, target - box.size / 2); }); // detect overlapping and join boxes overlapping = false; i = boxes.length; while (i--) { if (i > 0) { var previousBox = boxes[i - 1]; var box = boxes[i]; if (previousBox.pos + previousBox.size > box.pos) { // overlapping previousBox.size += box.size; previousBox.targets = previousBox.targets.concat(box.targets); // overflow, shift up if (previousBox.pos + previousBox.size > totalHeight) { previousBox.pos = totalHeight - previousBox.size; } boxes.splice(i, 1); // removing box overlapping = true; } } } } i = 0; // step 4: normalize y and adjust x boxes.forEach(function (b) { var posInCompositeBox = startY + lineHeight / 2; // middle of the label b.targets.forEach(function () { labels[i].y = b.pos + posInCompositeBox; posInCompositeBox += lineHeight; i++; }); }); // (x - cx)^2 + (y - cy)^2 = totalR^2 labels.forEach(function (label) { var rPow2 = label.r * label.r; var dyPow2 = Math.pow(Math.abs(label.y - center.y), 2); if (rPow2 < dyPow2) { label.x = center.x; } else { var dx = Math.sqrt(rPow2 - dyPow2); if (!isRight) { // left label.x = center.x - dx; } else { // right label.x = center.x + dx; } } }); } var PieLabels = function PieLabels(cfg) { PieLabels.superclass.constructor.call(this, cfg); }; Util.extend(PieLabels, PolarLabels); Util.augment(PieLabels, { getDefaultCfg: function getDefaultCfg() { return { label: Global.thetaLabels }; }, getDefaultOffset: function getDefaultOffset(point) { return point.offset || 0; }, /** * @protected * to avoid overlapping * @param {Array} items labels to be placed * @return {Array} items */ adjustItems: function adjustItems(items) { var self = this; var offset = items[0] ? items[0].offset : 0; if (offset > 0) { items = self._distribute(items, offset); } return PieLabels.superclass.adjustItems.call(this, items); }, /** * @private * distribute labels * @param {Array} labels labels * @param {Number} offset offset * @return {Array} labels */ _distribute: function _distribute(labels, offset) { var self = this; var coord = self.get('coord'); var radius = coord.getRadius(); var lineHeight = self.get('label').labelHeight; var center = coord.getCenter(); var totalR = radius + offset; var totalHeight = totalR * 2 + lineHeight * 2; var plotRange = { start: coord.start, end: coord.end }; var geom = self.get('geom'); if (geom) { var view = geom.get('view'); plotRange = view.getViewRegion(); } // step 1: separate labels var halves = [[], // left [] // right ]; labels.forEach(function (label) { if (!label) { return; } if (label.textAlign === 'right') { // left halves[0].push(label); } else { // right or center will be put on the right side halves[1].push(label); } }); halves.forEach(function (half, index) { // step 2: reduce labels var maxLabelsCountForOneSide = parseInt(totalHeight / lineHeight, 10); if (half.length > maxLabelsCountForOneSide) { half.sort(function (a, b) { // sort by percentage DESC return b['..percent'] - a['..percent']; }); half.splice(maxLabelsCountForOneSide, half.length - maxLabelsCountForOneSide); } // step 3: distribute position (x and y) half.sort(function (a, b) { // sort by y ASC return a.y - b.y; }); antiCollision(half, lineHeight, plotRange, center, index); }); return halves[0].concat(halves[1]); }, // 连接线 lineToLabel: function lineToLabel(label) { var self = this; var coord = self.get('coord'); var r = coord.getRadius(); var distance = label.offset; var angle = label.orignAngle || label.angle; var center = coord.getCenter(); var start = getEndPoint(center, angle, r + MARGIN / 2); var inner = getEndPoint(center, angle, r + distance / 2); if (!label.labelLine) { label.labelLine = self.get('label').labelLine || {}; } label.labelLine.path = ['M' + start.x, start.y + ' Q' + inner.x, inner.y + ' ' + label.x, label.y].join(','); }, /** * @protected * get rotation for label * @param {Number} angle angle * @param {Number} offset offset * @return {Number} rotate */ getLabelRotate: function getLabelRotate(angle, offset) { var rotate; if (offset < 0) { rotate = angle * 180 / Math.PI; if (rotate > 90) { rotate = rotate - 180; } if (rotate < -90) { rotate = rotate + 180; } } return rotate / 180 * Math.PI; }, /** * @protected * get text align for label * @param {Object} point point * @return {String} align */ getLabelAlign: function getLabelAlign(point) { var self = this; var coord = self.get('coord'); var center = coord.getCenter(); var align; if (point.angle <= Math.PI / 2 && point.x >= center.x) { align = 'left'; } else { align = 'right'; } var offset = self.getDefaultOffset(point); if (offset <= 0) { if (align === 'right') { align = 'left'; } else { align = 'right'; } } return align; }, getArcPoint: function getArcPoint(point) { return point; }, getPointAngle: function getPointAngle(point) { var self = this; var coord = self.get('coord'); var startPoint = { x: Util.isArray(point.x) ? point.x[0] : point.x, y: point.y[0] }; self.transLabelPoint(startPoint); // 转换到画布坐标,如果坐标系发生改变 var endPoint = { x: Util.isArray(point.x) ? point.x[1] : point.x, y: point.y[1] }; self.transLabelPoint(endPoint); // 转换到画布坐标,如果坐标系发生改变 var angle; var startAngle = PathUtil.getPointAngle(coord, startPoint); if (point.points && point.points[0].y === point.points[1].y) { angle = startAngle; } else { var endAngle = PathUtil.getPointAngle(coord, endPoint); if (startAngle >= endAngle) { // 100% pie slice endAngle = endAngle + Math.PI * 2; } angle = startAngle + (endAngle - startAngle) / 2; } return angle; }, getCirclePoint: function getCirclePoint(angle, offset) { var self = this; var coord = self.get('coord'); var center = coord.getCenter(); var r = coord.getRadius() + offset; var point = getEndPoint(center, angle, r); point.angle = angle; point.r = r; return point; } }); module.exports = PieLabels; /***/ }), /* 394 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(0); var GeomLabels = __webpack_require__(91); var IntervalLabels = function IntervalLabels(cfg) { IntervalLabels.superclass.constructor.call(this, cfg); }; Util.extend(IntervalLabels, GeomLabels); Util.augment(IntervalLabels, { setLabelPosition: function setLabelPosition(point, originPoint, index, position) { if (Util.isFunction(position)) { position = position(point.text, originPoint._origin, index); } var coord = this.get('coord'); var transposed = coord.isTransposed; var point0 = coord.convertPoint(originPoint.points[0]); var point1 = coord.convertPoint(originPoint.points[2]); var width = (point0.x - point1.x) / 2 * (transposed ? -1 : 1); var height = (point0.y - point1.y) / 2 * (transposed ? -1 : 1); switch (position) { case 'right': if (transposed) { point.x -= width; point.y += height; point.textAlign = point.textAlign || 'center'; } else { point.x -= width; point.y += height; point.textAlign = point.textAlign || 'left'; } break; case 'left': if (transposed) { point.x -= width; point.y -= height; point.textAlign = point.textAlign || 'center'; } else { point.x += width; point.y += height; point.textAlign = point.textAlign || 'right'; } break; case 'bottom': if (transposed) { point.x -= width * 2; point.textAlign = point.textAlign || 'left'; } else { point.y += height * 2; point.textAlign = point.textAlign || 'center'; } break; case 'middle': if (transposed) { point.x -= width; } else { point.y += height; } point.textAlign = point.textAlign || 'center'; break; case 'top': if (transposed) { point.textAlign = point.textAlign || 'left'; } else { point.textAlign = point.textAlign || 'center'; } break; default: break; } } }); module.exports = IntervalLabels; /***/ }), /* 395 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview The tooltip handler * @author sima.zhang */ var Util = __webpack_require__(0); var _require = __webpack_require__(8), defaultColor = _require.defaultColor; var FIELD_ORIGIN = '_origin'; function getScaleName(scale) { return scale.alias || scale.field; } var TooltipMixin = { _getIntervalSize: function _getIntervalSize(obj) { var size = null; var type = this.get('type'); var coord = this.get('coord'); if (coord.isRect && (type === 'interval' || type === 'schema')) { size = this.getSize(obj[FIELD_ORIGIN]); // 如果字段发生了映射,宽度计算就会报错 var dim = coord.isTransposed ? 'y' : 'x'; if (Util.isArray(obj[dim])) { var width = Math.abs(obj[dim][1] - obj[dim][0]); size = size < width ? null : size; // 直方图计算错误 } } return size; }, _snapEqual: function _snapEqual(v1, v2, scale) { var equals; v1 = scale.translate(v1); v2 = scale.translate(v2); if (scale.isCategory) { equals = v1 === v2; } else { equals = Util.snapEqual(v1, v2); } return equals; }, _getScaleValueByPoint: function _getScaleValueByPoint(point) { var result = 0; var coord = this.get('coord'); var xScale = this.getXScale(); var invertPoint = coord.invert(point); var xValue = invertPoint.x; if (this.isInCircle() && xValue > (1 + xScale.rangeMax()) / 2) { xValue = xScale.rangeMin(); // 极坐标下,scale 的 range 被做过特殊处理 see view.js#L88 } result = xScale.invert(xValue); if (xScale.isCategory) { result = xScale.translate(result); // 防止分类类型 } return result; }, _getOriginByPoint: function _getOriginByPoint(point) { var xScale = this.getXScale(); var yScale = this.getYScale(); var xField = xScale.field; var yField = yScale.field; var coord = this.get('coord'); var invertPoint = coord.invert(point); var xValue = xScale.invert(invertPoint.x); var yValue = yScale.invert(invertPoint.y); var result = {}; result[xField] = xValue; result[yField] = yValue; return result; }, _getScale: function _getScale(field) { var self = this; var scales = self.get('scales'); var rst = null; Util.each(scales, function (scale) { if (scale.field === field) { rst = scale; return false; } }); return rst; }, // 获取值对应的度量 _getTipValueScale: function _getTipValueScale() { var attrs = this.getAttrsForLegend(); var scale; Util.each(attrs, function (attr) { var tmpScale = attr.getScale(attr.type); if (tmpScale.isLinear) { // 如果指定字段是非position的,同时是连续的 scale = tmpScale; return false; } }); var xScale = this.getXScale(); var yScale = this.getYScale(); if (!scale && yScale && yScale.field === '..y') { return xScale; } return scale || yScale || xScale; }, _getTipTitleScale: function _getTipTitleScale(titleField) { var self = this; if (titleField) { return self._getScale(titleField); } var position = self.getAttr('position'); var fields = position.getFields(); var tmpField; Util.each(fields, function (field) { if (!field.includes('..')) { tmpField = field; return false; } }); return self._getScale(tmpField); }, _filterValue: function _filterValue(arr, point) { var coord = this.get('coord'); var yScale = this.getYScale(); var yField = yScale.field; var invertPoint = coord.invert(point); var yValue = invertPoint.y; yValue = yScale.invert(yValue); var rst = arr[arr.length - 1]; Util.each(arr, function (obj) { var origin = obj[FIELD_ORIGIN]; if (origin[yField][0] <= yValue && origin[yField][1] >= yValue) { rst = obj; return false; } }); return rst; }, getXDistance: function getXDistance() { var self = this; var distance = self.get('xDistance'); if (!distance) { var xScale = self.getXScale(); if (xScale.isCategory) { distance = 1; } else { var values = xScale.values; // values 是无序的 var min = xScale.translate(values[0]); var max = min; Util.each(values, function (value) { // 时间类型需要 translate value = xScale.translate(value); if (value < min) { min = value; } if (value > max) { max = value; } }); var length = values.length; // 应该是除以 length - 1 distance = (max - min) / (length - 1); } self.set('xDistance', distance); } return distance; }, findPoint: function findPoint(point, dataArray) { var self = this; var type = self.get('type'); var xScale = self.getXScale(); var yScale = self.getYScale(); var xField = xScale.field; var yField = yScale.field; var rst = null; if (Util.indexOf(['heatmap', 'point'], type) > -1) { var coord = self.get('coord'); var invertPoint = coord.invert(point); var xValue = xScale.invert(invertPoint.x); var yValue = yScale.invert(invertPoint.y); var min = Infinity; Util.each(dataArray, function (obj) { var distance = Math.pow(obj[FIELD_ORIGIN][xField] - xValue, 2) + Math.pow(obj[FIELD_ORIGIN][yField] - yValue, 2); if (distance < min) { min = distance; rst = obj; } }); return rst; } var first = dataArray[0]; var last = dataArray[dataArray.length - 1]; if (!first) { return rst; } var value = self._getScaleValueByPoint(point); // 根据该点获得对应度量后数据的值 var firstXValue = first[FIELD_ORIGIN][xField]; var firstYValue = first[FIELD_ORIGIN][yField]; var lastXValue = last[FIELD_ORIGIN][xField]; var isYRange = yScale.isLinear && Util.isArray(firstYValue); // 考虑 x 维度相同,y 是数组区间的情况 // 如果x的值是数组 if (Util.isArray(firstXValue)) { Util.each(dataArray, function (record) { var origin = record[FIELD_ORIGIN]; if (xScale.translate(origin[xField][0]) <= value && xScale.translate(origin[xField][1]) >= value) { if (isYRange) { if (!Util.isArray(rst)) { rst = []; } rst.push(record); } else { rst = record; return false; } } }); if (Util.isArray(rst)) { rst = this._filterValue(rst, point); } } else { var next; if (!xScale.isLinear && xScale.type !== 'timeCat') { Util.each(dataArray, function (record, index) { var origin = record[FIELD_ORIGIN]; if (self._snapEqual(origin[xField], value, xScale)) { if (isYRange) { if (!Util.isArray(rst)) { rst = []; } rst.push(record); } else { rst = record; return false; } } else if (xScale.translate(origin[xField]) <= value) { last = record; next = dataArray[index + 1]; } }); if (Util.isArray(rst)) { rst = this._filterValue(rst, point); } } else { if ((value > xScale.translate(lastXValue) || value < xScale.translate(firstXValue)) && (value > xScale.max || value < xScale.min)) { return null; } var firstIdx = 0; var lastIdx = dataArray.length - 1; var middleIdx; while (firstIdx <= lastIdx) { middleIdx = Math.floor((firstIdx + lastIdx) / 2); var item = dataArray[middleIdx][FIELD_ORIGIN][xField]; if (self._snapEqual(item, value, xScale)) { return dataArray[middleIdx]; } if (xScale.translate(item) <= xScale.translate(value)) { firstIdx = middleIdx + 1; last = dataArray[middleIdx]; next = dataArray[middleIdx + 1]; } else { if (lastIdx === 0) { last = dataArray[0]; } lastIdx = middleIdx - 1; } } } if (last && next) { // 计算最逼近的 if (Math.abs(xScale.translate(last[FIELD_ORIGIN][xField]) - value) > Math.abs(xScale.translate(next[FIELD_ORIGIN][xField]) - value)) { last = next; } } } var distance = self.getXDistance(); // 每个分类间的平均间距 if (!rst && Math.abs(xScale.translate(last[FIELD_ORIGIN][xField]) - value) <= distance / 2) { rst = last; } return rst; }, /** * @protected * 获取tooltip的标题 * @param {Object} origin 点的原始信息 * @param {String} titleField 标题的字段 * @return {String} 提示信息的标题 */ getTipTitle: function getTipTitle(origin, titleField) { var tipTitle = ''; var titleScale = this._getTipTitleScale(titleField); if (titleScale) { var value = origin[titleScale.field]; tipTitle = titleScale.getText(value); } else if (this.get('type') === 'heatmap') { // 热力图在不存在 title 的时候特殊处理 var xScale = this.getXScale(); var yScale = this.getYScale(); var xValue = xScale.getText(origin[xScale.field]); var yValue = yScale.getText(origin[yScale.field]); tipTitle = '( ' + xValue + ', ' + yValue + ' )'; } return tipTitle; }, getTipValue: function getTipValue(origin, valueScale) { var value; var field = valueScale.field; var key = origin.key; value = origin[field]; if (Util.isArray(value)) { var tmp = []; Util.each(value, function (sub) { tmp.push(valueScale.getText(sub)); }); value = tmp.join('-'); } else { value = valueScale.getText(value, key); } return value; }, /** * @protected * 获取tooltip的名称 * @param {Object} origin 点的原始信息 * @return {String} 提示信息的名称 */ getTipName: function getTipName(origin) { var name; var nameScale; var groupScales = this._getGroupScales(); if (groupScales.length) { // 如果存在分组类型,取第一个分组类型 Util.each(groupScales, function (scale) { nameScale = scale; return false; }); } if (nameScale) { var field = nameScale.field; name = nameScale.getText(origin[field]); } else { var valueScale = this._getTipValueScale(); name = getScaleName(valueScale); } return name; }, /** * 获取点对应tooltip的信息 * @protected * @param {Object} point 原始的数据记录 * @param {String} titleField tooltipTitle 配置信息 * @return {Array} 一条或者多条记录 */ getTipItems: function getTipItems(point, titleField) { var self = this; var origin = point[FIELD_ORIGIN]; var tipTitle = self.getTipTitle(origin, titleField); var tooltipCfg = self.get('tooltipCfg'); var items = []; var name; var value; function addItem(itemName, itemValue, cfg) { if (!Util.isNil(itemValue) && itemValue !== '') { // 值为null的时候,忽视 var item = { title: tipTitle, point: point, name: itemName || tipTitle, value: itemValue, color: point.color || defaultColor, marker: true }; item.size = self._getIntervalSize(point); items.push(Util.mix({}, item, cfg)); } } if (tooltipCfg) { var fields = tooltipCfg.fields; var cfg = tooltipCfg.cfg; var callbackParams = []; Util.each(fields, function (field) { callbackParams.push(origin[field]); }); if (cfg) { // 存在回调函数 if (Util.isFunction(cfg)) { cfg = cfg.apply(null, callbackParams); } var itemCfg = Util.mix({}, { point: point, title: tipTitle, color: point.color || defaultColor, marker: true // 默认展示 marker }, cfg); itemCfg.size = self._getIntervalSize(point); items.push(itemCfg); } else { Util.each(fields, function (field) { if (!Util.isNil(origin[field])) { // 字段数据为null ,undefined时不显示 var scale = self._getScale(field); name = getScaleName(scale); value = scale.getText(origin[field]); addItem(name, value); } }); } } else { var valueScale = self._getTipValueScale(); if (!Util.isNil(origin[valueScale.field])) { // 字段数据为null ,undefined时不显示 value = self.getTipValue(origin, valueScale); name = self.getTipName(origin); addItem(name, value); } } return items; }, isShareTooltip: function isShareTooltip() { var shareTooltip = this.get('shareTooltip'); var type = this.get('type'); var view = this.get('view'); var options; if (view.get('parent')) { options = view.get('parent').get('options'); } else { options = view.get('options'); } if (type === 'interval') { var coord = this.get('coord'); var coordType = coord.type; if (coordType === 'theta' || coordType === 'polar' && coord.isTransposed) { shareTooltip = false; } } else if (!this.getYScale() || Util.inArray(['contour', 'point', 'polygon', 'edge'], type)) { shareTooltip = false; } if (options.tooltip && Util.isBoolean(options.tooltip.shared)) { // 以用户设置的为准 shareTooltip = options.tooltip.shared; } return shareTooltip; } }; module.exports = TooltipMixin; /***/ }), /* 396 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview the interaction when geom was actived * @author sima.zhang */ var Util = __webpack_require__(0); var FIELD_ORIGIN = '_origin'; var ZIndexUtil = __webpack_require__(199); var ATTRS_ORIGIN_ACTIVE = '_originActiveAttrs'; function isSameShape(shape1, shape2) { if (Util.isNil(shape1) || Util.isNil(shape2)) { return false; } var shape1Origin = shape1.get('origin'); var shape2Origin = shape2.get('origin'); return Util.isEqual(shape1Origin, shape2Origin); } function isChange(preShapes, shapes) { if (!preShapes) { return true; } if (preShapes.length !== shapes.length) { return true; } var rst = false; Util.each(shapes, function (shape, index) { if (!isSameShape(shape, preShapes[index])) { rst = true; return false; } }); return rst; } function getOriginAttrs(activeCfg, shape) { var originAttrs = {}; Util.each(activeCfg, function (v, k) { var originValue = shape.attr(k); if (Util.isArray(originValue)) { originValue = Util.cloneDeep(originValue); // 缓存原来的属性,由于 .attr('matrix') 是数组,所以此处需要深度复制 } originAttrs[k] = originValue; }); return originAttrs; } var ActiveMixin = { _isAllowActive: function _isAllowActive() { var allowActive = this.get('allowActive'); if (Util.isNil(allowActive)) { // 用户未设置,使用默认的策略 var view = this.get('view'); var isShareTooltip = this.isShareTooltip(); var options = view.get('options'); // 默认情况下,tooltip 关闭或者 tooltip 模式为 shared === false 的时候允许 active if (options.tooltip === false || !isShareTooltip) { return true; } } else { return allowActive; } return false; }, _onMouseenter: function _onMouseenter(ev) { var self = this; var shape = ev.shape; var shapeContainer = self.get('shapeContainer'); if (shape && shapeContainer.contain(shape) && self._isAllowActive()) { // shape.get('animating') self.setShapesActived(shape); } }, _onMouseleave: function _onMouseleave() { var self = this; var view = self.get('view'); var canvas = view.get('canvas'); if (self.get('activeShapes')) { self.clearActivedShapes(); canvas.draw(); } }, _bindActiveAction: function _bindActiveAction() { var self = this; var view = self.get('view'); var type = self.get('type'); view.on(type + ':mouseenter', Util.wrapBehavior(self, '_onMouseenter')); view.on(type + ':mouseleave', Util.wrapBehavior(self, '_onMouseleave')); }, _offActiveAction: function _offActiveAction() { var self = this; var view = self.get('view'); var type = self.get('type'); view.off(type + ':mouseenter', Util.getWrapBehavior(self, '_onMouseenter')); view.off(type + ':mouseleave', Util.getWrapBehavior(self, '_onMouseleave')); }, _setActiveShape: function _setActiveShape(shape) { var self = this; var activedOptions = self.get('activedOptions') || {}; var shapeData = shape.get('origin'); var shapeName = shapeData.shape || self.getDefaultValue('shape'); if (Util.isArray(shapeName)) { shapeName = shapeName[0]; } var shapeFactory = self.get('shapeFactory'); var shapeCfg = Util.mix({}, shape.attr(), { origin: shapeData }); var activeCfg = shapeFactory.getActiveCfg(shapeName, shapeCfg); if (activedOptions.style) { Util.mix(activeCfg, activedOptions.style); } var originAttrs = getOriginAttrs(activeCfg, shape); shape.setSilent(ATTRS_ORIGIN_ACTIVE, originAttrs); if (activedOptions.animate) { shape.animate(activeCfg, 300); } else { shape.attr(activeCfg); } ZIndexUtil.toFront(shape); // 提前 }, setShapesActived: function setShapesActived(shapes) { var self = this; if (!Util.isArray(shapes)) { shapes = [shapes]; } var preShapes = self.get('activeShapes'); // 获取上次被激活的 shapes if (!isChange(preShapes, shapes)) { return; } var view = self.get('view'); var canvas = view.get('canvas'); var activedOptions = self.get('activedOptions'); if (activedOptions && activedOptions.highlight) { // 上次的动画未完成,所以要停止掉动画 Util.each(shapes, function (shape) { if (shape.get('animating')) { shape.stopAnimate(); } }); self.highlightShapes(shapes); } else { if (preShapes) { self.clearActivedShapes(); // 先清除激活元素 } Util.each(shapes, function (shape) { if (shape.get('animating')) { shape.stopAnimate(); } if (shape.get('visible')) { // && !shape.get('selected') self._setActiveShape(shape); } }); } self.set('activeShapes', shapes); // shapeContainer.sort(); // toFront, resetZIndex 不需要再排序 canvas.draw(); }, clearActivedShapes: function clearActivedShapes() { var self = this; var shapeContainer = self.get('shapeContainer'); var activedOptions = self.get('activedOptions'); var activeAnimate = activedOptions && activedOptions.animate; if (shapeContainer && !shapeContainer.get('destroyed')) { var activeShapes = self.get('activeShapes'); Util.each(activeShapes, function (activeShape) { // if (!activeShape.get('selected')) { var originAttrs = activeShape.get(ATTRS_ORIGIN_ACTIVE); if (activeAnimate) { activeShape.stopAnimate(); activeShape.animate(originAttrs, 300); } else { activeShape.attr(originAttrs); } ZIndexUtil.resetZIndex(activeShape); activeShape.setSilent(ATTRS_ORIGIN_ACTIVE, null); // } }); var preHighlightShapes = self.get('preHighlightShapes'); if (preHighlightShapes) { var shapes = shapeContainer.get('children'); Util.each(shapes, function (shape) { // if (!shape.get('selected')) { var originAttrs = shape.get(ATTRS_ORIGIN_ACTIVE); if (originAttrs) { if (activeAnimate) { shape.stopAnimate(); shape.animate(originAttrs, 300); } else { shape.attr(originAttrs); } ZIndexUtil.resetZIndex(shape); shape.setSilent(ATTRS_ORIGIN_ACTIVE, null); } // } }); } // 恢复原来排序 // const children = shapeContainer.get('children'); // children.sort((obj1, obj2) => { // return obj1._INDEX - obj2._INDEX; // }); self.set('activeShapes', null); self.set('preHighlightShapes', null); } }, getGroupShapesByPoint: function getGroupShapesByPoint(point) { var self = this; var shapeContainer = self.get('shapeContainer'); var activeShapes = []; if (shapeContainer) { var xField = self.getXScale().field; var shapes = self.getShapes(); var originObj = self._getOriginByPoint(point); Util.each(shapes, function (shape) { var origin = shape.get('origin'); if (shape.get('visible') && origin) { // 有可能不是图形,而是label文本,所以判断一下 var shapeXValue = origin[FIELD_ORIGIN][xField]; if (shapeXValue === originObj[xField]) { activeShapes.push(shape); } } }); } return activeShapes; }, getSingleShapeByPoint: function getSingleShapeByPoint(point) { var self = this; var shapeContainer = self.get('shapeContainer'); var canvas = shapeContainer.get('canvas'); var pixelRatio = canvas.get('pixelRatio'); var result; if (shapeContainer) { result = shapeContainer.getShape(point.x * pixelRatio, point.y * pixelRatio); } if (result && result.get('origin')) { return result; } }, highlightShapes: function highlightShapes(_highlightShapes, highlightCfg) { var self = this; if (!Util.isArray(_highlightShapes)) { _highlightShapes = [_highlightShapes]; } var preHighlightShapes = self.get('activeShapes'); // 获取上次被激活的 shapes if (!isChange(preHighlightShapes, _highlightShapes)) { return; } if (preHighlightShapes) { self.clearActivedShapes(); } var shapes = self.getShapes(); var activedOptions = self.get('activedOptions'); var activeAnimate = activedOptions && activedOptions.animate; var activeStyle = activedOptions && activedOptions.style; Util.each(shapes, function (shape) { var changeAttrs = {}; shape.stopAnimate(); if (Util.indexOf(_highlightShapes, shape) !== -1) { Util.mix(changeAttrs, activeStyle, highlightCfg); // shape.setZIndex(1); // 提前 ZIndexUtil.toFront(shape); } else { Util.mix(changeAttrs, { fillOpacity: 0.3, // @2018-07-11 by blue.lb 由于线图只有stoke,fillOpacity不生效,最好还是直接改成整个图形透明度opacity opacity: 0.3 }); ZIndexUtil.resetZIndex(shape); } var originAttrs = getOriginAttrs(changeAttrs, shape); shape.setSilent(ATTRS_ORIGIN_ACTIVE, originAttrs); if (activeAnimate) { shape.animate(changeAttrs, 300); } else { shape.attr(changeAttrs); } }); self.set('preHighlightShapes', _highlightShapes); self.set('activeShapes', _highlightShapes); } }; module.exports = ActiveMixin; /***/ }), /* 397 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview the interaction when geom was selected * @author sima.zhang */ var Util = __webpack_require__(0); var FIELD_ORIGIN = '_origin'; var ZIndexUtil = __webpack_require__(199); function isSameShape(shape1, shape2) { if (Util.isNil(shape1) || Util.isNil(shape2)) { return false; } var shape1Origin = shape1.get('origin'); var shape2Origin = shape2.get('origin'); return Util.isEqual(shape1Origin, shape2Origin); } function getOriginAttrs(selectedCfg, shape) { var originAttrs = {}; Util.each(selectedCfg, function (v, k) { if (k === 'transform') { k = 'matrix'; } var originValue = shape.attr(k); if (Util.isArray(originValue)) { originValue = Util.cloneDeep(originValue); // 缓存原来的属性,由于 .attr('matrix') 是数组,所以此处需要深度复制 } originAttrs[k] = originValue; }); return originAttrs; } var SelectMixin = { _isAllowSelect: function _isAllowSelect() { var isAllowSelect = this.get('allowSelect'); if (Util.isNil(isAllowSelect)) { var type = this.get('type'); var coord = this.get('coord'); var coordType = coord && coord.type; if (type === 'interval' && coordType === 'theta') { // 饼图默认可以进行选中 return true; } } else { // 用户设置了 select 配置 return isAllowSelect; } return false; }, _onClick: function _onClick(ev) { var self = this; if (self._isAllowSelect()) { // 允许选中下才执行 // self.clearActivedShapes(); // 不需要清除hover效果 var shape = ev.shape; var shapeContainer = self.get('shapeContainer'); if (shape && shapeContainer.contain(shape)) { // 去除 !shape.get('animating') 的判定,点击反馈更加及时 self.setShapeSelected(shape); } } }, _bindSelectedAction: function _bindSelectedAction() { var self = this; var view = self.get('view'); var type = self.get('type'); view.on(type + ':click', Util.wrapBehavior(self, '_onClick')); }, _offSelectedAction: function _offSelectedAction() { var self = this; var view = self.get('view'); var type = self.get('type'); view.off(type + ':click', Util.getWrapBehavior(self, '_onClick')); }, _setShapeStatus: function _setShapeStatus(shape, status) { var self = this; var view = self.get('view'); var selectedOptions = self.get('selectedOptions') || {}; var animate = selectedOptions.animate !== false; // 默认允许动画 var canvas = view.get('canvas'); shape.set('selected', status); var shapeData = shape.get('origin'); if (status) { // 选中状态 var shapeName = shapeData.shape || self.getDefaultValue('shape'); if (Util.isArray(shapeName)) { shapeName = shapeName[0]; } var shapeFactory = self.get('shapeFactory'); var cfg = Util.mix({ geom: self, point: shapeData }, selectedOptions); var selectedStyle = shapeFactory.getSelectedCfg(shapeName, cfg); Util.mix(selectedStyle, cfg.style); // 用户设置的优先级更高 if (!shape.get('_originAttrs')) { // 缓存原有属性 if (shape.get('animating')) { // 停止动画 shape.stopAnimate(); } shape.set('_originAttrs', getOriginAttrs(selectedStyle, shape)); } // 选中时图形要到最上面 if (selectedOptions.toFront) { ZIndexUtil.toFront(shape); } if (animate) { shape.animate(selectedStyle, 300); } else { shape.attr(selectedStyle); canvas.draw(); } } else { var originAttrs = shape.get('_originAttrs'); // 取消选中时,要恢复到原先的位置 if (selectedOptions.toFront) { ZIndexUtil.resetZIndex(shape); } shape.set('_originAttrs', null); if (animate) { shape.animate(originAttrs, 300); } else { shape.attr(originAttrs); canvas.draw(); } } }, setShapeSelected: function setShapeSelected(shape) { var self = this; var selectedShapes = self._getSelectedShapes(); var selectedOptions = self.get('selectedOptions') || {}; var cancelable = selectedOptions.cancelable !== false; // 选中状态是否允许取消,默认允许 if (selectedOptions.mode === 'multiple') { // 支持多选 if (Util.indexOf(selectedShapes, shape) === -1) { selectedShapes.push(shape); self._setShapeStatus(shape, true); } else if (cancelable) { // 图形已经被选中并且选中状态允许取消选中 Util.Array.remove(selectedShapes, shape); self._setShapeStatus(shape, false); } } else { var selectedShape = selectedShapes[0]; if (cancelable) { // 如果允许取消,则选中null shape = isSameShape(selectedShape, shape) ? null : shape; } if (!isSameShape(selectedShape, shape)) { if (selectedShape) { self._setShapeStatus(selectedShape, false); } if (shape) { self._setShapeStatus(shape, true); } } } }, clearSelected: function clearSelected() { var self = this; var shapeContainer = self.get('shapeContainer'); if (shapeContainer && !shapeContainer.get('destroyed')) { var selectedShapes = self._getSelectedShapes(); Util.each(selectedShapes, function (shape) { self._setShapeStatus(shape, false); shape.set('_originAttrs', null); }); } }, /** * 设置记录对应的图形选中 * @param {Object} record 选中的记录 * @chainable * @return {Geom} 返回当前的 Geometry */ setSelected: function setSelected(record) { var self = this; var shapes = self.getShapes(); Util.each(shapes, function (shape) { var origin = shape.get('origin'); if (origin && origin[FIELD_ORIGIN] === record) { self.setShapeSelected(shape); } }); return this; }, _getSelectedShapes: function _getSelectedShapes() { var self = this; var shapes = self.getShapes(); var selectedShapes = []; Util.each(shapes, function (shape) { if (shape.get('selected')) { selectedShapes.push(shape); } }); self.set('selectedShapes', selectedShapes); return selectedShapes; } }; module.exports = SelectMixin; /***/ }), /* 398 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(0); module.exports = function (field) { if (Util.isArray(field)) { return field; } if (Util.isString(field)) { return field.split('*'); } return [field]; }; /***/ }), /* 399 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview 度量的控制器 * @author dxq613@gmail.com */ var Scale = __webpack_require__(105); var Util = __webpack_require__(0); var dateRegex = /^(?:(?!0000)[0-9]{4}([-/.]+)(?:(?:0?[1-9]|1[0-2])\1(?:0?[1-9]|1[0-9]|2[0-8])|(?:0?[13-9]|1[0-2])\1(?:29|30)|(?:0?[13578]|1[02])\1(?:31))|(?:[0-9]{2}(?:0[48]|[2468][048]|[13579][26])|(?:0[48]|[2468][048]|[13579][26])00)([-/.]+)0?2\2(?:29))(\s+([01]|([01][0-9]|2[0-3])):([0-9]|[0-5][0-9]):([0-9]|[0-5][0-9]))?$/; var TYPES = { LINEAR: 'linear', CAT: 'cat', TIME: 'time' }; var ScaleController = /*#__PURE__*/function () { function ScaleController(cfg) { // defs 列定义 this.defs = {}; this.viewTheme = { scales: {} }; // filtered fields this.filters = {}; Util.assign(this, cfg); } var _proto = ScaleController.prototype; _proto._getDef = function _getDef(field) { var defs = this.defs; var viewTheme = this.viewTheme; var def = null; if (viewTheme.scales[field] || defs[field]) { def = Util.mix({}, viewTheme.scales[field]); // 处理覆盖属性的问题 Util.each(defs[field], function (v, k) { if (Util.isNil(v)) { delete def[k]; } else { def[k] = v; } }); if (this.filters[field]) { delete def.min; delete def.max; } } return def; }; _proto._getDefaultType = function _getDefaultType(field, data) { var type = TYPES.LINEAR; var value = Util.Array.firstValue(data, field); if (Util.isArray(value)) { value = value[0]; } if (dateRegex.test(value)) { type = TYPES.TIME; } else if (Util.isString(value)) { type = TYPES.CAT; } return type; }; _proto._getScaleCfg = function _getScaleCfg(type, field, data) { var cfg = { field: field }; var values = Util.Array.values(data, field); cfg.values = values; if (!Scale.isCategory(type) && type !== 'time') { var range = Util.Array.getRange(values); cfg.min = range.min; cfg.max = range.max; cfg.nice = true; } if (type === 'time') { cfg.nice = false; } return cfg; }; _proto.createScale = function createScale(field, data) { var self = this; var def = self._getDef(field); var scale; var validData = data || []; var firstValue = Util.Array.firstValue(validData, field); if (Util.isNumber(field) || Util.isNil(firstValue) && !def) { scale = Scale.identity({ value: field, field: field.toString(), values: [field] }); } else { // 如果已经定义过这个度量 var type; if (def) { type = def.type; } type = type || self._getDefaultType(field, validData); var cfg = self._getScaleCfg(type, field, validData); if (def) { Util.mix(cfg, def); } scale = Scale[type](cfg); } return scale; }; return ScaleController; }(); module.exports = ScaleController; /***/ }), /* 400 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview The controller of coordinate * @author sima.zhang */ var Util = __webpack_require__(0); var Coord = __webpack_require__(401); var CoordController = /*#__PURE__*/function () { function CoordController(option) { this.type = 'rect'; this.actions = []; this.cfg = {}; Util.mix(this, option); this.option = option || {}; } var _proto = CoordController.prototype; _proto.reset = function reset(coordOption) { this.actions = coordOption.actions || []; this.type = coordOption.type; this.cfg = coordOption.cfg; this.option.actions = this.actions; this.option.type = this.type; this.option.cfg = this.cfg; return this; }; _proto._execActions = function _execActions(coord) { var actions = this.actions; Util.each(actions, function (action) { var m = action[0]; coord[m](action[1], action[2]); }); }; _proto.hasAction = function hasAction(actionName) { var actions = this.actions; var rst = false; Util.each(actions, function (action) { if (actionName === action[0]) { rst = true; return false; } }); return rst; } /** * 创建坐标系对象 * @param {Object} start 坐标系起始点 * @param {Object} end 坐标系结束点 * @return {Function} 坐标系的构造函数 */ ; _proto.createCoord = function createCoord(start, end) { var self = this; var type = self.type; var cfg = self.cfg; var C; // 构造函数 var coord; var coordCfg = Util.mix({ start: start, end: end }, cfg); if (type === 'theta') { // definition of theta coord C = Coord.Polar; if (!self.hasAction('transpose')) { self.transpose(); // 极坐标,同时transpose } coord = new C(coordCfg); coord.type = type; } else { C = Coord[Util.upperFirst(type || '')] || Coord.Rect; coord = new C(coordCfg); } self._execActions(coord); return coord; }; _proto.rotate = function rotate(angle) { angle = angle * Math.PI / 180; this.actions.push(['rotate', angle]); return this; }; _proto.reflect = function reflect(dim) { this.actions.push(['reflect', dim]); return this; }; _proto.scale = function scale(sx, sy) { this.actions.push(['scale', sx, sy]); return this; }; _proto.transpose = function transpose() { this.actions.push(['transpose']); return this; }; return CoordController; }(); module.exports = CoordController; /***/ }), /* 401 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; /** * @fileOverview the entry of coordinate * @author sima.zhang1990@gmail.com */ var Coord = __webpack_require__(56); Coord.Cartesian = __webpack_require__(402); Coord.Rect = Coord.Cartesian; Coord.Polar = __webpack_require__(403); Coord.Helix = __webpack_require__(404); module.exports = Coord; /***/ }), /* 402 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(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 _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } 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 _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(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 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 _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } /** * @fileOverview the class of Cartesian Coordinate * @author sima.zhang */ var mix = __webpack_require__(10); var Base = __webpack_require__(56); var Cartesian = /*#__PURE__*/function (_Base) { _inherits(Cartesian, _Base); _createClass(Cartesian, [{ key: "getDefaultCfg", /** * @override */ value: function getDefaultCfg() { var cfg = _get(_getPrototypeOf(Cartesian.prototype), "getDefaultCfg", this).call(this); return mix({}, cfg, { start: { x: 0, y: 0 }, end: { x: 0, y: 0 }, type: 'cartesian', isRect: true }); } }]); function Cartesian(cfg) { var _this; _classCallCheck(this, Cartesian); _this = _possibleConstructorReturn(this, _getPrototypeOf(Cartesian).call(this, cfg)); _this._init(); return _this; } _createClass(Cartesian, [{ key: "_init", value: function _init() { var start = this.start, end = this.end; var x = { start: start.x, end: end.x }; var y = { start: start.y, end: end.y }; this.x = x; this.y = y; } }, { key: "convertPoint", value: function convertPoint(point) { var x; var y; if (this.isTransposed) { x = point.y; y = point.x; } else { x = point.x; y = point.y; } return { x: this.convertDim(x, 'x'), y: this.convertDim(y, 'y') }; } }, { key: "invertPoint", value: function invertPoint(point) { var x = this.invertDim(point.x, 'x'); var y = this.invertDim(point.y, 'y'); if (this.isTransposed) { return { x: y, y: x }; } return { x: x, y: y }; } }]); return Cartesian; }(Base); module.exports = Cartesian; /***/ }), /* 403 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(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 _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } 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 _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(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 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 _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } /** * @fileOverview the class of Polar Coordinate * @author sima.zhang */ var MatrixUtil = __webpack_require__(50); var isNumberEqual = __webpack_require__(30); var mix = __webpack_require__(10); var Base = __webpack_require__(56); var mat3 = MatrixUtil.mat3; var vec2 = MatrixUtil.vec2; var vec3 = MatrixUtil.vec3; var Polar = /*#__PURE__*/function (_Base) { _inherits(Polar, _Base); _createClass(Polar, [{ key: "getDefaultCfg", value: function getDefaultCfg() { var cfg = _get(_getPrototypeOf(Polar.prototype), "getDefaultCfg", this).call(this); return mix({}, cfg, { startAngle: -Math.PI / 2, endAngle: Math.PI * 3 / 2, innerRadius: 0, type: 'polar', isPolar: true }); } }]); function Polar(cfg) { var _this; _classCallCheck(this, Polar); _this = _possibleConstructorReturn(this, _getPrototypeOf(Polar).call(this, cfg)); _this._init(); return _this; } _createClass(Polar, [{ key: "_init", value: function _init() { var radius = this.radius; var innerRadius = this.innerRadius; var center = this.center; var startAngle = this.startAngle; var endAngle = this.endAngle; while (endAngle < startAngle) { endAngle += Math.PI * 2; } this.endAngle = endAngle; var oneBox = this.getOneBox(); var oneWidth = oneBox.maxX - oneBox.minX; var oneHeight = oneBox.maxY - oneBox.minY; var left = Math.abs(oneBox.minX) / oneWidth; var top = Math.abs(oneBox.minY) / oneHeight; var width = this.width; var height = this.height; var maxRadius; var circleCentre; if (height / oneHeight > width / oneWidth) { // width为主 maxRadius = width / oneWidth; circleCentre = { x: center.x - (0.5 - left) * width, y: center.y - (0.5 - top) * maxRadius * oneHeight }; } else { // height为主 maxRadius = height / oneHeight; circleCentre = { x: center.x - (0.5 - left) * maxRadius * oneWidth, y: center.y - (0.5 - top) * height }; } if (!radius) { radius = maxRadius; } else if (radius > 0 && radius <= 1) { radius = maxRadius * radius; } else if (radius <= 0 || radius > maxRadius) { radius = maxRadius; } var x = { start: startAngle, end: endAngle }; var y = { start: innerRadius * radius, end: radius }; this.x = x; this.y = y; this.radius = radius; this.circleCentre = circleCentre; this.center = circleCentre; } }, { key: "getCenter", value: function getCenter() { return this.circleCentre; } }, { key: "getOneBox", value: function getOneBox() { var startAngle = this.startAngle; var endAngle = this.endAngle; if (Math.abs(endAngle - startAngle) >= Math.PI * 2) { return { minX: -1, maxX: 1, minY: -1, maxY: 1 }; } var xs = [0, Math.cos(startAngle), Math.cos(endAngle)]; var ys = [0, Math.sin(startAngle), Math.sin(endAngle)]; for (var i = Math.min(startAngle, endAngle); i < Math.max(startAngle, endAngle); i += Math.PI / 18) { xs.push(Math.cos(i)); ys.push(Math.sin(i)); } return { minX: Math.min.apply(Math, xs), maxX: Math.max.apply(Math, xs), minY: Math.min.apply(Math, ys), maxY: Math.max.apply(Math, ys) }; } }, { key: "getRadius", value: function getRadius() { return this.radius; } }, { key: "convertPoint", value: function convertPoint(point) { var center = this.getCenter(); var x = this.isTransposed ? point.y : point.x; var y = this.isTransposed ? point.x : point.y; x = this.convertDim(x, 'x'); y = this.convertDim(y, 'y'); return { x: center.x + Math.cos(x) * y, y: center.y + Math.sin(x) * y }; } }, { key: "invertPoint", value: function invertPoint(point) { var center = this.getCenter(); var vPoint = [point.x - center.x, point.y - center.y]; var x = this.x; var m = [1, 0, 0, 0, 1, 0, 0, 0, 1]; mat3.rotate(m, m, x.start); var vStart = [1, 0, 0]; vec3.transformMat3(vStart, vStart, m); vStart = [vStart[0], vStart[1]]; var angle = vec2.angleTo(vStart, vPoint, x.end < x.start); if (isNumberEqual(angle, Math.PI * 2)) { angle = 0; } var radius = vec2.length(vPoint); var xPercent = angle / (x.end - x.start); xPercent = x.end - x.start > 0 ? xPercent : -xPercent; var yPercent = this.invertDim(radius, 'y'); var rst = {}; rst.x = this.isTransposed ? yPercent : xPercent; rst.y = this.isTransposed ? xPercent : yPercent; return rst; } }]); return Polar; }(Base); module.exports = Polar; /***/ }), /* 404 */ /***/ (function(module, exports, __webpack_require__) { "use strict"; function _typeof(obj) { if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(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 _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); } function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } 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 _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(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } 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 _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; } function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); } /** * @fileOverview the class of Helix Coordinate * @author sima.zhang */ var MatrixUtil = __webpack_require__(50); var isNumberEqual = __webpack_require__(30); var mix = __webpack_require__(10); var Base = __webpack_require__(56); var vec2 = MatrixUtil.vec2; var Helix = /*#__PURE__*/function (_Base) { _inherits(Helix, _Base); _createClass(Helix, [{ key: "getDefaultCfg", value: function getDefaultCfg() { var cfg = _get(_getPrototypeOf(Helix.prototype), "getDefaultCfg", this).call(this); return mix({}, cfg, { startAngle: 1.25 * Math.PI, endAngle: 7.25 * Math.PI, innerRadius: 0, type: 'helix', isHelix: true }); } }]); function Helix(cfg) { var _this; _classCallCheck(this, Helix); _this = _possibleConstructorReturn(this, _getPrototypeOf(Helix).call(this, cfg)); _this._init(); return _this; } _createClass(Helix, [{ key: "_init", value: function _init() { var width = this.width; var height = this.height; var radius = this.radius; var innerRadius = this.innerRadius; var startAngle = this.startAngle; var endAngle = this.endAngle; var index = (endAngle - startAngle) / (2 * Math.PI) + 1; // 螺线圈数 var maxRadius = Math.min(width, height) / 2; if (radius && radius >= 0 && radius <= 1) { maxRadius = maxRadius * radius; } var d = Math.floor(maxRadius * (1 - innerRadius) / index); var a = d / (Math.PI * 2); // 螺线系数 var x = { start: startAngle, end: endAngle }; var y = { start: innerRadius * maxRadius, end: innerRadius * maxRadius + d * 0.99 }; this.a = a; this.d = d; this.x = x; this.y = y; } }, { key: "getCenter", value: function getCenter() { return this.center; } /** * 将百分比数据变成屏幕坐标 * @param {Object} point 归一化的点坐标 * @return {Object} 返回对应的屏幕坐标 */ }, { key: "convertPoint", value: function convertPoint(point) { var a = this.a; var center = this.center; var x; var y; if (this.isTransposed) { x = point.y; y = point.x; } else { x = point.x; y = point.y; } var thi = this.convertDim(x, 'x'); var r = a * thi; var newY = this.convertDim(y, 'y'); return { x: center.x + Math.cos(thi) * (r + newY), y: center.y + Math.sin(thi) * (r + newY) }; } /** * 将屏幕坐标点还原成百分比数据 * @param {Object} point 屏幕坐标 * @return {Object} 返回对应的归一化后的数据 */ }, { key: "invertPoint", value: function invertPoint(point) { var center = this.center; var a = this.a; var d = this.d + this.y.start; var v = vec2.subtract([], [point.x, point.y], [center.x, center.y]); var thi = vec2.angleTo(v, [1, 0], true); var rMin = thi * a; // 坐标与原点的连线在第一圈上的交点,最小r值 if (vec2.length(v) < rMin) { // 坐标与原点的连线不可能小于最小r值,但不排除因小数计算产生的略小于rMin的情况 rMin = vec2.length(v); } var index = Math.floor((vec2.length(v) - rMin) / d); // 当前点位于第index圈 thi = 2 * index * Math.PI + thi; var r = a * thi; var newY = vec2.length(v) - r; newY = isNumberEqual(newY, 0) ? 0 : newY; var x = this.invertDim(thi, 'x'); var y = this.invertDim(newY, 'y'); x = isNumberEqual(x, 0) ? 0 : x; y = isNumberEqual(y, 0) ? 0 : y; var rst = {}; rst.x = this.isTransposed ? y : x; rst.y = this.isTransposed ? x : y; return rst; } }]); return Helix; }(Base); module.exports = Helix; /***/ }), /* 405 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview The controller of axis * @author sima.zhang */ var Util = __webpack_require__(0); var _require = __webpack_require__(24), Axis = _require.Axis; var vec2 = Util.MatrixUtil.vec2; function formatTicks(ticks) { var tmp = []; if (ticks.length > 0) { tmp = ticks.slice(0); var first = tmp[0]; var last = tmp[tmp.length - 1]; if (first.value !== 0) { tmp.unshift({ value: 0 }); } if (last.value !== 1) { tmp.push({ value: 1 }); } } return tmp; } function fillAxisTicks(ticks, isLinear, gridCentering) { var result = []; if (ticks.length < 1) return result; if (ticks.length >= 2 && isLinear && gridCentering) { result.push({ text: '', tickValue: '', value: 0 }); } if (ticks[0].value !== 0) { result.push({ text: '', tickValue: '', value: 0 }); } result = result.concat(ticks); if (result[result.length - 1].value !== 1) { result.push({ text: '', tickValue: '', value: 1 }); } return result; } function getDefaultValueFromPosition(position, val) { if (val === void 0) { val = 0; } if (position === 'middle') { val = 0.5; } if (position.includes('%')) { val = parseInt(position, 10) / 100; } return val; } var AxisController = /*#__PURE__*/function () { function AxisController(cfg) { this.visible = true; this.canvas = null; this.container = null; this.coord = null; this.options = null; this.axes = []; Util.mix(this, cfg); } var _proto = AxisController.prototype; _proto._isHide = function _isHide(field) { // 对应的坐标轴是否隐藏 var options = this.options; if (options && options[field] === false) { return true; } return false; }; _proto._getMiddleValue = function _getMiddleValue(curValue, ticks, index, isLinear) { if (curValue === 0 && !isLinear) { return 0; } if (curValue === 1) { return 1; } var nextValue = ticks[index + 1].value; if (!isLinear && nextValue === 1) { return 1; } return (curValue + nextValue) / 2; }; _proto._getLineRange = function _getLineRange(coord, scale, dimType, index) { var start; var end; var isVertical; var field = scale.field; var options = this.options; var position = ''; if (options[field] && options[field].position) { position = options[field].position; } // TODO middle & percentage for position if (dimType === 'x') { // x轴的坐标轴,底部的横坐标 var y = position === 'top' ? 1 : 0; y = getDefaultValueFromPosition(position, y); start = { x: 0, y: y }; end = { x: 1, y: y }; isVertical = false; } else { // y轴坐标轴 if (index) { // 多轴的情况 var x = position === 'left' ? 0 : 1; x = getDefaultValueFromPosition(position, x); start = { x: x, y: 0 }; end = { x: x, y: 1 }; } else { // 单个y轴,或者第一个y轴 var _x = position === 'right' ? 1 : 0; _x = getDefaultValueFromPosition(position, _x); start = { x: _x, y: 0 }; end = { x: _x, y: 1 }; } isVertical = true; } start = coord.convert(start); end = coord.convert(end); return { start: start, end: end, isVertical: isVertical }; }; _proto._getLineCfg = function _getLineCfg(coord, scale, dimType, index) { var factor; var range = this._getLineRange(coord, scale, dimType, index); var isVertical = range.isVertical; // 标识该坐标轴是否是纵坐标 var start = range.start; var end = range.end; var center = coord.center; if (coord.isTransposed) { isVertical = !isVertical; } if (isVertical && start.x > center.x || !isVertical && start.y > center.y) { factor = 1; } else { factor = -1; } return { isVertical: isVertical, factor: factor, start: start, end: end }; } // 获取圆弧坐标轴配置项信息 ; _proto._getCircleCfg = function _getCircleCfg(coord) { var circleCfg = {}; var rangeX = coord.x; var rangeY = coord.y; var isReflectY = rangeY.start > rangeY.end; var start; if (coord.isTransposed) { start = { x: isReflectY ? 0 : 1, y: 0 }; } else { start = { x: 0, y: isReflectY ? 0 : 1 }; } start = coord.convert(start); var center = coord.circleCentre; var startVector = [start.x - center.x, start.y - center.y]; var normalVector = [1, 0]; var startAngle; if (start.y > center.y) { startAngle = vec2.angle(startVector, normalVector); } else { startAngle = vec2.angle(startVector, normalVector) * -1; } var endAngle = startAngle + (rangeX.end - rangeX.start); circleCfg.startAngle = startAngle; circleCfg.endAngle = endAngle; circleCfg.center = center; circleCfg.radius = Math.sqrt(Math.pow(start.x - center.x, 2) + Math.pow(start.y - center.y, 2)); circleCfg.inner = coord.innerRadius || 0; return circleCfg; }; _proto._getRadiusCfg = function _getRadiusCfg(coord) { var startAngle = coord.x.start; var factor = startAngle < 0 ? -1 : 1; var start; var end; if (coord.isTransposed) { start = { x: 0, y: 0 }; end = { x: 1, y: 0 }; } else { start = { x: 0, y: 0 }; end = { x: 0, y: 1 }; } return { factor: factor, start: coord.convert(start), end: coord.convert(end) }; } // 确定坐标轴的位置 ; _proto._getAxisPosition = function _getAxisPosition(coord, dimType, index, field) { var position = ''; // 用户自己定义了 position var options = this.options; // const VALID_POSITIONS = [ // 'top', // 'left', // 'right', // 'bottom' // ]; if (options[field] && options[field].position) { position = options[field].position; // if (VALID_POSITIONS.indexOf(position) > -1) { // return position; // } } else { var coordType = coord.type; if (coord.isRect) { if (dimType === 'x') { position = 'bottom'; } else if (dimType === 'y') { if (index) { position = 'right'; } else { position = 'left'; } } } else if (coordType === 'helix') { position = 'helix'; } else if (dimType === 'x') { position = coord.isTransposed ? 'radius' : 'circle'; } else { position = coord.isTransposed ? 'circle' : 'radius'; } } return position; } // 获取坐标轴构成的配置信息 ; _proto._getAxisDefaultCfg = function _getAxisDefaultCfg(coord, scale, type, position) { var self = this; var viewTheme = self.viewTheme; var cfg = {}; var options = self.options; var field = scale.field; cfg = Util.deepMix({}, viewTheme.axis[position], cfg, options[field]); cfg.viewTheme = viewTheme; if (cfg.title) { var title = Util.isPlainObject(cfg.title) ? cfg.title : {}; title.text = title.text || scale.alias || field; Util.deepMix(cfg, { title: title }); } cfg.ticks = scale.getTicks(); if (coord.isPolar && !scale.isCategory) { if (type === 'x' && Math.abs(coord.endAngle - coord.startAngle) === Math.PI * 2) { cfg.ticks.pop(); } } cfg.coord = coord; if (cfg.label && Util.isNil(cfg.label.autoRotate)) { cfg.label.autoRotate = true; // 允许自动旋转,避免重叠 } if (options.hasOwnProperty('xField') && options.xField.hasOwnProperty('grid')) { if (cfg.position === 'left') { Util.deepMix(cfg, options.xField); } } return cfg; } // 确定坐标轴的配置信息 ; _proto._getAxisCfg = function _getAxisCfg(coord, scale, verticalScale, dimType, index, viewId) { if (index === void 0) { index = ''; } var self = this; var position = self._getAxisPosition(coord, dimType, index, scale.field); var cfg = self._getAxisDefaultCfg(coord, scale, dimType, position); if (!Util.isEmpty(cfg.grid) && verticalScale) { // 生成 gridPoints var gridPoints = []; var tickValues = []; var verticalTicks = formatTicks(verticalScale.getTicks()); // 没有垂直的坐标点时不会只栅格 if (verticalTicks.length) { var ticks = fillAxisTicks(cfg.ticks, scale.isLinear, cfg.grid.align === 'center'); Util.each(ticks, function (tick, idx) { tickValues.push(tick.tickValue); var subPoints = []; var value = tick.value; if (cfg.grid.align === 'center') { value = self._getMiddleValue(value, ticks, idx, scale.isLinear); } if (!Util.isNil(value)) { var rangeX = coord.x; var rangeY = coord.y; Util.each(verticalTicks, function (verticalTick) { var x = dimType === 'x' ? value : verticalTick.value; var y = dimType === 'x' ? verticalTick.value : value; var point = coord.convert({ x: x, y: y }); if (coord.isPolar) { var center = coord.circleCentre; if (rangeY.start > rangeY.end) { y = 1 - y; } point.flag = rangeX.start > rangeX.end ? 0 : 1; point.radius = Math.sqrt(Math.pow(point.x - center.x, 2) + Math.pow(point.y - center.y, 2)); } subPoints.push(point); }); gridPoints.push({ _id: viewId + '-' + dimType + index + '-grid-' + tick.tickValue, points: subPoints }); } }); } cfg.grid.items = gridPoints; cfg.grid.tickValues = tickValues; } cfg.type = scale.type; return cfg; }; _proto._getHelixCfg = function _getHelixCfg(coord) { var helixCfg = {}; var a = coord.a; var startAngle = coord.startAngle; var endAngle = coord.endAngle; var index = 100; var crp = []; for (var i = 0; i <= index; i++) { var point = coord.convert({ x: i / 100, y: 0 }); crp.push(point.x); crp.push(point.y); } var axisStart = coord.convert({ x: 0, y: 0 }); helixCfg.a = a; helixCfg.startAngle = startAngle; helixCfg.endAngle = endAngle; helixCfg.crp = crp; helixCfg.axisStart = axisStart; helixCfg.center = coord.center; helixCfg.inner = coord.y.start; // 内半径 return helixCfg; }; _proto._drawAxis = function _drawAxis(coord, scale, verticalScale, dimType, viewId, xAxis, index) { var container = this.container; var canvas = this.canvas; var C; // 坐标轴类 var appendCfg; // 每个坐标轴 start end 等绘制边界的信息 if (coord.type === 'cartesian') { C = Axis.Line; appendCfg = this._getLineCfg(coord, scale, dimType, index); } else if (coord.type === 'helix' && dimType === 'x') { C = Axis.Helix; appendCfg = this._getHelixCfg(coord); } else if (dimType === 'x') { C = Axis.Circle; appendCfg = this._getCircleCfg(coord); } else { C = Axis.Line; appendCfg = this._getRadiusCfg(coord); } var cfg = this._getAxisCfg(coord, scale, verticalScale, dimType, index, viewId); cfg = Util.mix({}, cfg, appendCfg); if (dimType === 'y' && xAxis && xAxis.get('type') === 'circle') { cfg.circle = xAxis; } cfg._id = viewId + '-' + dimType; if (!Util.isNil(index)) { cfg._id = viewId + '-' + dimType + index; } Util.mix(cfg, { canvas: canvas, // 每个 axis 需要单独的 group, // 否则所有的 aixs 的文本都混在一起了 // 同时无法知道是哪个坐标轴的事件 group: container.addGroup({ viewId: viewId }) }); var axis = new C(cfg); axis.render(); this.axes.push(axis); return axis; }; _proto.createAxis = function createAxis(xScale, yScales, viewId) { var self = this; var coord = this.coord; var coordType = coord.type; // theta坐标系默认不绘制坐标轴 if (coordType !== 'theta' && !(coordType === 'polar' && coord.isTransposed)) { var xAxis; if (xScale && !self._isHide(xScale.field)) { xAxis = self._drawAxis(coord, xScale, yScales[0], 'x', viewId); // 绘制 x 轴 } if (!Util.isEmpty(yScales) && coordType !== 'helix') { Util.each(yScales, function (yScale, index) { if (!self._isHide(yScale.field)) { self._drawAxis(coord, yScale, xScale, 'y', viewId, xAxis, index); } }); } } }; _proto.changeVisible = function changeVisible(visible) { var axes = this.axes; Util.each(axes, function (axis) { axis.set('visible', visible); }); }; _proto.clear = function clear() { var self = this; var axes = self.axes; Util.each(axes, function (axis) { axis.destroy(); }); self.axes = []; }; return AxisController; }(); module.exports = AxisController; /***/ }), /* 406 */ /***/ (function(module, exports, __webpack_require__) { var Util = __webpack_require__(0); var Guide = __webpack_require__(407); var GuideController = /*#__PURE__*/function () { function GuideController(cfg) { this.guides = []; this.options = []; this.xScales = null; this.yScales = null; this.view = null; this.viewTheme = null; this.frontGroup = null; this.backGroup = null; Util.mix(this, cfg); } var _proto = GuideController.prototype; _proto._creatGuides = function _creatGuides() { var self = this; var options = this.options; var xScales = this.xScales; var yScales = this.yScales; var view = this.view; var viewTheme = this.viewTheme; // @2019-01-18 by blue.lb 这里如果给 backContainer 添加 group 的话,会直接导致 BBoxOfBackPlot 函数中计算 element.getBBox() 出错 if (this.backContainer && view) { this.backGroup = this.backContainer.addGroup({ viewId: view.get('_id') }); } if (this.frontContainer && view) { this.frontGroup = this.frontContainer.addGroup({ viewId: view.get('_id') }); } options.forEach(function (option) { var type = option.type; var config = Util.deepMix({ xScales: xScales, yScales: yScales, viewTheme: viewTheme }, viewTheme ? viewTheme.guide[type] : {}, option); type = Util.upperFirst(type); var guide = new Guide[type](config); self.guides.push(guide); }); return self.guides; }; _proto.line = function line(cfg) { if (cfg === void 0) { cfg = {}; } this.options.push(Util.mix({ type: 'line' }, cfg)); return this; }; _proto.arc = function arc(cfg) { if (cfg === void 0) { cfg = {}; } this.options.push(Util.mix({ type: 'arc' }, cfg)); return this; }; _proto.text = function text(cfg) { if (cfg === void 0) { cfg = {}; } this.options.push(Util.mix({ type: 'text' }, cfg)); return this; }; _proto.image = function image(cfg) { if (cfg === void 0) { cfg = {}; } this.options.push(Util.mix({ type: 'image' }, cfg)); return this; }; _proto.region = function region(cfg) { if (cfg === void 0) { cfg = {}; } this.options.push(Util.mix({ type: 'region' }, cfg)); return this; }; _proto.regionFilter = function regionFilter(cfg) { if (cfg === void 0) { cfg = {}; } this.options.push(Util.mix({ type: 'regionFilter' }, cfg)); return this; }; _proto.dataMarker = function dataMarker(cfg) { if (cfg === void 0) { cfg = {}; } this.options.push(Util.mix({ type: 'dataMarker' }, cfg)); return this; }; _proto.dataRegion = function dataRegion(cfg) { if (cfg === void 0) { cfg = {}; } this.options.push(Util.mix({ type: 'dataRegion' }, cfg)); return this; }; _proto.html = function html(cfg) { if (cfg === void 0) { cfg = {}; } this.options.push(Util.mix({ type: 'html' }, cfg)); return this; }; _proto.render = function render(coord) { var self = this; var view = self.view; var viewData = view && view.get('data'); var guides = self._creatGuides(); Util.each(guides, function (guide) { var container; if (guide.get('top')) { // 默认 guide 绘制到 backPlot,用户也可以声明 top: true,显示在最上层 // @2019-01-18 by blue.lb 直接用传入的就行 container = self.frontGroup || self.frontContainer; // container = self.frontContainer; } else { // @2019-01-18 by blue.lb 直接用传入的就行 container = self.backGroup || self.backContainer; // container = self.backContainer; } guide.render(coord, container, viewData, view); }); }; _proto.clear = function clear() { this.options = []; this.reset(); }; _proto.changeVisible = function changeVisible(visible) { var guides = this.guides; Util.each(guides, function (guide) { guide.changeVisible(visible); }); }; _proto.reset = function reset() { var guides = this.guides; Util.each(guides, function (guide) { guide.clear(); }); this.guides = []; // @2019-01-18 by blue.lb 删除这部分 this.backGroup && this.backGroup.remove(); this.frontGroup && this.frontGroup.remove(); }; return GuideController; }(); module.exports = GuideController; /***/ }), /* 407 */ /***/ (function(module, exports, __webpack_require__) { var _require = __webpack_require__(24), Guide = _require.Guide; var RegionFilter = __webpack_require__(408); Guide.RegionFilter = RegionFilter; module.exports = Guide; /***/ }), /* 408 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } var Util = __webpack_require__(0); var Guide = __webpack_require__(17); var _require = __webpack_require__(112), Path = _require.Path; var RegionFilter = /*#__PURE__*/function (_Guide) { _inheritsLoose(RegionFilter, _Guide); function RegionFilter() { return _Guide.apply(this, arguments) || this; } var _proto = RegionFilter.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Guide.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { name: 'regionFilter', zIndex: 1, top: true, start: null, end: null, color: null, apply: null, style: { opacity: 1 } }); }; _proto.render = function render(coord, group, viewData, view) { var self = this; var layer = group.addGroup(); layer.name = 'guide-region-filter'; view.once('afterpaint', function () { // 2018-08-08 by blue.lb padding为auto时,会导致重新绘制一次,这时候layer已经被销毁了 if (layer.get('destroyed')) return; self._drawShapes(view, layer); var clip = self._drawClip(coord); layer.attr({ clip: clip }); self.set('clip', clip); self.get('appendInfo') && layer.setSilent('appendInfo', self.get('appendInfo')); self.set('el', layer); }); }; _proto._drawShapes = function _drawShapes(view, layer) { var self = this; var output = []; var geoms = view.getAllGeoms(); geoms.map(function (geom) { var shapes = geom.getShapes(); var geomType = geom.get('type'); var filter = self._geomFilter(geomType); if (filter) { shapes.map(function (shape) { var shapeType = shape.type; // const shapeAttr = Util.mix({}, shape.attr()); var shapeAttr = Util.cloneDeep(shape.attr()); self._adjustDisplay(shapeAttr); var s = layer.addShape(shapeType, { attrs: shapeAttr }); output.push(s); return shape; }); } return geom; }); return output; }; _proto._drawClip = function _drawClip(coord) { var self = this; var start = self.parsePoint(coord, self.get('start')); var end = self.parsePoint(coord, self.get('end')); var path = [['M', start.x, start.y], ['L', end.x, start.y], ['L', end.x, end.y], ['L', start.x, end.y], ['z']]; var clip = new Path({ attrs: { path: path, opacity: 1 } }); return clip; }; _proto._adjustDisplay = function _adjustDisplay(attr) { var self = this; var color = self.get('color'); if (attr.fill) { attr.fill = attr.fillStyle = color; } attr.stroke = attr.strokeStyle = color; }; _proto._geomFilter = function _geomFilter(geomType) { var self = this; var apply = self.get('apply'); if (apply) { return Util.contains(apply, geomType); } return true; }; _proto.clear = function clear() { _Guide.prototype.clear.call(this); var clip = this.get('clip'); clip && clip.remove(); }; return RegionFilter; }(Guide); module.exports = RegionFilter; /***/ }), /* 409 */ /***/ (function(module, exports, __webpack_require__) { function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } var Util = __webpack_require__(0); var _require = __webpack_require__(24), Legend = _require.Legend; var Tail = __webpack_require__(410); var Shape = __webpack_require__(21); var bboxOfBackPlot = __webpack_require__(201); var plotRange2BBox = __webpack_require__(203); var Global = __webpack_require__(8); var FIELD_ORIGIN = '_origin'; var MARKER_SIZE = 4.5; var requireAnimationFrameFn = window.requestAnimationFrame || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame || window.msRequestAnimationFrame; var STROKE_MARKERS = ['cross', 'tick', 'plus', 'hyphen', 'line', 'hollowCircle', 'hollowSquare', 'hollowDiamond', 'hollowTriangle', 'hollowTriangleDown', 'hollowHexagon', 'hollowBowtie']; function _snapEqual(v1, v2, scale) { var isEqual; if (Util.isNil(scale)) { return false; } v1 = scale.translate(v1); v2 = scale.translate(v2); if (scale.isCategory) { isEqual = v1 === v2; } else { isEqual = Math.abs(v1 - v2) <= 1; } return isEqual; } function findGeom(geoms, value) { var rst; Util.each(geoms, function (geom) { if (geom.get('visible')) { var yScale = geom.getYScale(); if (yScale.field === value) { rst = geom; return; } } }); return rst; } var LegendController = /*#__PURE__*/function () { function LegendController(cfg) { var self = this; self.options = {}; Util.mix(self, cfg); self.clear(); var chart = self.chart; self.container = chart.get('frontPlot'); self.plotRange = chart.get('plotRange'); } var _proto = LegendController.prototype; _proto.clear = function clear() { var legends = this.legends; this.backRange = null; Util.each(legends, function (legendItems) { Util.each(legendItems, function (legend) { legend.destroy(); }); }); this.legends = {}; } // 获取坐标轴等背景元素占的范围,防止遮挡坐标轴 ; _proto.getBackRange = function getBackRange() { var backRange = this.backRange; if (!backRange) { var backPlot = this.chart.get('backPlot'); backRange = bboxOfBackPlot(backPlot, plotRange2BBox(this.chart.get('plotRange'))); var plotRange = this.plotRange; if (backRange.maxX - backRange.minX < plotRange.br.x - plotRange.tl.x && backRange.maxY - backRange.minY < plotRange.br.y - plotRange.tl.y) { // 如果背景小于则直接使用 plotRange backRange = { minX: plotRange.tl.x, minY: plotRange.tl.y, maxX: plotRange.br.x, maxY: plotRange.br.y }; } this.backRange = backRange; } return backRange; }; _proto._isFieldInView = function _isFieldInView(field, value, view) { var flag = false; var scales = view.get('scales'); var fieldScale = scales[field]; if (fieldScale && fieldScale.values) { flag = Util.inArray(fieldScale.values, value); } return flag; }; _proto._bindClickEvent = function _bindClickEvent(legend, scale, filterVals) { var self = this; var chart = self.chart; var views = chart.get('views'); var field = scale.field; var options = self.options; legend.on('itemclick', function (ev) { if (options.onClick && options.defaultClickHandlerEnabled !== true) { options.onClick(ev); } else { // if 'defaultClickHandlerEnabled' is true the default click behavior would be worked. var item = ev.item; var checked = ev.checked; var isSingleSelected = legend.get('selectedMode') === 'single'; // 图例的选中模式 var clickedValue = item.dataValue; // import: 需要取该图例项原始的数值 if (checked) { Util.Array.remove(filterVals, clickedValue); if (self._isFieldInView(field, clickedValue, chart)) { chart.filter(field, function (field) { return isSingleSelected ? field === clickedValue : !Util.inArray(filterVals, field); }); } Util.each(views, function (view) { if (self._isFieldInView(field, clickedValue, view)) { view.filter(field, function (field) { return isSingleSelected ? field === clickedValue : !Util.inArray(filterVals, field); }); } }); } else if (!isSingleSelected) { filterVals.push(clickedValue); if (self._isFieldInView(field, clickedValue, chart)) { chart.filter(field, function (field) { return !Util.inArray(filterVals, field); }); } Util.each(views, function (view) { if (self._isFieldInView(field, clickedValue, view)) { view.filter(field, function (field) { return !Util.inArray(filterVals, field); }); } }); } if (options.onClick) { options.onClick(ev); } chart.set('keepLegend', true); // 图例不重新渲染 chart.set('keepPadding', true); // 边框不重新计算 chart.repaint(); chart.set('keepPadding', false); chart.set('keepLegend', false); } }); }; _proto._bindClickEventForMix = function _bindClickEventForMix(legend) { var self = this; var chart = self.chart; var geoms = chart.getAllGeoms(); legend.on('itemclick', function (ev) { var itemField = ev.item.field; var checked = ev.checked; if (checked) { Util.each(geoms, function (geom) { var field = geom.getYScale().field; if (field === itemField) { geom.show(); } }); } else { Util.each(geoms, function (geom) { var field = geom.getYScale().field; if (field === itemField) { geom.hide(); } }); } }); }; _proto._filterLabels = function _filterLabels(shape, geom, visible) { if (shape.get('gLabel')) { shape.get('gLabel').set('visible', visible); } else { var labelCfg = geom.get('labelCfg'); if (labelCfg && labelCfg.fields && labelCfg.fields.length > 0) { var xScale = geom.getXScale(); var yScale = geom.getYScale(); var xField = xScale.field; var yField = yScale.field; var shapeData = shape.get('origin')._origin; var labelContainer = geom.get('labelContainer'); var labels = labelContainer.get('labelsGroup').get('children'); Util.each(labels, function (label) { var labelData = label.get('origin') || []; if (labelData[xField] === shapeData[xField] && labelData[yField] === shapeData[yField]) { label.set('visible', visible); shape.set('gLabel', label); } }); } } }; _proto._bindFilterEvent = function _bindFilterEvent(legend, scale) { var self = this; var chart = this.chart; var field = scale.field; legend.on('itemfilter', function (ev) { var range = ev.range; chart.filterShape(function (obj, shape, geom) { // @2018-12-21 by blue.lb 由于数值0直接被类型转换为false,这里需要做更精确一点的判断 if (!Util.isNil(obj[field])) { var filtered = obj[field] >= range[0] && obj[field] <= range[1]; // shape 带 label,则还需要隐藏 label self._filterLabels(shape, geom, filtered); return filtered; } return true; }); var geoms = chart.getAllGeoms() || []; var _loop = function _loop(i) { var geom = geoms[i]; if (geom.get('type') === 'heatmap') { requireAnimationFrameFn(function () { geom.drawWithRange(range); }); } }; for (var i = 0; i < geoms.length; i++) { _loop(i); } }); }; _proto._getShapeData = function _getShapeData(shape) { var originData = shape.get('origin'); if (Util.isArray(originData)) { originData = originData[0]; } return originData[FIELD_ORIGIN]; }; _proto._bindHoverEvent = function _bindHoverEvent(legend, field) { var self = this; var chart = self.chart; var geoms = chart.getAllGeoms(); var options = self.options; var canvas = chart.get('canvas'); legend.on('itemhover', function (ev) { var value = ev.item.value; var pre = self.pre; if (!pre) { Util.each(geoms, function (geom) { var shapeContainer = geom.get('shapeContainer'); var shapes = geom.getShapes(); var activeShapes = []; if (field) { var scale = geom.get('scales')[field]; Util.each(shapes, function (shape) { var origin = self._getShapeData(shape); if (origin && _snapEqual(origin[field], value, scale)) { activeShapes.push(shape); } }); } else if (geom.getYScale().field === value) { activeShapes = shapes; } if (!Util.isEmpty(activeShapes)) { ev.shapes = activeShapes; ev.geom = geom; if (options.onHover) { options.onHover(ev); shapeContainer.sort(); canvas.draw(); } else { geom.setShapesActived(activeShapes); } } }); self.pre = value; } else if (pre === value) { return; } }); legend.on('itemunhover', function (ev) { self.pre = null; if (options.onUnhover) { options.onUnhover(ev); } Util.each(geoms, function (geom) { if (geom.get('activeShapes')) { geom.clearActivedShapes(); canvas.draw(); } }); }); }; _proto._isFiltered = function _isFiltered(scale, filterVals, scaleValue) { if (!scale.isCategory) { return true; } var rst = true; scaleValue = scale.invert(scaleValue); Util.each(filterVals, function (val) { if (scale.getText(val) === scale.getText(scaleValue)) { rst = false; return false; } }); return rst; }; _proto._alignLegend = function _alignLegend(legend, pre, region, position) { var self = this; var viewTheme = self.viewTheme; var container = self.container; var canvas = container.get('canvas'); var width = canvas.get('width'); var height = canvas.get('height'); var totalRegion = self.totalRegion; var plotRange = self.plotRange; var backRange = self.getBackRange(); // 背景占得范围 var offsetX = legend.get('offset')[0] || 0; var offsetY = legend.get('offset')[1] || 0; // const offset = Util.isNil(legend.get('offset')) ? MARGIN : legend.get('offset'); var legendHeight = legend.getHeight(); var legendWidth = legend.getWidth(); var borderMargin = viewTheme.legend.margin; var innerMargin = viewTheme.legend.legendMargin; var legendNum = self.legends[position].length; var posArray = position.split('-'); var x = 0; var y = 0; var tempoRegion = legendNum > 1 ? totalRegion : region; if (posArray[0] === 'left' || posArray[0] === 'right') { height = plotRange.br.y; x = self._getXAlign(posArray[0], width, region, backRange, legendWidth, borderMargin); if (pre) { // @2018-10-19 by blue.lb 由于legend中并不存在y属性,这里需要先获取group再获取y值 // @2019-03-21 by blue.lb 由于内部实现问题,usehtml部分的实例可以直接获取x、y的 y = (pre.get('y') || pre.get('group').get('y')) + pre.getHeight() + innerMargin; } else { y = self._getYAlignVertical(posArray[1], height, tempoRegion, backRange, 0, borderMargin, canvas.get('height')); } } else if (posArray[0] === 'top' || posArray[0] === 'bottom') { y = self._getYAlignHorizontal(posArray[0], height, region, backRange, legendHeight, borderMargin); if (pre) { var preWidth = pre.getWidth(); // @2018-10-19 by blue.lb 由于legend中并不存在x属性,这里需要先获取group再获取x值 // @2019-03-21 by blue.lb 由于内部实现问题,usehtml部分的实例可以直接获取x、y的 x = (pre.get('x') || pre.get('group').get('x')) + preWidth + innerMargin; } else { x = self._getXAlign(posArray[1], width, tempoRegion, backRange, 0, borderMargin); if (posArray[1] === 'right') x = plotRange.br.x - tempoRegion.totalWidth; } } legend.move(x + offsetX, y + offsetY); }; _proto._getXAlign = function _getXAlign(pos, width, region, backRange, legendWidth, borderMargin) { var leftPos = backRange.minX - legendWidth - borderMargin[3] < 0 ? 0 : backRange.minX - legendWidth - borderMargin[3]; var x = pos === 'left' ? leftPos : backRange.maxX + borderMargin[1]; if (pos === 'center') { x = (width - region.totalWidth) / 2; } return x; }; _proto._getYAlignHorizontal = function _getYAlignHorizontal(pos, height, region, backRange, legendHeight, borderMargin) { var y = pos === 'top' ? backRange.minY - legendHeight - borderMargin[0] : backRange.maxY + borderMargin[2]; return y; }; _proto._getYAlignVertical = function _getYAlignVertical(pos, height, region, backRange, legendHeight, borderMargin, canvasHeight) { var y = pos === 'top' ? backRange.minY - legendHeight - borderMargin[0] : height - region.totalHeight; if (pos === 'center') { y = (canvasHeight - region.totalHeight) / 2; } return y; }; _proto._getSubRegion = function _getSubRegion(legends) { var maxWidth = 0; var maxHeight = 0; var totalWidth = 0; var totalHeight = 0; Util.each(legends, function (legend) { var width = legend.getWidth(); var height = legend.getHeight(); if (maxWidth < width) { maxWidth = width; } totalWidth += width; if (maxHeight < height) { maxHeight = height; } totalHeight += height; }); return { maxWidth: maxWidth, totalWidth: totalWidth, maxHeight: maxHeight, totalHeight: totalHeight }; }; _proto._getRegion = function _getRegion() { var self = this; var viewTheme = self.viewTheme; var legends = self.legends; var innerMargin = viewTheme.legend.legendMargin; var subs = []; var totalWidth = 0; var totalHeight = 0; Util.each(legends, function (legendItems) { var subRegion = self._getSubRegion(legendItems); subs.push(subRegion); totalWidth += subRegion.totalWidth + innerMargin; totalHeight += subRegion.totalHeight + innerMargin; }); return { totalWidth: totalWidth, totalHeight: totalHeight, subs: subs }; }; _proto._addCategoryLegend = function _addCategoryLegend(scale, attr, geom, filterVals, position) { var self = this; var field = scale.field; var legendOptions = self.options; var fieldOption = legendOptions[field]; if (fieldOption) { legendOptions = fieldOption; } var legends = self.legends; legends[position] = legends[position] || []; var container = self.container; var items = []; var ticks = scale.getTicks(); var isByAttr = true; var shapeType = geom.get('shapeType') || 'point'; var shape = geom.getDefaultValue('shape') || 'circle'; if (legendOptions[field] && legendOptions[field].marker) { // 用户为 field 对应的图例定义了 marker shape = legendOptions[field].marker; shapeType = 'point'; isByAttr = false; } else if (legendOptions.marker) { shape = legendOptions.marker; shapeType = 'point'; isByAttr = false; } var chart = self.chart; var viewTheme = self.viewTheme; var canvas = chart.get('canvas'); var plotRange = self.plotRange; var posArray = position.split('-'); var maxLength = posArray[0] === 'right' || posArray[0] === 'left' ? plotRange.bl.y - plotRange.tr.y : canvas.get('width'); Util.each(ticks, function (tick) { var text = tick.text; var name = text; var scaleValue = tick.value; var value = scale.invert(scaleValue); var cfg = { isInCircle: geom.isInCircle() }; var checked = filterVals ? self._isFiltered(scale, filterVals, scaleValue) : true; var colorAttr = geom.getAttr('color'); var shapeAttr = geom.getAttr('shape'); if (colorAttr) { // 存在颜色映射 if (colorAttr.callback && colorAttr.callback.length > 1) { // 多参数映射,阻止程序报错 var restArgs = Array(colorAttr.callback.length - 1).fill(''); cfg.color = colorAttr.mapping.apply(colorAttr, [value].concat(restArgs)).join('') || viewTheme.defaultColor; } else { cfg.color = colorAttr.mapping(value).join('') || viewTheme.defaultColor; } } if (isByAttr && shapeAttr) { // 存在形状映射 if (shapeAttr.callback && shapeAttr.callback.length > 1) { // 多参数映射,阻止程序报错 var _restArgs = Array(shapeAttr.callback.length - 1).fill(''); shape = shapeAttr.mapping.apply(shapeAttr, [value].concat(_restArgs)).join(''); } else { shape = shapeAttr.mapping(value).join(''); } } var shapeObject = Shape.getShapeFactory(shapeType); var marker = shapeObject.getMarkerCfg(shape, cfg); if (Global.legendMarkerRadius) { marker.radius = Global.legendMarkerRadius; } if (Util.isFunction(shape)) { marker.symbol = shape; } items.push({ value: name, // 图例项显示文本的内容 dataValue: value, // 图例项对应原始数据中的数值 checked: checked, marker: marker }); }); var legendCfg = Util.deepMix({}, viewTheme.legend[posArray[0]], legendOptions[field] || legendOptions, { viewId: chart.get('_id'), maxLength: maxLength, items: items, container: container, position: [0, 0] }); if (legendCfg.title) { Util.deepMix(legendCfg, { title: { text: scale.alias || scale.field } }); } var legend; if (self._isTailLegend(legendOptions, geom)) { legendCfg.chart = self.chart; legendCfg.geom = geom; legend = new Tail(legendCfg); } else { if (legendOptions.useHtml) { var canvasEle = container.get('canvas').get('el'); container = legendOptions.container; if (Util.isString(container) && /^\#/.test(container)) { // 如果传入 dom 节点的 id var id = container.replace('#', ''); container = document.getElementById(id); } if (!container) { container = canvasEle.parentNode; } legendCfg.container = container; if (legendCfg.legendStyle === undefined) legendCfg.legendStyle = {}; legendCfg.legendStyle.CONTAINER_CLASS = _extends({}, legendCfg.legendStyle.CONTAINER_CLASS, { position: 'absolute', overflow: 'auto', 'z-index': canvasEle.style.zIndex === '' ? 1 : parseInt(canvasEle.style.zIndex, 10) + 1 }); if (legendOptions.flipPage) { legendCfg.legendStyle.CONTAINER_CLASS.height = posArray[0] === 'right' || posArray[0] === 'left' ? maxLength + 'px' : 'auto'; legendCfg.legendStyle.CONTAINER_CLASS.width = !(posArray[0] === 'right' || posArray[0] === 'left') ? maxLength + 'px' : 'auto'; legend = new Legend.CatPageHtml(legendCfg); } else { legend = new Legend.CatHtml(legendCfg); } } else { legend = new Legend.Category(legendCfg); } } self._bindClickEvent(legend, scale, filterVals); legends[position].push(legend); return legend; }; _proto._bindChartMove = function _bindChartMove(scale) { var chart = this.chart; var legends = this.legends; chart.on('plotmove', function (ev) { var selected = false; if (ev.target) { var origin = ev.target.get('origin'); if (origin) { var data = origin[FIELD_ORIGIN] || origin[0][FIELD_ORIGIN]; var field = scale.field; if (data) { var value = data[field]; Util.each(legends, function (legendItems) { Util.each(legendItems, function (legend) { selected = true; !legend.destroyed && legend.activate(value); }); }); } } } if (!selected) { Util.each(legends, function (legendItems) { Util.each(legendItems, function (legend) { !legend.destroyed && legend.deactivate(); }); }); } }); }; _proto._addContinuousLegend = function _addContinuousLegend(scale, attr, position) { var self = this; var legends = self.legends; legends[position] = legends[position] || []; var container = self.container; var field = scale.field; var ticks = scale.getTicks(); var items = []; var legend; var minValue; var maxValue; var viewTheme = self.viewTheme; Util.each(ticks, function (tick) { var scaleValue = tick.value; var invertValue = scale.invert(scaleValue); var attrValue = attr.mapping(invertValue).join(''); items.push({ value: tick.tickValue, // tick.text attrValue: attrValue, color: attrValue, scaleValue: scaleValue }); if (scaleValue === 0) { minValue = true; } if (scaleValue === 1) { maxValue = true; } }); if (!minValue) { items.push({ value: scale.min, attrValue: attr.mapping(0).join(''), color: attr.mapping(0).join(''), scaleValue: 0 }); } if (!maxValue) { items.push({ value: scale.max, attrValue: attr.mapping(1).join(''), color: attr.mapping(1).join(''), scaleValue: 1 }); } var options = self.options; var posArray = position.split('-'); var defaultCfg = viewTheme.legend[posArray[0]]; if (options && options.slidable === false || options[field] && options[field].slidable === false) { defaultCfg = Util.mix({}, defaultCfg, viewTheme.legend.gradient); } var legendCfg = Util.deepMix({}, defaultCfg, options[field] || options, { items: items, attr: attr, formatter: scale.formatter, container: container, position: [0, 0] }); if (legendCfg.title) { Util.deepMix(legendCfg, { title: { text: scale.alias || scale.field } }); } if (attr.type === 'color') { legend = new Legend.Color(legendCfg); } else if (attr.type === 'size') { if (options && options.sizeType === 'circle') legend = new Legend.CircleSize(legendCfg);else legend = new Legend.Size(legendCfg); } else { return; } self._bindFilterEvent(legend, scale); legends[position].push(legend); return legend; }; _proto._isTailLegend = function _isTailLegend(opt, geom) { if (opt.hasOwnProperty('attachLast') && opt.attachLast) { var geomType = geom.get('type'); if (geomType === 'line' || geomType === 'lineStack' || geomType === 'area' || geomType === 'areaStack') return true; } return false; }; _proto._adjustPosition = function _adjustPosition(position, isTailLegend) { var pos; if (isTailLegend) { pos = 'right-top'; } else if (Util.isArray(position)) { pos = String(position[0]) + '-' + String(position[1]); } else { var posArr = position.split('-'); if (posArr.length === 1) { // 只用了left/right/bottom/top一个位置定位 if (posArr[0] === 'left') pos = 'left-bottom'; if (posArr[0] === 'right') pos = 'right-bottom'; if (posArr[0] === 'top') pos = 'top-center'; if (posArr[0] === 'bottom') pos = 'bottom-center'; } else { pos = position; } } return pos; }; _proto.addLegend = function addLegend(scale, attr, geom, filterVals) { var self = this; var legendOptions = self.options; var field = scale.field; var fieldOption = legendOptions[field]; var viewTheme = self.viewTheme; if (fieldOption === false) { // 如果不显示此图例 return null; } if (fieldOption && fieldOption.custom) { self.addCustomLegend(field); } else { var position = legendOptions.position || viewTheme.defaultLegendPosition; position = self._adjustPosition(position, self._isTailLegend(legendOptions, geom)); if (fieldOption && fieldOption.position) { // 如果对某个图例单独设置 position,则对 position 重新赋值 position = self._adjustPosition(fieldOption.position, self._isTailLegend(fieldOption, geom)); } var legend; if (scale.isLinear) { legend = self._addContinuousLegend(scale, attr, position); } else { legend = self._addCategoryLegend(scale, attr, geom, filterVals, position); } if (legend) { self._bindHoverEvent(legend, field); legendOptions.reactive && self._bindChartMove(scale); } } } /** * 自定义图例 * @param {string} field 自定义图例的数据字段名,可以为空 * @return {object} legend 自定义图例实例 */ ; _proto.addCustomLegend = function addCustomLegend(field) { var self = this; var chart = self.chart; var viewTheme = self.viewTheme; var container = self.container; var legendOptions = self.options; if (field) { legendOptions = legendOptions[field]; } var position = legendOptions.position || viewTheme.defaultLegendPosition; position = self._adjustPosition(position); var legends = self.legends; legends[position] = legends[position] || []; var items = legendOptions.items; if (!items) { return; } var geoms = chart.getAllGeoms(); Util.each(items, function (item) { var geom = findGeom(geoms, item.value); if (!Util.isPlainObject(item.marker)) { // 直接传入字符串或者回调函数时转换为对象,如 item.marker = 'circle' item.marker = { symbol: item.marker || 'circle', radius: Global.legendMarkerRadius || MARKER_SIZE }; if (Util.indexOf(STROKE_MARKERS, item.marker.symbol) !== -1) { item.marker.stroke = item.fill; } else { item.marker.fill = item.fill; } } else { // 用户传入对象 item.marker = { symbol: 'circle', fill: 'red', radius: 3 } item.marker.radius = item.marker.radius || Global.legendMarkerRadius || MARKER_SIZE; } var symbol = item.marker.symbol; if (Util.isString(symbol) && symbol.indexOf('hollow') !== -1) { item.marker.symbol = Util.lowerFirst(symbol.substr(6)); } item.checked = Util.isNil(item.checked) ? true : item.checked; item.geom = geom; }); var canvas = chart.get('canvas'); var plotRange = self.plotRange; var posArray = position.split('-'); var maxLength = posArray[0] === 'right' || posArray[0] === 'left' ? plotRange.bl.y - plotRange.tr.y : canvas.get('width'); var legendCfg = Util.deepMix({}, viewTheme.legend[posArray[0]], legendOptions, { maxLength: maxLength, items: items, container: container, position: [0, 0] }); var legend; if (legendOptions.useHtml) { var htmlContainer = legendOptions.container; if (/^\#/.test(container)) { // 如果传入 dom 节点的 id var id = htmlContainer.replace('#', ''); htmlContainer = document.getElementById(id); } else if (!htmlContainer) { htmlContainer = container.get('canvas').get('el').parentNode; } legendCfg.container = htmlContainer; if (legendCfg.legendStyle === undefined) legendCfg.legendStyle = {}; if (!legendCfg.legendStyle.CONTAINER_CLASS) { legendCfg.legendStyle.CONTAINER_CLASS = { height: posArray[0] === 'right' || posArray[0] === 'left' ? maxLength + 'px' : 'auto', width: !(posArray[0] === 'right' || posArray[0] === 'left') ? maxLength + 'px' : 'auto', position: 'absolute', overflow: 'auto' }; } if (legendOptions.flipPage) legend = new Legend.CatPageHtml(legendCfg);else legend = new Legend.CatHtml(legendCfg); } else legend = new Legend.Category(legendCfg); legends[position].push(legend); legend.on('itemclick', function (ev) { if (legendOptions.onClick) { // 用户自定义了图例点击事件 legendOptions.onClick(ev); } }); self._bindHoverEvent(legend); return legend; }; _proto.addMixedLegend = function addMixedLegend(scales, geoms) { var self = this; var legendOptions = self.options; var items = []; Util.each(scales, function (scale) { var value = scale.alias || scale.field; var fieldLegendOptions = legendOptions[scale.field]; Util.each(geoms, function (geom) { if (geom.getYScale() === scale && scale.values && scale.values.length > 0 && fieldLegendOptions !== false) { var shapeType = geom.get('shapeType') || 'point'; var shape = geom.getDefaultValue('shape') || 'circle'; var shapeObject = Shape.getShapeFactory(shapeType); var cfg = { color: geom.getDefaultValue('color') }; var marker = shapeObject.getMarkerCfg(shape, cfg); if (Global.legendMarkerRadius) { marker.radius = Global.legendMarkerRadius; } var item = { value: value, marker: marker, field: scale.field }; items.push(item); } }); // end of geom loop }); // end of scale loop var options = { custom: true, items: items }; self.options = Util.deepMix({}, options, self.options); var legend = self.addCustomLegend(); self._bindClickEventForMix(legend); }; _proto.alignLegends = function alignLegends() { var self = this; var legends = self.legends; var totalRegion = self._getRegion(legends); self.totalRegion = totalRegion; var i = 0; Util.each(legends, function (legendItems, position) { var region = /* self._getRegion(legendItems)*/ totalRegion.subs[i]; Util.each(legendItems, function (legend, index) { var pre = legendItems[index - 1]; if (!(legend.get('useHtml') && !legend.get('autoPosition'))) { self._alignLegend(legend, pre, region, position); } }); i++; }); return this; }; return LegendController; }(); module.exports = LegendController; /***/ }), /* 410 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @fileOverview The class of tail legend * @author Ye Liu */ var Util = __webpack_require__(0); // const Category = require('./category'); var Components = __webpack_require__(24); var Global = __webpack_require__(8); var Legend = Components.Legend; var Category = Legend.Category; var Tail = /*#__PURE__*/function (_Category) { _inheritsLoose(Tail, _Category); function Tail() { return _Category.apply(this, arguments) || this; } var _proto = Tail.prototype; _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Category.prototype.getDefaultCfg.call(this); return Util.mix({}, cfg, { /** * type标识 * @type {String} */ type: 'tail-legend', /** * 布局方式 * horizontal 水平 * vertical 垂直 * @type {String} */ layout: 'vertical', autoLayout: true }); }; _proto._addItem = function _addItem(item) { var itemsGroup = this.get('itemsGroup'); var x = this._getNextX(); var y = 0; var unCheckColor = this.get('unCheckColor'); var itemGroup = itemsGroup.addGroup({ x: 0, y: 0, value: item.value, scaleValue: item.scaleValue, checked: item.checked }); itemGroup.translate(x, y); itemGroup.set('viewId', itemsGroup.get('viewId')); var textStyle = this.get('textStyle'); var wordSpace = this.get('_wordSpaceing'); var startX = 0; if (item.marker) { // 如果有marker添加marker var markerAttrs = Util.mix({}, item.marker, { x: item.marker.radius, y: 0 }); if (!item.checked) { if (markerAttrs.fill) { markerAttrs.fill = unCheckColor; } if (markerAttrs.stroke) { markerAttrs.stroke = unCheckColor; } } var markerShape = itemGroup.addShape('marker', { type: 'marker', attrs: markerAttrs }); markerShape.attr('cursor', 'pointer'); markerShape.name = 'legend-marker'; startX += markerShape.getBBox().width + wordSpace; } var textAttrs = Util.mix({}, textStyle, { x: startX, y: 0, text: this._formatItemValue(item.value) }); if (!item.checked) { Util.mix(textAttrs, { fill: unCheckColor }); } var textShape = itemGroup.addShape('text', { attrs: textAttrs }); textShape.attr('cursor', 'pointer'); textShape.name = 'legend-text'; this.get('appendInfo') && textShape.setSilent('appendInfo', this.get('appendInfo')); // 添加一个包围矩形,用于事件支持 var bbox = itemGroup.getBBox(); var itemWidth = this.get('itemWidth'); var wrapperShape = itemGroup.addShape('rect', { attrs: { x: x, y: y - bbox.height / 2, fill: '#fff', fillOpacity: 0, width: itemWidth || bbox.width, height: bbox.height } }); wrapperShape.attr('cursor', 'pointer'); wrapperShape.setSilent('origin', item); // 保存图例项相关的数据,便于事件操作 wrapperShape.name = 'legend-item'; this.get('appendInfo') && wrapperShape.setSilent('appendInfo', this.get('appendInfo')); itemGroup.name = 'legendGroup'; return itemGroup; }; _proto._adjust = function _adjust() { var self = this; var geom = self.get('geom'); if (geom) { var groupMatrix = self.get('group').attr('matrix'); groupMatrix[7] = 0; var dataArray = self.get('geom').get('dataArray'); var groups = this.get('itemsGroup').get('children'); var index = 0; Util.each(groups, function (groupItem) { var dArray = dataArray[index]; var lastY = dArray[dArray.length - 1].y; if (Util.isArray(lastY)) { lastY = lastY[1]; } var groupHeight = groupItem.getBBox().height; var x = groupItem.get('x'); var y = lastY - groupHeight / 2; groupItem.translate(x, y); index++; }); if (self.get('autoLayout')) { self._antiCollision(groups); } } }; _proto.render = function render() { var _this = this; _Category.prototype.render.call(this); var chart = this.get('chart'); chart.once('afterpaint', function () { _this._adjust(); }); }; _proto._getPreviousY = function _getPreviousY(item) { var y = item.attr('matrix')[7]; var height = item.getBBox().height; return y + height; }; _proto._adjustDenote = function _adjustDenote(group, start, end) { var margin = Global.legend.legendMargin; var x0 = -2; var x2 = -margin * 2; group.addShape('path', { attrs: { path: 'M' + x0 + ',' + start + 'L' + x2 + ',' + (end + 3), lineWidth: 1, lineDash: [2, 2], stroke: '#999999' } }); }; _proto._antiCollision = function _antiCollision(items) { if (items === void 0) { items = []; } if (!items.length) return; var self = this; items.sort(function (a, b) { var ay = a.attr('matrix')[7]; var by = b.attr('matrix')[7]; return ay - by; }); var overlapping = true; var plotRange = self.get('chart').get('plotRange'); var startY = plotRange.tl.y; var totalHeight = Math.abs(startY - plotRange.bl.y); var elementHeight = items[0].getBBox().height; var minY = Number.MIN_VALUE; var maxY = 0; var boxes = items.map(function (item) { var y = item.attr('matrix')[7]; if (y > maxY) { maxY = y; } if (y < minY) { minY = y; } return { size: item.getBBox().height, targets: [y - startY] }; }); minY -= startY; var i = 0; while (overlapping) { for (var _i = 0; _i < boxes.length; _i++) { var box = boxes[_i]; var target = (Math.min.apply(minY, box.targets) + Math.max.apply(minY, box.targets)) / 2; box.pos = Math.min(Math.max(minY, target - box.size / 2), totalHeight - box.size); } overlapping = false; i = boxes.length; while (i--) { if (i > 0) { var previous = boxes[i - 1]; var current = boxes[i]; if (previous.pos + previous.size > current.pos) { // overlapping previous.size += current.size; previous.targets = previous.targets.concat(current.targets); boxes.splice(i, 1); overlapping = true; } } } // end of while i } // end of while // adjust y i = 0; var group = this.get('itemsGroup').addGroup(); boxes.forEach(function (b) { var posInCompositeBox = startY + elementHeight; b.targets.forEach(function () { var origin_y = items[i].attr('matrix')[7]; var y = b.pos + posInCompositeBox - elementHeight / 2; var dist = Math.abs(origin_y - y); if (dist > elementHeight / 2) { self._adjustDenote(group, y, origin_y - self.get('group').attr('matrix')[7] / 2); } items[i].translate(0, -origin_y); items[i].translate(0, y); posInCompositeBox += elementHeight; i++; }); }); } // end of antiCollision ; return Tail; }(Category); module.exports = Tail; /***/ }), /* 411 */ /***/ (function(module, exports, __webpack_require__) { function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } /** * @fileOverview The controller of tooltip * @author sima.zhang */ var Util = __webpack_require__(0); var Shape = __webpack_require__(21); var _require = __webpack_require__(24), Tooltip = _require.Tooltip; var MatrixUtil = Util.MatrixUtil; var Vector2 = MatrixUtil.vec2; var TYPE_SHOW_MARKERS = ['line', 'area', 'path', 'areaStack']; // 默认展示 tooltip marker 的几何图形 var TYPE_SHOW_CROSSHAIRS = ['line', 'area', 'point']; // 默认展示十字瞄准线的几何图形 // TODO FIXME this is HARD CODING var IGNORE_TOOLTIP_ITEM_PROPERTIES = ['marker', 'showMarker']; function _indexOfArray(items, item) { var rst = -1; Util.each(items, function (sub, index) { var isEqual = true; for (var key in item) { if (item.hasOwnProperty(key) && !IGNORE_TOOLTIP_ITEM_PROPERTIES.includes(key)) { if (!Util.isObject(item[key]) && item[key] !== sub[key]) { isEqual = false; break; } } } if (isEqual) { rst = index; return false; } }); return rst; } // 判断是否有样式 function _hasClass(dom, className) { if (!dom) { return false; } var cls = ''; if (!dom.className) return false; if (!Util.isNil(dom.className.baseVal)) { cls = dom.className.baseVal; } else { cls = dom.className; } return cls.includes(className); } function _isParent(dom, cls) { var parent = dom.parentNode; var rst = false; while (parent && parent !== document.body) { if (_hasClass(parent, cls)) { rst = true; break; } parent = parent.parentNode; } return rst; } // 去除重复的值, 去除不同图形相同数据,只展示一份即可 function _uniqItems(items) { var tmp = []; Util.each(items, function (item) { var index = _indexOfArray(tmp, item); if (index === -1) { tmp.push(item); } else { tmp[index] = item; } }); return tmp; } var TooltipController = /*#__PURE__*/function () { function TooltipController(cfg) { Util.assign(this, cfg); this.timeStamp = 0; // tooltip 锁定不能移动 this.locked = false; } var _proto = TooltipController.prototype; _proto._normalizeEvent = function _normalizeEvent(event) { var chart = this.chart; var canvas = this._getCanvas(); var point = canvas.getPointByClient(event.clientX, event.clientY); var pixelRatio = canvas.get('pixelRatio'); point.x = point.x / pixelRatio; point.y = point.y / pixelRatio; var views = chart.getViewsByPoint(point); point.views = views; return point; }; _proto._getCanvas = function _getCanvas() { return this.chart.get('canvas'); }; _proto._getTriggerEvent = function _getTriggerEvent() { var options = this.options; var triggerOn = options.triggerOn; var eventName; if (!triggerOn || triggerOn === 'mousemove') { eventName = 'plotmove'; } else if (triggerOn === 'click') { eventName = 'plotclick'; } else if (triggerOn === 'none') { eventName = null; } return eventName; }; _proto._getDefaultTooltipCfg = function _getDefaultTooltipCfg() { var self = this; var chart = self.chart; var viewTheme = self.viewTheme; var options = self.options; var defaultCfg = Util.mix({}, viewTheme.tooltip); var geoms = chart.getAllGeoms().filter(function (geom) { return geom.get('visible'); }); var shapes = []; Util.each(geoms, function (geom) { var type = geom.get('type'); var adjusts = geom.get('adjusts'); var isSymmetric = false; if (adjusts) { Util.each(adjusts, function (adjust) { if (adjust.type === 'symmetric' || adjust.type === 'Symmetric') { isSymmetric = true; return false; } }); } if (Util.indexOf(shapes, type) === -1 && !isSymmetric) { shapes.push(type); } }); var isTransposed = geoms.length && geoms[0].get('coord') ? geoms[0].get('coord').isTransposed : false; var crosshairsCfg; if (geoms.length && geoms[0].get('coord') && geoms[0].get('coord').type === 'cartesian') { if (shapes[0] === 'interval' && options.shared !== false) { // 直角坐标系下 interval 的 crosshair 为矩形背景框 var crosshairs = Util.mix({}, viewTheme.tooltipCrosshairsRect); crosshairs.isTransposed = isTransposed; crosshairsCfg = { zIndex: 0, // 矩形背景框不可覆盖 geom crosshairs: crosshairs }; } else if (Util.indexOf(TYPE_SHOW_CROSSHAIRS, shapes[0]) > -1) { var _crosshairs = Util.mix({}, viewTheme.tooltipCrosshairsLine); _crosshairs.isTransposed = isTransposed; crosshairsCfg = { crosshairs: _crosshairs }; } } return Util.mix(defaultCfg, crosshairsCfg, {}); }; _proto._bindEvent = function _bindEvent() { var chart = this.chart; var triggerEvent = this._getTriggerEvent(); if (triggerEvent) { chart.on(triggerEvent, Util.wrapBehavior(this, 'onMouseMove')); chart.on('plotleave', Util.wrapBehavior(this, 'onMouseOut')); } }; _proto._offEvent = function _offEvent() { var chart = this.chart; var triggerEvent = this._getTriggerEvent(); if (triggerEvent) { chart.off(triggerEvent, Util.getWrapBehavior(this, 'onMouseMove')); chart.off('plotleave', Util.getWrapBehavior(this, 'onMouseOut')); } }; _proto._setTooltip = function _setTooltip(point, items, markersItems, target) { var self = this; var tooltip = self.tooltip; var prePoint = self.prePoint; if (!prePoint || prePoint.x !== point.x || prePoint.y !== point.y) { items = _uniqItems(items); self.prePoint = point; var chart = self.chart; var viewTheme = self.viewTheme; var x = Util.isArray(point.x) ? point.x[point.x.length - 1] : point.x; var y = Util.isArray(point.y) ? point.y[point.y.length - 1] : point.y; if (!tooltip.get('visible')) { chart.emit('tooltip:show', { x: x, y: y, tooltip: tooltip }); } var first = items[0]; var title = first.title || first.name; if (tooltip.isContentChange(title, items)) { chart.emit('tooltip:change', { tooltip: tooltip, x: x, y: y, items: items }); // bugfix: when set the title in the tooltip:change event does not take effect. title = items[0].title || items[0].name; tooltip.setContent(title, items); if (!Util.isEmpty(markersItems)) { if (self.options.hideMarkers === true) { // 不展示 tooltip marker tooltip.set('markerItems', markersItems); // 用于 tooltip 辅助线的定位 } else { tooltip.setMarkers(markersItems, viewTheme.tooltipMarker); } } else { tooltip.clearMarkers(); // clearMarkers 只会将 markerItems 从 markerGroup 中移除 // 所以我们还要将 markerItems 从 tooltip 中移除 // 这么做是为了防止上一次设置 marker 时的 markerItems 影响此次 tooltip 辅助线的定位 tooltip.set('markerItems', []); } } var canvas = this._getCanvas(); if (target === canvas && tooltip.get('type') === 'mini') { // filter mini tooltip tooltip.hide(); } else { tooltip.setPosition(x, y, target); tooltip.show(); } } }; _proto.hideTooltip = function hideTooltip() { var tooltip = this.tooltip; var chart = this.chart; var canvas = this._getCanvas(); this.prePoint = null; tooltip.hide(); chart.emit('tooltip:hide', { tooltip: tooltip }); canvas.draw(); }; _proto.onMouseMove = function onMouseMove(ev) { // 锁定时不移动 tooltip if (Util.isEmpty(ev.views) || this.locked) { return; } var lastTimeStamp = this.timeStamp; var timeStamp = +new Date(); var point = { x: ev.x, y: ev.y }; if (timeStamp - lastTimeStamp > 16 && !this.chart.get('stopTooltip')) { this.showTooltip(point, ev.views, ev.shape); this.timeStamp = timeStamp; } }; _proto.onMouseOut = function onMouseOut(ev) { var tooltip = this.tooltip; // 锁定 tooltip 时不隐藏 if (!tooltip.get('visible') || !tooltip.get('follow') || this.locked) { return; } // 除非离开 plot 时鼠标依然在图形上,这段逻辑没有意义 // if (ev && ev.target !== canvas) { // return; // } if (ev && ev.toElement && (_hasClass(ev.toElement, 'g2-tooltip') || _isParent(ev.toElement, 'g2-tooltip'))) { return; } this.hideTooltip(); }; _proto.renderTooltip = function renderTooltip() { var self = this; if (self.tooltip) { // tooltip 对象已经创建 return; } var chart = self.chart; var viewTheme = self.viewTheme; var canvas = self._getCanvas(); var defaultCfg = self._getDefaultTooltipCfg(); var options = self.options; options = Util.deepMix({ plotRange: chart.get('plotRange'), capture: false, canvas: canvas, frontPlot: chart.get('frontPlot'), viewTheme: viewTheme.tooltip, backPlot: chart.get('backPlot') }, defaultCfg, options); if (options.crosshairs && options.crosshairs.type === 'rect') { options.zIndex = 0; // toolip 背景框不可遮盖住 geom,防止用户配置了 crosshairs } options.visible = false; // @2018-09-13 by blue.lb 如果设置shared为false不需要指定position // if (options.shared === false && Util.isNil(options.position)) { // options.position = 'top'; // } var tooltip; if (options.type === 'mini') { options.crosshairs = false; // this.options.shared = false; options.position = 'top'; tooltip = new Tooltip.Mini(options); } else if (options.useHtml) { tooltip = new Tooltip.Html(options); } else { tooltip = new Tooltip.Canvas(options); } self.tooltip = tooltip; var triggerEvent = self._getTriggerEvent(); var tooltipContainer = tooltip.get('container'); if (!tooltip.get('enterable') && triggerEvent === 'plotmove') { // 鼠标不允许进入 tooltip 容器 if (tooltipContainer) { tooltipContainer.onmousemove = function (e) { // 避免 tooltip 频繁闪烁 var eventObj = self._normalizeEvent(e); chart.emit(triggerEvent, eventObj); }; } } // 优化:鼠标移入 tooltipContainer 然后再移出时,需要隐藏 tooltip if (tooltipContainer) { tooltipContainer.onmouseleave = function () { if (!self.locked) { self.hideTooltip(); } }; } self._bindEvent(); }; _proto._formatMarkerOfItem = function _formatMarkerOfItem(coord, geom, item) { var self = this; var options = self.options; var point = item.point; if (point && point.x && point.y) { // hotfix: make sure there is no null value var x = Util.isArray(point.x) ? point.x[point.x.length - 1] : point.x; var y = Util.isArray(point.y) ? point.y[point.y.length - 1] : point.y; point = coord.applyMatrix(x, y, 1); item.x = point[0]; item.y = point[1]; item.showMarker = true; // bugfix // 由于tooltip是DOM而不是Canvas,设置渐变色时,marker无法正常显示 // 如果,设置的颜色是渐变色并且设置了tooltip使用html方式渲染,则取渐变色的起始颜色作为marker的颜色,暂时解决这个问题 if (item.color.substring(0, 2) === 'l(' && (!options.hasOwnProperty('useHtml') || options.useHtml)) { item.color = item.color.split(' ')[1].substring(2); } var itemMarker = self._getItemMarker(geom, item); item.marker = itemMarker; if (Util.indexOf(TYPE_SHOW_MARKERS, geom.get('type')) !== -1) { return item; } } return null; }; _proto.lockTooltip = function lockTooltip() { this.locked = true; }; _proto.unlockTooltip = function unlockTooltip() { this.locked = false; }; _proto.showTooltip = function showTooltip(point, views, target) { var _this = this; var self = this; if (Util.isEmpty(views) || !point) { return; } if (!this.tooltip) { this.renderTooltip(); // 如果一开始 tooltip 关闭,用户重新调用的时候需要先生成 tooltip } var options = self.options; var markersItems = []; var items = []; Util.each(views, function (view) { if (!view.get('tooltipEnable')) { // 如果不显示tooltip,则跳过 return true; } var geoms = view.get('geoms'); var coord = view.get('coord'); Util.each(geoms, function (geom) { var type = geom.get('type'); if (geom.get('visible') && geom.get('tooltipCfg') !== false) { var dataArray = geom.get('dataArray'); if (geom.isShareTooltip() || options.shared === false && Util.inArray(['area', 'line', 'path', 'polygon'], type)) { // 打补丁解决 bug: https://github.com/antvis/g2/issues/1248 // 当 interval 对应的 color 和 x 字段相同的时候,并且包含 dodge,items 取值逻辑不一样 // 这种情况下,每一个 x 字段分成一组 var xScale = geom.getXScale(); var colorAttr = geom.getAttr('color'); var colorField = colorAttr ? colorAttr.field : undefined; if (type === 'interval' && xScale.field === colorField && geom.hasAdjust('dodge')) { // 找不到不为空的 var points = Util.find(dataArray, function (obj) { return !!geom.findPoint(point, obj); }); // 转为 tooltip items Util.each(points, function (tmpPoint) { var subItems = geom.getTipItems(tmpPoint, options.title); Util.each(subItems, function (v) { var markerItem = self._formatMarkerOfItem(coord, geom, v); if (markerItem) { markersItems.push(markerItem); } }); items = items.concat(subItems); }); } else { Util.each(dataArray, function (obj) { var tmpPoint = geom.findPoint(point, obj); if (tmpPoint) { var subItems = geom.getTipItems(tmpPoint, options.title); Util.each(subItems, function (v) { var markerItem = self._formatMarkerOfItem(coord, geom, v); if (markerItem) { markersItems.push(markerItem); } }); items = items.concat(subItems); } }); } } else { var geomContainer = geom.get('shapeContainer'); var canvas = geomContainer.get('canvas'); var pixelRatio = canvas.get('pixelRatio'); var shape = geomContainer.getShape(point.x * pixelRatio, point.y * pixelRatio); if (shape && shape.get('visible') && shape.get('origin')) { items = geom.getTipItems(shape.get('origin'), options.title); } Util.each(items, function (v) { var markerItem = _this._formatMarkerOfItem(coord, geom, v); if (markerItem) { markersItems.push(markerItem); } }); } } }); Util.each(items, function (item) { var point = item.point; var x = Util.isArray(point.x) ? point.x[point.x.length - 1] : point.x; var y = Util.isArray(point.y) ? point.y[point.y.length - 1] : point.y; point = coord.applyMatrix(x, y, 1); item.x = point[0]; item.y = point[1]; }); }); if (items.length) { var first = items[0]; // bugfix: multiple tooltip items with different titles if (!items.every(function (item) { return item.title === first.title; })) { var nearestItem = first; var nearestDistance = Infinity; items.forEach(function (item) { var distance = Vector2.distance([point.x, point.y], [item.x, item.y]); if (distance < nearestDistance) { nearestDistance = distance; nearestItem = item; } }); items = items.filter(function (item) { return item.title === nearestItem.title; }); markersItems = markersItems.filter(function (item) { return item.title === nearestItem.title; }); } if (options.shared === false && items.length > 1) { var snapItem = items[0]; var min = Math.abs(point.y - snapItem.y); Util.each(items, function (aItem) { if (Math.abs(point.y - aItem.y) <= min) { snapItem = aItem; min = Math.abs(point.y - aItem.y); } }); if (snapItem && snapItem.x && snapItem.y) { markersItems = [snapItem]; } items = [snapItem]; } // 3.0 采用当前鼠标位置作为 tooltip 的参考点 // if (!Util.isEmpty(markersItems)) { // point = markersItems[0]; // } self._setTooltip(point, items, markersItems, target); } else { self.hideTooltip(); } }; _proto.clear = function clear() { var tooltip = this.tooltip; tooltip && tooltip.destroy(); this.tooltip = null; this.prePoint = null; this._offEvent(); }; _proto._getItemMarker = function _getItemMarker(geom, item) { var options = this.options; var markerOption = options.marker || this.viewTheme.tooltip.marker; if (Util.isFunction(markerOption)) { var shapeType = geom.get('shapeType') || 'point'; var shape = geom.getDefaultValue('shape') || 'circle'; var shapeObject = Shape.getShapeFactory(shapeType); var cfg = { color: item.color }; var marker = shapeObject.getMarkerCfg(shape, cfg); return markerOption(marker, item); } return _extends({ fill: item.color }, markerOption); }; return TooltipController; }(); module.exports = TooltipController; /***/ }), /* 412 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview The controller of chart's events * @author sima.zhang */ var Util = __webpack_require__(0); function isSameShape(shape1, shape2) { if (Util.isNil(shape1) || Util.isNil(shape2)) { return false; } var shape1Origin = shape1.get('origin'); var shape2Origin = shape2.get('origin'); // hotfix: if both shapes have no data,just compare shapes. if (Util.isNil(shape1Origin) && Util.isNil(shape2Origin)) { return Util.isEqual(shape1, shape2); } return Util.isEqual(shape1Origin, shape2Origin); } function registerData(eventObj) { if (eventObj.shape && eventObj.shape.get('origin')) { eventObj.data = eventObj.shape.get('origin'); } } var EventController = /*#__PURE__*/function () { function EventController(cfg) { this.view = null; this.canvas = null; Util.assign(this, cfg); this._init(); } var _proto = EventController.prototype; _proto._init = function _init() { this.pixelRatio = this.canvas.get('pixelRatio'); }; _proto._getShapeEventObj = function _getShapeEventObj(ev) { return { x: ev.x / this.pixelRatio, y: ev.y / this.pixelRatio, target: ev.target, // canvas 元素 toElement: ev.event.toElement || ev.event.relatedTarget }; }; _proto._getShape = function _getShape(x, y) { var view = this.view; var container = view.get('canvas'); return container.getShape(x, y); }; _proto._getPointInfo = function _getPointInfo(ev) { var view = this.view; var point = { x: ev.x / this.pixelRatio, y: ev.y / this.pixelRatio }; var views = view.getViewsByPoint(point); point.views = views; return point; }; _proto._getEventObj = function _getEventObj(ev, point, views) { return { x: point.x, y: point.y, target: ev.target, // canvas 元素 toElement: ev.event.toElement || ev.event.relatedTarget, // 目标元素 views: views }; }; _proto.bindEvents = function bindEvents() { var canvas = this.canvas; canvas.on('mousedown', Util.wrapBehavior(this, 'onDown')); canvas.on('mousemove', Util.wrapBehavior(this, 'onMove')); canvas.on('mouseleave', Util.wrapBehavior(this, 'onOut')); canvas.on('mouseup', Util.wrapBehavior(this, 'onUp')); canvas.on('click', Util.wrapBehavior(this, 'onClick')); canvas.on('dblclick', Util.wrapBehavior(this, 'onClick')); canvas.on('touchstart', Util.wrapBehavior(this, 'onTouchstart')); canvas.on('touchmove', Util.wrapBehavior(this, 'onTouchmove')); canvas.on('touchend', Util.wrapBehavior(this, 'onTouchend')); }; _proto._triggerShapeEvent = function _triggerShapeEvent(shape, eventName, eventObj) { if (shape && shape.name && !shape.get('destroyed')) { var view = this.view; if (view.isShapeInView(shape)) { var name = shape.name + ':' + eventName; eventObj.view = view; eventObj.appendInfo = shape.get('appendInfo'); // appendInfo is defined by user view.emit(name, eventObj); var parent = view.get('parent'); if (parent) { // chart 上也需要抛出该事件,本期先不抛出 parent.emit(name, eventObj); } } } }; _proto.onDown = function onDown(ev) { var view = this.view; var eventObj = this._getShapeEventObj(ev); eventObj.shape = this.currentShape; registerData(eventObj); view.emit('mousedown', eventObj); this._triggerShapeEvent(this.currentShape, 'mousedown', eventObj); }; _proto.onMove = function onMove(ev) { var self = this; var view = self.view; var currentShape = self.currentShape; // 如果图形被销毁,则设置当前 shape 为空 if (currentShape && currentShape.get('destroyed')) { currentShape = null; self.currentShape = null; } var shape = self._getShape(ev.x, ev.y) || ev.currentTarget; var eventObj = self._getShapeEventObj(ev); eventObj.shape = shape; registerData(eventObj); view.emit('mousemove', eventObj); self._triggerShapeEvent(shape, 'mousemove', eventObj); if (currentShape && !isSameShape(currentShape, shape)) { var leaveObj = self._getShapeEventObj(ev); leaveObj.shape = currentShape; leaveObj.toShape = shape; registerData(leaveObj); self._triggerShapeEvent(currentShape, 'mouseleave', leaveObj); } if (shape && !isSameShape(currentShape, shape)) { var enterObj = self._getShapeEventObj(ev); enterObj.shape = shape; enterObj.fromShape = currentShape; registerData(enterObj); self._triggerShapeEvent(shape, 'mouseenter', enterObj); } self.currentShape = shape; var point = self._getPointInfo(ev); var preViews = self.curViews || []; if (preViews.length === 0 && point.views.length) { view.emit('plotenter', self._getEventObj(ev, point, point.views)); } // point.views 是指当前 view 或者子 view,不会取跟当前 view 同一层级的兄弟元素(view) if (preViews.length && point.views.length === 0) { view.emit('plotleave', self._getEventObj(ev, point, preViews)); } if (point.views.length) { eventObj = self._getEventObj(ev, point, point.views); eventObj.shape = shape; registerData(eventObj); view.emit('plotmove', eventObj); } self.curViews = point.views; }; _proto.onOut = function onOut(ev) { var self = this; var view = self.view; var point = self._getPointInfo(ev); var preViews = self.curViews || []; var evtObj = self._getEventObj(ev, point, preViews); // 只有没有padding 时,当前依然在 view 的 plotRange 情况下才会出现这个情况,保证 plotleave 触发 if (self.curViews && self.curViews.length !== 0 && (!evtObj.toElement || evtObj.toElement.tagName !== 'CANVAS')) { view.emit('plotleave', evtObj); self.curViews = []; // 清空 } }; _proto.onUp = function onUp(ev) { var view = this.view; var eventObj = this._getShapeEventObj(ev); eventObj.shape = this.currentShape; view.emit('mouseup', eventObj); this._triggerShapeEvent(this.currentShape, 'mouseup', eventObj); }; _proto.onClick = function onClick(ev) { var self = this; var view = self.view; var shape = self._getShape(ev.x, ev.y) || ev.currentTarget; var shapeEventObj = self._getShapeEventObj(ev); shapeEventObj.shape = shape; registerData(shapeEventObj); view.emit('click', shapeEventObj); self._triggerShapeEvent(shape, ev.type, shapeEventObj); self.currentShape = shape; var point = self._getPointInfo(ev); var views = point.views; if (!Util.isEmpty(views)) { var eventObj = self._getEventObj(ev, point, views); if (self.currentShape) { var _shape = self.currentShape; eventObj.shape = _shape; registerData(eventObj); // eventObj.data = shape.get('origin'); } if (ev.type === 'dblclick') { view.emit('plotdblclick', eventObj); view.emit('dblclick', shapeEventObj); } else { view.emit('plotclick', eventObj); } } }; _proto.onTouchstart = function onTouchstart(ev) { var view = this.view; var shape = this._getShape(ev.x, ev.y) || ev.currentTarget; var eventObj = this._getShapeEventObj(ev); eventObj.shape = shape; registerData(eventObj); view.emit('touchstart', eventObj); this._triggerShapeEvent(shape, 'touchstart', eventObj); this.currentShape = shape; }; _proto.onTouchmove = function onTouchmove(ev) { var view = this.view; var shape = this._getShape(ev.x, ev.y) || ev.currentTarget; var eventObj = this._getShapeEventObj(ev); eventObj.shape = shape; registerData(eventObj); view.emit('touchmove', eventObj); this._triggerShapeEvent(shape, 'touchmove', eventObj); this.currentShape = shape; }; _proto.onTouchend = function onTouchend(ev) { var view = this.view; var eventObj = this._getShapeEventObj(ev); eventObj.shape = this.currentShape; registerData(eventObj); view.emit('touchend', eventObj); this._triggerShapeEvent(this.currentShape, 'touchend', eventObj); }; _proto.clearEvents = function clearEvents() { var canvas = this.canvas; canvas.off('mousemove', Util.getWrapBehavior(this, 'onMove')); canvas.off('mouseleave', Util.getWrapBehavior(this, 'onOut')); canvas.off('mousedown', Util.getWrapBehavior(this, 'onDown')); canvas.off('mouseup', Util.getWrapBehavior(this, 'onUp')); canvas.off('click', Util.getWrapBehavior(this, 'onClick')); canvas.off('dblclick', Util.getWrapBehavior(this, 'onClick')); canvas.off('touchstart', Util.getWrapBehavior(this, 'onTouchstart')); canvas.off('touchmove', Util.getWrapBehavior(this, 'onTouchmove')); canvas.off('touchend', Util.getWrapBehavior(this, 'onTouchend')); }; return EventController; }(); module.exports = EventController; /***/ }), /* 413 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview The entry of chart's animation * @author sima.zhang */ var Util = __webpack_require__(0); var Animate = __webpack_require__(142); var MatrixUtil = Util.MatrixUtil; var mat3 = MatrixUtil.mat3; // 获取图组内所有的shapes function getShapes(container, viewId) { var shapes = []; if (container.get('animate') === false) { return []; } var children = container.get('children'); Util.each(children, function (child) { if (child.isGroup) { shapes = shapes.concat(getShapes(child, viewId)); } else if (child.isShape && child._id) { var id = child._id; id = id.split('-')[0]; if (id === viewId) { shapes.push(child); } } }); return shapes; } function cache(shapes) { var rst = {}; Util.each(shapes, function (shape) { if (!shape._id || shape.isClip) return; var id = shape._id; rst[id] = { _id: id, type: shape.get('type'), attrs: Util.cloneDeep(shape.attr()), // 原始属性 name: shape.name, index: shape.get('index'), animateCfg: shape.get('animateCfg'), coord: shape.get('coord') }; }); return rst; } function getAnimate(geomType, coord, animationType, animationName) { var result; if (animationName) { result = Animate.Action[animationType][animationName]; } else { result = Animate.getAnimation(geomType, coord, animationType); } return result; } function getAnimateCfg(geomType, animationType, animateCfg) { var defaultCfg = Animate.getAnimateCfg(geomType, animationType); if (animateCfg && animateCfg[animationType]) { return Util.deepMix({}, defaultCfg, animateCfg[animationType]); } return defaultCfg; } function addAnimate(cache, shapes, canvas, isUpdate) { var animate; var animateCfg; var canvasDrawn = false; if (isUpdate) { // Step: leave -> update -> enter var updateShapes = []; // 存储的是 shapes var newShapes = []; // 存储的是 shapes Util.each(shapes, function (shape) { var result = cache[shape._id]; if (!result) { newShapes.push(shape); } else { shape.setSilent('cacheShape', result); updateShapes.push(shape); delete cache[shape._id]; } }); Util.each(cache, function (deletedShape) { var name = deletedShape.name, coord = deletedShape.coord, _id = deletedShape._id, attrs = deletedShape.attrs, index = deletedShape.index, type = deletedShape.type; animateCfg = getAnimateCfg(name, 'leave', deletedShape.animateCfg); animate = getAnimate(name, coord, 'leave', animateCfg.animation); if (Util.isFunction(animate)) { var tempShape = canvas.addShape(type, { attrs: attrs, index: index }); tempShape._id = _id; tempShape.name = name; if (coord && name !== 'label') { var tempShapeMatrix = tempShape.getMatrix(); var finalMatrix = mat3.multiply([], tempShapeMatrix, coord.matrix); tempShape.setMatrix(finalMatrix); } canvasDrawn = true; animate(tempShape, animateCfg, coord); } }); Util.each(updateShapes, function (updateShape) { var name = updateShape.name; var coord = updateShape.get('coord'); var cacheAttrs = updateShape.get('cacheShape').attrs; // 判断如果属性相同的话就不进行变换 if (!Util.isEqual(cacheAttrs, updateShape.attr())) { animateCfg = getAnimateCfg(name, 'update', updateShape.get('animateCfg')); animate = getAnimate(name, coord, 'update', animateCfg.animation); if (Util.isFunction(animate)) { animate(updateShape, animateCfg, coord); } else { var endState = Util.cloneDeep(updateShape.attr()); updateShape.attr(cacheAttrs); updateShape.animate(endState, animateCfg.duration, animateCfg.easing, function () { updateShape.setSilent('cacheShape', null); }); } canvasDrawn = true; } }); Util.each(newShapes, function (newShape) { var name = newShape.name; var coord = newShape.get('coord'); animateCfg = getAnimateCfg(name, 'enter', newShape.get('animateCfg')); animate = getAnimate(name, coord, 'enter', animateCfg.animation); if (Util.isFunction(animate)) { animate(newShape, animateCfg, coord); canvasDrawn = true; } }); } else { Util.each(shapes, function (shape) { var name = shape.name; var coord = shape.get('coord'); animateCfg = getAnimateCfg(name, 'appear', shape.get('animateCfg')); animate = getAnimate(name, coord, 'appear', animateCfg.animation); if (Util.isFunction(animate)) { animate(shape, animateCfg, coord); canvasDrawn = true; } }); } return canvasDrawn; } module.exports = { execAnimation: function execAnimation(view, isUpdate) { var viewContainer = view.get('middlePlot'); var axisContainer = view.get('backPlot'); var viewId = view.get('_id'); var canvas = view.get('canvas'); var caches = canvas.get(viewId + 'caches') || []; if (caches.length === 0) { isUpdate = false; } var shapes = getShapes(viewContainer, viewId); var axisShapes = getShapes(axisContainer, viewId); var cacheShapes = shapes.concat(axisShapes); canvas.setSilent(viewId + 'caches', cache(cacheShapes)); var drawn; if (isUpdate) { drawn = addAnimate(caches, cacheShapes, canvas, isUpdate); } else { drawn = addAnimate(caches, shapes, canvas, isUpdate); } if (!drawn) { canvas.draw(); } } }; /***/ }), /* 414 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview The class of canvas plot * @author sima.zhang */ var Util = __webpack_require__(0); var _require = __webpack_require__(18), Group = _require.Group; var AUTO_STR = 'auto'; var PlotBack = function PlotBack(cfg) { PlotBack.superclass.constructor.call(this, cfg); }; Util.extend(PlotBack, Group); Util.augment(PlotBack, { getDefaultCfg: function getDefaultCfg() { return { /** * 类型 * @type {String} */ type: 'plotBack', /** * 画布边距 * @type {Number | Array | Object | "auto"} */ padding: null, /** * 大背景 * @type {Object} */ background: null, /** * 绘图区域范围 * @type {Object} */ plotRange: null, /** * 绘图区域背景 * @type {Object} */ plotBackground: null }; }, _beforeRenderUI: function _beforeRenderUI() { this._calculateRange(); }, _renderUI: function _renderUI() { this._renderBackground(); this._renderPlotBackground(); }, _renderBackground: function _renderBackground() { var self = this; var background = self.get('background'); if (background) { var canvas = this.get('canvas'); var width = self.get('width') || canvas.get('width'); var height = self.get('height') || canvas.get('height'); var cfg = { x: 0, y: 0, width: width, height: height }; var rect = self.get('backgroundShape'); if (!rect) { rect = this.addShape('rect', { attrs: Util.mix(cfg, background) }); this.set('backgroundShape', rect); } else { rect.attr(cfg); } } else { return; } }, _renderPlotBackground: function _renderPlotBackground() { var self = this; var plotBackground = self.get('plotBackground'); if (plotBackground) { var plotRange = self.get('plotRange'); var width = plotRange.br.x - plotRange.bl.x; var height = plotRange.br.y - plotRange.tr.y; var tl = plotRange.tl; var cfg = { x: tl.x, y: tl.y, width: width, height: height }; var plotBackShape = self.get('plotBackShape'); if (!plotBackShape) { if (plotBackground.image) { cfg.img = plotBackground.image; plotBackShape = self.addShape('image', { attrs: cfg }); } else { // 矩形 Util.mix(cfg, plotBackground); plotBackShape = self.addShape('rect', { attrs: cfg }); } self.set('plotBackShape', plotBackShape); } else { plotBackShape.attr(cfg); } } else { return; } }, _convert: function _convert(val, isHorizontal) { if (Util.isString(val)) { if (val === AUTO_STR) { val = 0; } else if (val.includes('%')) { var canvas = this.get('canvas'); var width = this.get('width') || canvas.get('width'); var height = this.get('height') || canvas.get('height'); val = parseInt(val, 10) / 100; val = isHorizontal ? val * width : val * height; } } return val; }, _calculateRange: function _calculateRange() { var self = this; var plotRange = self.get('plotRange'); if (Util.isNil(plotRange)) { plotRange = {}; } var padding = self.get('padding'); var canvas = this.get('canvas'); var width = self.get('width') || canvas.get('width'); var height = self.get('height') || canvas.get('height'); var allPadding = Util.toAllPadding(padding); var top = self._convert(allPadding[0], false); var right = self._convert(allPadding[1], true); var bottom = self._convert(allPadding[2], false); var left = self._convert(allPadding[3], true); var minX = Math.min(left, width - right); var maxX = Math.max(left, width - right); var minY = Math.min(height - bottom, top); var maxY = Math.max(height - bottom, top); plotRange.tl = { x: minX, y: minY }; // top-left plotRange.tr = { x: maxX, y: minY }; // top-right plotRange.bl = { x: minX, y: maxY }; // bottom-left plotRange.br = { x: maxX, y: maxY }; // bottom-right plotRange.cc = { x: (maxX + minX) / 2, y: (maxY + minY) / 2 }; this.set('plotRange', plotRange); }, repaint: function repaint() { this._calculateRange(); this._renderBackground(); this._renderPlotBackground(); return this; } }); module.exports = PlotBack; /***/ }), /* 415 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview 需要计算所占x轴上的宽度的辅助类 * @author sima.zhang1990@gmail.com * @author dxq613@gmail.com */ var Global = __webpack_require__(8); var Util = __webpack_require__(0); // 已经排序后的数据查找距离最小的 function findMinDistance(arr, scale) { var count = arr.length; // 日期类型的 values 经常上文本类型,所以需要转换一下 if (Util.isString(arr[0])) { arr = arr.map(function (v) { return scale.translate(v); }); } var distance = arr[1] - arr[0]; for (var i = 2; i < count; i++) { var tmp = arr[i] - arr[i - 1]; if (distance > tmp) { distance = tmp; } } return distance; } var SizeMixin = { getDefaultSize: function getDefaultSize() { var defaultSize = this.get('defaultSize'); var viewTheme = this.get('viewTheme') || Global; if (!defaultSize) { var coord = this.get('coord'); var xScale = this.getXScale(); var xValues = xScale.values; var dataArray = this.get('dataArray'); var count; if (xScale.isLinear && xValues.length > 1) { xValues.sort(); var interval = findMinDistance(xValues, xScale); count = (xScale.max - xScale.min) / interval; if (xValues.length > count) { count = xValues.length; } } else { count = xValues.length; } var range = xScale.range; var normalizeSize = 1 / count; var widthRatio = 1; if (this.isInCircle()) { if (coord.isTransposed && count > 1) { // 极坐标下多层环图 widthRatio = viewTheme.widthRatio.multiplePie; } else { widthRatio = viewTheme.widthRatio.rose; } /* if (dataArray.length > 1) { normalizeSize *= (range[1] - range[0]); } */ } else { if (xScale.isLinear) { normalizeSize *= range[1] - range[0]; } widthRatio = viewTheme.widthRatio.column; // 柱状图要除以2 } normalizeSize *= widthRatio; if (this.hasAdjust('dodge')) { var _this$_getDodgeCfg = this._getDodgeCfg(dataArray), dodgeCount = _this$_getDodgeCfg.dodgeCount, dodgeRatio = _this$_getDodgeCfg.dodgeRatio; normalizeSize = normalizeSize / dodgeCount; if (dodgeRatio > 0) { normalizeSize = dodgeRatio * normalizeSize / widthRatio; } } defaultSize = normalizeSize; this.set('defaultSize', defaultSize); } return defaultSize; }, _getDodgeCfg: function _getDodgeCfg(dataArray) { var adjusts = this.get('adjusts'); var dodgeBy; var dodgeRatio; var count = dataArray.length; Util.each(adjusts, function (adjust) { if (adjust.type === 'dodge') { dodgeBy = adjust.dodgeBy; dodgeRatio = adjust.dodgeRatio; } }); if (dodgeBy) { var mergeData = Util.Array.merge(dataArray); var values = Util.Array.values(mergeData, dodgeBy); count = values.length; } return { dodgeCount: count, dodgeRatio: dodgeRatio }; }, getDimWidth: function getDimWidth(dimName) { var coord = this.get('coord'); var start = coord.convertPoint({ x: 0, y: 0 }); var end = coord.convertPoint({ x: dimName === 'x' ? 1 : 0, y: dimName === 'x' ? 0 : 1 }); var width = 0; if (start && end) { width = Math.sqrt(Math.pow(end.x - start.x, 2) + Math.pow(end.y - start.y, 2)); } return width; }, _getWidth: function _getWidth() { var coord = this.get('coord'); var width; // x轴的长度 if (this.isInCircle() && !coord.isTransposed) { // 极坐标下 width 为弧长 width = (coord.endAngle - coord.startAngle) * coord.radius; } else { width = this.getDimWidth('x'); // 不需要判断transpose } return width; }, _toNormalizedSize: function _toNormalizedSize(size) { var width = this._getWidth(); return size / width; }, _toCoordSize: function _toCoordSize(normalizeSize) { var width = this._getWidth(); return width * normalizeSize; }, getNormalizedSize: function getNormalizedSize(obj) { var size = this.getAttrValue('size', obj); if (Util.isNil(size)) { size = this.getDefaultSize(); } else { size = this._toNormalizedSize(size); } return size; }, getSize: function getSize(obj) { var size = this.getAttrValue('size', obj); if (Util.isNil(size)) { var normalizeSize = this.getDefaultSize(); size = this._toCoordSize(normalizeSize); } return size; } }; module.exports = SizeMixin; /***/ }), /* 416 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview 分割数据用于处理存在 null 值的折线图、区域图 * @author dxq613@gmail.com */ var Util = __webpack_require__(0); var Global = __webpack_require__(8); module.exports = { splitData: function splitData(data) { var viewTheme = this.get('viewTheme') || Global; if (!data.length) return []; var arr = []; var tmp = []; var yScale = this.getYScale(); var yDim = yScale.field; var yValue; Util.each(data, function (obj) { yValue = obj._origin ? obj._origin[yDim] : obj[yDim]; if (viewTheme.connectNulls) { // 如果忽视 Null 直接连接节点,则将 value = null 的数据过滤掉 if (!Util.isNil(yValue)) { tmp.push(obj); } } else { if (Util.isArray(yValue) && Util.isNil(yValue[0]) || Util.isNil(yValue)) { if (tmp.length) { arr.push(tmp); tmp = []; } } else { tmp.push(obj); } } }); if (tmp.length) { arr.push(tmp); } return arr; } }; /***/ }), /* 417 */ /***/ (function(module, exports, __webpack_require__) { function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @fileOverview 路径图,无序的线图 * @author dxq613@gmail.com */ var GeomBase = __webpack_require__(23); var SplitMixin = __webpack_require__(416); var Util = __webpack_require__(0); var Path = /*#__PURE__*/function (_GeomBase) { _inheritsLoose(Path, _GeomBase); var _proto = Path.prototype; /** * 获取默认的配置属性 * @protected * @return {Object} 默认属性 */ _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _GeomBase.prototype.getDefaultCfg.call(this); cfg.type = 'path'; cfg.shapeType = 'line'; return cfg; }; function Path(cfg) { var _this; _this = _GeomBase.call(this, cfg) || this; Util.assign(_assertThisInitialized(_this), SplitMixin); return _this; } _proto.getDrawCfg = function getDrawCfg(obj) { var cfg = _GeomBase.prototype.getDrawCfg.call(this, obj); cfg.isStack = this.hasStack(); return cfg; }; _proto.draw = function draw(data, container, shapeFactory, index) { var self = this; var splitArray = this.splitData(data); var cfg = this.getDrawCfg(data[0]); self._applyViewThemeShapeStyle(cfg, cfg.shape, shapeFactory); cfg.origin = data; // path,line 等图的origin 是整个序列 Util.each(splitArray, function (subData, splitedIndex) { if (!Util.isEmpty(subData)) { cfg.splitedIndex = splitedIndex; // 传入分割片段索引 用于生成id cfg.points = subData; var geomShape = shapeFactory.drawShape(cfg.shape, cfg, container); self.appendShapeInfo(geomShape, index + splitedIndex); } }); }; return Path; }(GeomBase); GeomBase.Path = Path; module.exports = Path; /***/ }), /* 418 */, /* 419 */, /* 420 */, /* 421 */, /* 422 */, /* 423 */ /***/ (function(module, exports, __webpack_require__) { function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; } function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @fileOverview interval geometry * @author dxq613@gmail.com */ var GeomBase = __webpack_require__(23); var Util = __webpack_require__(0); var SizeMixin = __webpack_require__(415); __webpack_require__(424); var Interval = /*#__PURE__*/function (_GeomBase) { _inheritsLoose(Interval, _GeomBase); var _proto = Interval.prototype; /** * 获取默认的配置属性 * @protected * @return {Object} 默认属性 */ _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _GeomBase.prototype.getDefaultCfg.call(this); cfg.type = 'interval'; cfg.shapeType = 'interval'; cfg.generatePoints = true; return cfg; }; function Interval(cfg) { var _this; _this = _GeomBase.call(this, cfg) || this; Util.assign(_assertThisInitialized(_this), SizeMixin); return _this; } _proto.createShapePointsCfg = function createShapePointsCfg(obj) { var cfg = _GeomBase.prototype.createShapePointsCfg.call(this, obj); cfg.size = this.getNormalizedSize(obj); return cfg; }; _proto.clearInner = function clearInner() { _GeomBase.prototype.clearInner.call(this); this.set('defaultSize', null); }; return Interval; }(GeomBase); var IntervalStack = /*#__PURE__*/function (_Interval) { _inheritsLoose(IntervalStack, _Interval); function IntervalStack() { return _Interval.apply(this, arguments) || this; } var _proto2 = IntervalStack.prototype; _proto2.getDefaultCfg = function getDefaultCfg() { var cfg = _Interval.prototype.getDefaultCfg.call(this); cfg.hasDefaultAdjust = true; cfg.adjusts = [{ type: 'stack' }]; return cfg; }; return IntervalStack; }(Interval); var IntervalDodge = /*#__PURE__*/function (_Interval2) { _inheritsLoose(IntervalDodge, _Interval2); function IntervalDodge() { return _Interval2.apply(this, arguments) || this; } var _proto3 = IntervalDodge.prototype; _proto3.getDefaultCfg = function getDefaultCfg() { var cfg = _Interval2.prototype.getDefaultCfg.call(this); cfg.hasDefaultAdjust = true; cfg.adjusts = [{ type: 'dodge' }]; return cfg; }; return IntervalDodge; }(Interval); var IntervalSymmetric = /*#__PURE__*/function (_Interval3) { _inheritsLoose(IntervalSymmetric, _Interval3); function IntervalSymmetric() { return _Interval3.apply(this, arguments) || this; } var _proto4 = IntervalSymmetric.prototype; _proto4.getDefaultCfg = function getDefaultCfg() { var cfg = _Interval3.prototype.getDefaultCfg.call(this); cfg.hasDefaultAdjust = true; cfg.adjusts = [{ type: 'symmetric' }]; return cfg; }; return IntervalSymmetric; }(Interval); Interval.Stack = IntervalStack; Interval.Dodge = IntervalDodge; Interval.Symmetric = IntervalSymmetric; GeomBase.Interval = Interval; GeomBase.IntervalStack = IntervalStack; GeomBase.IntervalDodge = IntervalDodge; GeomBase.IntervalSymmetric = IntervalSymmetric; module.exports = Interval; /***/ }), /* 424 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview interval shapes * @author dxq613@gmail.com * @author sima.zhang1990@gmail.com * @author huangtonger@aliyun.com */ var Util = __webpack_require__(0); var Shape = __webpack_require__(21); var PathUtil = __webpack_require__(25); var ShapeUtil = __webpack_require__(57); var Global = __webpack_require__(8); var G = __webpack_require__(18); var GPathUtil = Util.PathUtil; // 获取柱状图的几个点 function getRectPoints(cfg, isPyramid) { var x = cfg.x; var y = cfg.y; var y0 = cfg.y0; // 0 点的位置 var width = cfg.size; // 有3种情况, // 1. y,x都不是数组 // 2. y是数组,x不是 // 3. x是数组,y不是 var ymin = y0; var ymax = y; if (Util.isArray(y)) { ymax = y[1]; ymin = y[0]; } var xmin; var xmax; if (Util.isArray(x)) { xmin = x[0]; xmax = x[1]; } else { xmin = x - width / 2; xmax = x + width / 2; } var points = []; points.push({ x: xmin, y: ymin }, { x: xmin, y: ymax }); if (isPyramid) { points.push({ x: xmax, y: (ymax + ymin) / 2 }); } else { points.push({ x: xmax, y: ymax }, { x: xmax, y: ymin }); } return points; } function getRectPath(points) { var path = []; for (var i = 0; i < points.length; i++) { var point = points[i]; if (point) { var action = i === 0 ? 'M' : 'L'; path.push([action, point.x, point.y]); } } var first = points[0]; path.push(['L', first.x, first.y]); path.push(['z']); return path; } function getLinePoints(cfg) { var x = cfg.x; var y = cfg.y; var y0 = cfg.y0; // 0 点的位置 var points = []; if (Util.isArray(y)) { Util.each(y, function (yItem, idx) { points.push({ x: Util.isArray(x) ? x[idx] : x, y: yItem }); }); } else { points.push({ x: x, y: y }, { x: x, y: y0 }); } return points; } function getTickPoints(cfg) { var x = cfg.x; var y = Util.isArray(cfg.y) ? cfg.y[1] : cfg.y; var y0 = Util.isArray(cfg.y) ? cfg.y[0] : cfg.y0; var barWidth = cfg.size; var points = []; points.push({ x: x - barWidth / 2, y: y }, { x: x + barWidth / 2, y: y }, { x: x, y: y }, { x: x, y: y0 }, { x: x - barWidth / 2, y: y0 }, { x: x + barWidth / 2, y: y0 }); return points; } function getTickPath(points) { var path = []; path.push(['M', points[0].x, points[0].y], ['L', points[1].x, points[1].y], ['M', points[2].x, points[2].y], ['L', points[3].x, points[3].y], ['M', points[4].x, points[4].y], ['L', points[5].x, points[5].y]); return path; } function getFillAttrs(cfg) { var defaultAttrs = Global.shape.interval; var attrs = Util.mix({}, defaultAttrs, cfg.style); ShapeUtil.addFillAttrs(attrs, cfg); if (cfg.color) { attrs.stroke = attrs.stroke || cfg.color; } return attrs; } function getLineAttrs(cfg) { var defaultAttrs = Global.shape.hollowInterval; var attrs = Util.mix({}, defaultAttrs, cfg.style); ShapeUtil.addStrokeAttrs(attrs, cfg); return attrs; } function getFunnelPath(cfg, isFunnel) { var path = []; var points = cfg.points; var nextPoints = cfg.nextPoints; if (!Util.isNil(nextPoints)) { path.push(['M', points[0].x, points[0].y], ['L', points[1].x, points[1].y], ['L', nextPoints[1].x, nextPoints[1].y], ['L', nextPoints[0].x, nextPoints[0].y], ['Z']); } else if (isFunnel) { path.push(['M', points[0].x, points[0].y], ['L', points[1].x, points[1].y], ['L', points[2].x, points[2].y], ['L', points[3].x, points[3].y], ['Z']); } else { path.push(['M', points[0].x, points[0].y], ['L', points[1].x, points[1].y], ['L', points[2].x, points[2].y], ['L', points[2].x, points[2].y], ['Z']); } return path; } function getThetaCfg(point, coord) { var r = coord.getRadius(); var inner = coord.innerRadius; var startAngle; var endAngle; var ir = r * inner; var startPoint; var endPoint; if (!Util.isArray(point.x) && Util.isArray(point.y)) { point.x = [point.x, point.x]; // 如果x是一个值,y是数组,将x转成数组 } if (Util.isArray(point.x)) { startPoint = { x: point.x[0], y: point.y[0] }; endPoint = { x: point.x[1], y: point.y[1] }; startAngle = PathUtil.getPointAngle(coord, startPoint); endAngle = PathUtil.getPointAngle(coord, endPoint); if (endAngle <= startAngle) { // 考虑占比百分百的情形 endAngle = endAngle + Math.PI * 2; } } else { endPoint = point; startAngle = coord.startAngle; endAngle = PathUtil.getPointAngle(coord, endPoint); } return { r: r, ir: ir, startAngle: startAngle, endAngle: endAngle }; } // 获取选中时的样式,当前仅支持饼图 function _getSelectedCfg(type, cfg) { var geom = cfg.geom; var coord = geom.get('coord'); var point = cfg.point; var r = 7.5; var selectedCfg; if (coord && coord.type === 'theta') { var thetaCfg = getThetaCfg(point, coord); var middleAngle = (thetaCfg.endAngle - thetaCfg.startAngle) / 2 + thetaCfg.startAngle; var x = r * Math.cos(middleAngle); var y = r * Math.sin(middleAngle); selectedCfg = { transform: [['t', x, y]] }; } return Util.mix({}, selectedCfg); } var Interval = Shape.registerFactory('interval', { defaultShapeType: 'rect', getActiveCfg: function getActiveCfg(type, cfg) { if (!type || Util.inArray(['rect', 'funnel', 'pyramid'], type)) { // 透明度降低 0.15 var fillOpacity = cfg.fillOpacity || cfg.opacity || 1; return { fillOpacity: fillOpacity - 0.15 }; } var lineWidth = cfg.lineWidth || 0; return { lineWidth: lineWidth + 1 }; }, getDefaultPoints: function getDefaultPoints(pointInfo) { return getRectPoints(pointInfo); }, getSelectedCfg: function getSelectedCfg(type, cfg) { return _getSelectedCfg(type, cfg); } }); // 默认柱状图 Shape.registerShape('interval', 'rect', { draw: function draw(cfg, container) { var attrs = getFillAttrs(cfg); var path = getRectPath(cfg.points); path = this.parsePath(path); return container.addShape('path', { attrs: Util.mix(attrs, { path: path }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { var rectCfg = getFillAttrs(cfg); var isInCircle = cfg.isInCircle; return Util.mix({ symbol: isInCircle ? 'circle' : 'square', radius: isInCircle ? 4.5 : 4 }, rectCfg); } }); // 空心柱状图 Shape.registerShape('interval', 'hollowRect', { draw: function draw(cfg, container) { var attrs = getLineAttrs(cfg); var path = getRectPath(cfg.points); path = this.parsePath(path); return container.addShape('path', { attrs: Util.mix(attrs, { path: path }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { var rectCfg = getLineAttrs(cfg); var isInCircle = cfg.isInCircle; return Util.mix({ symbol: isInCircle ? 'circle' : 'square', radius: isInCircle ? 4.5 : 4 }, rectCfg); } }); // 线形柱状图 Shape.registerShape('interval', 'line', { getPoints: function getPoints(pointInfo) { return getLinePoints(pointInfo); }, draw: function draw(cfg, container) { var attrs = getLineAttrs(cfg); attrs.lineWidth = cfg.size || 1; // size 就是线的宽度 var path = getRectPath(cfg.points); path = this.parsePath(path); return container.addShape('path', { attrs: Util.mix(attrs, { path: path }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { var lineCfg = getLineAttrs(cfg); return Util.mix({ symbol: 'line', radius: 5 }, lineCfg); } }); // 钉子形的柱状图 Shape.registerShape('interval', 'tick', { getPoints: function getPoints(pointInfo) { return getTickPoints(pointInfo); }, draw: function draw(cfg, container) { var attrs = getLineAttrs(cfg); // @2018-12-25 by blue.lb 经过测试发现size代表的是宽度,而style中的lineWidth才是设置线宽,放在interval暂时先特殊处理 if (!attrs.lineWidth) { attrs.lineWidth = 2; } var path = getTickPath(cfg.points); path = this.parsePath(path); return container.addShape('path', { attrs: Util.mix(attrs, { path: path }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { var lineCfg = getLineAttrs(cfg); return Util.mix({ symbol: 'tick', radius: 5 }, lineCfg); } }); // 漏斗图 Shape.registerShape('interval', 'funnel', { getPoints: function getPoints(pointInfo) { pointInfo.size = pointInfo.size * 2; // 漏斗图的 size 是柱状图的两倍 return getRectPoints(pointInfo); }, draw: function draw(cfg, container) { var attrs = getFillAttrs(cfg); var path = getFunnelPath(cfg, true); path = this.parsePath(path); return container.addShape('path', { attrs: Util.mix(attrs, { path: path }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { var funnelCfg = getFillAttrs(cfg); return Util.mix({ symbol: 'square', radius: 4 }, funnelCfg); } }); // 金字塔图 Shape.registerShape('interval', 'pyramid', { getPoints: function getPoints(pointInfo) { pointInfo.size = pointInfo.size * 2; // 漏斗图的 size 是柱状图的两倍 return getRectPoints(pointInfo, true); }, draw: function draw(cfg, container) { var attrs = getFillAttrs(cfg); var path = getFunnelPath(cfg, false); path = this.parsePath(path); return container.addShape('path', { attrs: Util.mix(attrs, { path: path }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { var funnelCfg = getFillAttrs(cfg); return Util.mix({ symbol: 'square', radius: 4 }, funnelCfg); } }); // 水波图 /** * 用贝塞尔曲线模拟正弦波 * Using Bezier curves to fit sine wave. * There is 4 control points for each curve of wave, * which is at 1/4 wave length of the sine wave. * * The control points for a wave from (a) to (d) are a-b-c-d: * c *----* d * b * * | * ... a * .................. * * whose positions are a: (0, 0), b: (0.5, 0.5), c: (1, 1), d: (PI / 2, 1) * * @param {number} x x position of the left-most point (a) * @param {number} stage 0-3, stating which part of the wave it is * @param {number} waveLength wave length of the sine wave * @param {number} amplitude wave amplitude * @return {Array} 正弦片段曲线 */ function getWaterWavePositions(x, stage, waveLength, amplitude) { if (stage === 0) { return [[x + 1 / 2 * waveLength / Math.PI / 2, amplitude / 2], [x + 1 / 2 * waveLength / Math.PI, amplitude], [x + waveLength / 4, amplitude]]; } else if (stage === 1) { return [[x + 1 / 2 * waveLength / Math.PI / 2 * (Math.PI - 2), amplitude], [x + 1 / 2 * waveLength / Math.PI / 2 * (Math.PI - 1), amplitude / 2], [x + waveLength / 4, 0]]; } else if (stage === 2) { return [[x + 1 / 2 * waveLength / Math.PI / 2, -amplitude / 2], [x + 1 / 2 * waveLength / Math.PI, -amplitude], [x + waveLength / 4, -amplitude]]; } return [[x + 1 / 2 * waveLength / Math.PI / 2 * (Math.PI - 2), -amplitude], [x + 1 / 2 * waveLength / Math.PI / 2 * (Math.PI - 1), -amplitude / 2], [x + waveLength / 4, 0]]; } /** * 获取水波路径 * @param {number} radius 半径 * @param {number} waterLevel 水位 * @param {number} waveLength 波长 * @param {number} phase 相位 * @param {number} amplitude 震幅 * @param {number} cx 圆心x * @param {number} cy 圆心y * @return {Array} path 路径 * @reference http://gitlab.alipay-inc.com/datavis/g6/blob/1.2.0/src/graph/utils/path.js#L135 */ function getWaterWavePath(radius, waterLevel, waveLength, phase, amplitude, cx, cy) { var curves = Math.ceil(2 * radius / waveLength * 4) * 2; var path = []; // map phase to [-Math.PI * 2, 0] while (phase < -Math.PI * 2) { phase += Math.PI * 2; } while (phase > 0) { phase -= Math.PI * 2; } phase = phase / Math.PI / 2 * waveLength; var left = cx - radius + phase - radius * 2; /** * top-left corner as start point * * draws this point * | * \|/ * ~~~~~~~~ * | | * +------+ */ path.push(['M', left, waterLevel]); /** * top wave * * ~~~~~~~~ <- draws this sine wave * | | * +------+ */ var waveRight = 0; for (var c = 0; c < curves; ++c) { var stage = c % 4; var pos = getWaterWavePositions(c * waveLength / 4, stage, waveLength, amplitude); path.push(['C', pos[0][0] + left, -pos[0][1] + waterLevel, pos[1][0] + left, -pos[1][1] + waterLevel, pos[2][0] + left, -pos[2][1] + waterLevel]); if (c === curves - 1) { waveRight = pos[2][0]; } } /** * top-right corner * * ~~~~~~~~ * 3. draws this line -> | | <- 1. draws this line * +------+ * ^ * | * 2. draws this line */ path.push(['L', waveRight + left, cy + radius]); path.push(['L', left, cy + radius]); path.push(['L', left, waterLevel]); return path; } /** * 添加水波 * @param {number} x 中心x * @param {number} y 中心y * @param {number} level 水位等级 0~1 * @param {number} waveCount 水波数 * @param {number} colors 色值 * @param {number} group 图组 * @param {number} clip 用于剪切的图形 * @param {number} radius 绘制图形的高度 */ function addWaterWave(x, y, level, waveCount, colors, group, clip, radius) { var bbox = clip.getBBox(); var width = bbox.maxX - bbox.minX; var height = bbox.maxY - bbox.minY; var duration = 5000; var delayDiff = 300; for (var i = 0; i < waveCount; i++) { var wave = group.addShape('path', { attrs: { path: getWaterWavePath(radius, bbox.minY + height * level, width / 4, 0, width / 64, x, y), fill: colors[i], clip: clip } }); // FIXME wave animation error in svg if (Global.renderer === 'canvas') { wave.animate({ transform: [['t', width / 2, 0]], repeat: true }, duration - i * delayDiff); } } } Shape.registerShape('interval', 'liquid-fill-gauge', { draw: function draw(cfg, container) { var self = this; var cy = 0.5; var sumX = 0; var minX = Infinity; Util.each(cfg.points, function (p) { if (p.x < minX) { minX = p.x; } sumX += p.x; }); var cx = sumX / cfg.points.length; var cp = self.parsePoint({ x: cx, y: cy }); var minP = self.parsePoint({ x: minX, y: 0.5 }); var xWidth = cp.x - minP.x; var radius = Math.min(xWidth, minP.y); var attrs = getFillAttrs(cfg); var clipCircle = new G.Circle({ attrs: { x: cp.x, y: cp.y, r: radius } }); addWaterWave(cp.x, cp.y, cfg.y / (2 * cp.y), 1, [attrs.fill], container, clipCircle, radius * 4); return container.addShape('circle', { attrs: Util.mix(getLineAttrs(cfg), { x: cp.x, y: cp.y, r: radius + radius / 8 }) }); } }); var pathMetaCache = {}; Shape.registerShape('interval', 'liquid-fill-path', { draw: function draw(cfg, container) { var self = this; var attrs = Util.mix({}, getFillAttrs(cfg)); var path = cfg.shape[1]; var cy = 0.5; var sumX = 0; var minX = Infinity; Util.each(cfg.points, function (p) { if (p.x < minX) { minX = p.x; } sumX += p.x; }); var cx = sumX / cfg.points.length; var cp = self.parsePoint({ x: cx, y: cy }); var minP = self.parsePoint({ x: minX, y: 0.5 }); var xWidth = cp.x - minP.x; var radius = Math.min(xWidth, minP.y); var pathMeta; if (pathMetaCache[path]) { pathMeta = pathMetaCache[path]; } else { var segments = GPathUtil.parsePathString(path); pathMetaCache[path] = pathMeta = { segments: segments }; } var transform = []; if (attrs.rotate) { transform.push(['r', attrs.rotate / 180 * Math.PI]); delete attrs.rotate; } var shape = container.addShape('path', { attrs: Util.mix(attrs, { fillOpacity: 0, path: pathMeta.segments }) }); var bbox = Util.cloneDeep(shape.getBBox()); var rangeX = bbox.maxX - bbox.minX; var rangeY = bbox.maxY - bbox.minY; var range = Math.max(rangeX, rangeY); var scale = radius * 2 / range; shape.transform(transform.concat([['s', scale, scale]])); var dw = scale * rangeX / 2; // (bbox.maxX - bbox.minX) / 2; var dh = scale * rangeY / 2; // (bbox.maxY - bbox.minY) / 2; shape.transform([['t', cp.x - dw, cp.y - dh]]); addWaterWave(cp.x, cp.y, cfg.y / (2 * cp.y), 1, [attrs.fill], container, shape, minP.y * 4); var keyShape = container.addShape('path', { attrs: Util.mix(getLineAttrs(cfg), { path: pathMeta.segments }) }); keyShape.transform(transform.concat([['s', scale, scale], ['t', cp.x - dw, cp.y - dh]])); return keyShape; } }); Shape.registerShape('interval', 'top-line', { draw: function draw(cfg, container) { var attrs = getFillAttrs(cfg); var style = cfg.style || {}; var linePath = [['M', cfg.points[1].x, cfg.points[1].y], ['L', cfg.points[2].x, cfg.points[2].y]]; var lineAttrs = { stroke: style.stroke || 'white', lineWidth: style.lineWidth || 1, path: this.parsePath(linePath) }; var path = getRectPath(cfg.points); path = this.parsePath(path); delete attrs.stroke; // 不在柱子上绘制线 var rectShape = container.addShape('path', { attrs: Util.mix(attrs, { zIndex: 0, path: path }) }); container.addShape('path', { zIndex: 1, attrs: lineAttrs }); return rectShape; }, getMarkerCfg: function getMarkerCfg(cfg) { var rectCfg = getFillAttrs(cfg); var isInCircle = cfg.isInCircle; return Util.mix({ symbol: isInCircle ? 'circle' : 'square', radius: isInCircle ? 4.5 : 4 }, rectCfg); } }); module.exports = Interval; /***/ }), /* 425 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @fileOverview 线图 * @author dxq613@gmail.com */ var GeomBase = __webpack_require__(23); var Path = __webpack_require__(417); __webpack_require__(426); var Line = /*#__PURE__*/function (_Path) { _inheritsLoose(Line, _Path); function Line() { return _Path.apply(this, arguments) || this; } var _proto = Line.prototype; /** * 获取默认的配置属性 * @protected * @return {Object} 默认属性 */ _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _Path.prototype.getDefaultCfg.call(this); cfg.type = 'line'; cfg.sortable = true; return cfg; }; return Line; }(Path); var LineStack = /*#__PURE__*/function (_Line) { _inheritsLoose(LineStack, _Line); function LineStack() { return _Line.apply(this, arguments) || this; } var _proto2 = LineStack.prototype; _proto2.getDefaultCfg = function getDefaultCfg() { var cfg = _Line.prototype.getDefaultCfg.call(this); cfg.hasDefaultAdjust = true; cfg.adjusts = [{ type: 'stack' }]; return cfg; }; return LineStack; }(Line); Line.Stack = LineStack; GeomBase.Line = Line; GeomBase.LineStack = LineStack; module.exports = Line; /***/ }), /* 426 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview line shapes * @author dxq613@gmail.com * @author sima.zhang1990@gmail.com * @author huangtonger@aliyun.com */ var Util = __webpack_require__(0); var PathUtil = __webpack_require__(25); var ShapeUtil = __webpack_require__(57); var Shape = __webpack_require__(21); var Global = __webpack_require__(8); var DOT_ARR = [1, 1]; var DASH_ARR = [5.5, 1]; function getAttrs(cfg) { var defaultCfg = Global.shape.line; var lineAttrs = Util.mix({}, defaultCfg, cfg.style); ShapeUtil.addStrokeAttrs(lineAttrs, cfg); if (cfg.size) { lineAttrs.lineWidth = cfg.size; } return lineAttrs; } function getMarkerAttrs(cfg) { var defaultCfg = Global.shape.line; var lineAttrs = Util.mix({ lineWidth: 2, radius: 6 }, defaultCfg, cfg.style); ShapeUtil.addStrokeAttrs(lineAttrs, cfg); return lineAttrs; } // 获取带有上下区间的 path function getRangePath(points, smooth, isInCircle, cfg) { var topPoints = []; var isStack = cfg.isStack; var bottomPoints = []; for (var i = 0; i < points.length; i++) { var point = points[i]; var tmp = ShapeUtil.splitPoints(point); bottomPoints.push(tmp[0]); topPoints.push(tmp[1]); } var topPath = getSinglePath(topPoints, smooth, isInCircle, cfg); var bottomPath = getSinglePath(bottomPoints, smooth, isInCircle, cfg); if (isStack) { return topPath; } return topPath.concat(bottomPath); } // 单条 path function getSinglePath(points, smooth, isInCircle, cfg) { var path; if (!smooth) { path = PathUtil.getLinePath(points, false); if (isInCircle) { path.push(['Z']); } } else { // 直角坐标系下绘制曲线时限制最大值、最小值 var constraint = cfg.constraint; if (isInCircle && points.length) { points.push({ x: points[0].x, y: points[0].y }); } path = PathUtil.getSplinePath(points, false, constraint); } return path; } // get line path function getPath(cfg, smooth) { var path; var points = cfg.points; var isInCircle = cfg.isInCircle; var first = points[0]; if (Util.isArray(first.y)) { path = getRangePath(points, smooth, isInCircle, cfg); } else { path = getSinglePath(points, smooth, isInCircle, cfg); } return path; } function _interpPoints(points, fn) { var tmpPoints = []; Util.each(points, function (point, index) { var nextPoint = points[index + 1]; tmpPoints.push(point); if (nextPoint) { tmpPoints = tmpPoints.concat(fn(point, nextPoint)); } }); return tmpPoints; } // 插值的图形path,不考虑null function _getInterPath(points) { var path = []; Util.each(points, function (point, index) { var subPath = index === 0 ? ['M', point.x, point.y] : ['L', point.x, point.y]; path.push(subPath); }); return path; } // 插值的图形 function _getInterPointShapeCfg(cfg, fn) { var points = _interpPoints(cfg.points, fn); return _getInterPath(points); } function _markerFn(x, y, r) { return [['M', x - r, y], ['L', x + r, y]]; } function _smoothMarkerFn(x, y, r) { return [['M', x - r, y], ['A', r / 2, r / 2, 0, 1, 1, x, y], ['A', r / 2, r / 2, 0, 1, 0, x + r, y]]; } // get marker cfg function _getMarkerCfg(cfg, smooth) { return Util.mix({ symbol: smooth ? _smoothMarkerFn : _markerFn }, getMarkerAttrs(cfg)); } function _getInterMarkerCfg(cfg, fn) { return Util.mix({ symbol: fn }, getMarkerAttrs(cfg)); } // 当只有一个数据时绘制点 function drawPointShape(shapeObj, cfg, container) { var point = cfg.points[0]; return container.addShape('circle', { attrs: Util.mix({ x: point.x, y: point.y, r: 2, fill: cfg.color }, cfg.style) }); } // regist line geom var Line = Shape.registerFactory('line', { // 默认的shape defaultShapeType: 'line', /* getMarkerCfg(type, cfg) { const lineObj = Line[type] || Line.line; return lineObj.getMarkerCfg(cfg); }, */ getActiveCfg: function getActiveCfg(type, cfg) { var lineWidth = cfg.lineWidth || 0; return { lineWidth: lineWidth + 1 }; }, // 计算点 如果存在多个点,分割成单个的点, 不考虑多个x对应一个y的情况 getDefaultPoints: function getDefaultPoints(pointInfo) { return ShapeUtil.splitPoints(pointInfo); }, drawShape: function drawShape(type, cfg, container) { var shape = this.getShape(type); var gShape; if (cfg.points.length === 1 && Global.showSinglePoint) { gShape = drawPointShape(this, cfg, container); } else { gShape = shape.draw(cfg, container); } if (gShape) { gShape.set('origin', cfg.origin); gShape._id = cfg.splitedIndex ? cfg._id + cfg.splitedIndex : cfg._id; gShape.name = this.name; } return gShape; } }); // draw line shape Shape.registerShape('line', 'line', { draw: function draw(cfg, container) { var attrs = getAttrs(cfg); var path = getPath(cfg, false); return container.addShape('path', { attrs: Util.mix(attrs, { path: path }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { return _getMarkerCfg(cfg); } }); // 点线 ··· Shape.registerShape('line', 'dot', { draw: function draw(cfg, container) { var attrs = getAttrs(cfg); var path = getPath(cfg, false); return container.addShape('path', { attrs: Util.mix(attrs, { path: path, lineDash: DOT_ARR }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { var tmp = _getMarkerCfg(cfg, false); tmp.lineDash = DOT_ARR; return tmp; } }); // 断线 - - - Shape.registerShape('line', 'dash', { draw: function draw(cfg, container) { var attrs = getAttrs(cfg); var path = getPath(cfg, false); return container.addShape('path', { attrs: Util.mix({ path: path, lineDash: DASH_ARR }, attrs) }); }, getMarkerCfg: function getMarkerCfg(cfg) { var tmp = _getMarkerCfg(cfg, false); tmp.lineDash = tmp.lineDash || DASH_ARR; return tmp; } }); // draw smooth line shape Shape.registerShape('line', 'smooth', { draw: function draw(cfg, container) { var attrs = getAttrs(cfg); var coord = this._coord; // 曲线的限制 cfg.constraint = [[coord.start.x, coord.end.y], [coord.end.x, coord.start.y]]; var path = getPath(cfg, true); return container.addShape('path', { attrs: Util.mix(attrs, { path: path }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { return _getMarkerCfg(cfg, true); } }); Shape.registerShape('line', 'hv', { draw: function draw(cfg, container) { var attrs = getAttrs(cfg); var path = _getInterPointShapeCfg(cfg, function (point, nextPoint) { var tmp = []; tmp.push({ x: nextPoint.x, y: point.y }); return tmp; }); return container.addShape('path', { attrs: Util.mix(attrs, { path: path }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { return _getInterMarkerCfg(cfg, function (x, y, r) { return [['M', x - r - 1, y - 2.5], ['L', x, y - 2.5], ['L', x, y + 2.5], ['L', x + r + 1, y + 2.5]]; }); } }); Shape.registerShape('line', 'vh', { draw: function draw(cfg, container) { var attrs = getAttrs(cfg); var path = _getInterPointShapeCfg(cfg, function (point, nextPoint) { var tmp = []; tmp.push({ x: point.x, y: nextPoint.y }); return tmp; }); return container.addShape('path', { attrs: Util.mix(attrs, { path: path }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { return _getInterMarkerCfg(cfg, function (x, y, r) { return [['M', x - r - 1, y + 2.5], ['L', x, y + 2.5], ['L', x, y - 2.5], ['L', x + r + 1, y - 2.5]]; }); } }); Shape.registerShape('line', 'hvh', { draw: function draw(cfg, container) { var attrs = getAttrs(cfg); var path = _getInterPointShapeCfg(cfg, function (point, nextPoint) { var tmp = []; var middlex = (nextPoint.x - point.x) / 2 + point.x; tmp.push({ x: middlex, y: point.y }); tmp.push({ x: middlex, y: nextPoint.y }); return tmp; }); return container.addShape('path', { attrs: Util.mix(attrs, { path: path }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { return _getInterMarkerCfg(cfg, function (x, y, r) { return [['M', x - (r + 1), y + 2.5], ['L', x - r / 2, y + 2.5], ['L', x - r / 2, y - 2.5], ['L', x + r / 2, y - 2.5], ['L', x + r / 2, y + 2.5], ['L', x + r + 1, y + 2.5]]; }); } }); Shape.registerShape('line', 'vhv', { draw: function draw(cfg, container) { var attrs = getAttrs(cfg); var path = _getInterPointShapeCfg(cfg, function (point, nextPoint) { var tmp = []; var middley = (nextPoint.y - point.y) / 2 + point.y; tmp.push({ x: point.x, y: middley }); tmp.push({ x: nextPoint.x, y: middley }); return tmp; }); return container.addShape('path', { attrs: Util.mix(attrs, { path: path }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { return _getInterMarkerCfg(cfg, function (x, y) { // 宽 13px,高 8px return [['M', x - 5, y + 2.5], ['L', x - 5, y], ['L', x, y], ['L', x, y - 3], ['L', x, y + 3], ['L', x + 6.5, y + 3]]; }); } }); Line.spline = Line.smooth; module.exports = Line; /***/ }), /* 427 */ /***/ (function(module, exports, __webpack_require__) { function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; _setPrototypeOf(subClass, superClass); } function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); } /** * @fileOverview 点图 * @author dxq613@gmail.com */ var GeomBase = __webpack_require__(23); var Util = __webpack_require__(0); __webpack_require__(428); var Point = /*#__PURE__*/function (_GeomBase) { _inheritsLoose(Point, _GeomBase); function Point() { return _GeomBase.apply(this, arguments) || this; } var _proto = Point.prototype; /** * 获取默认的配置属性 * @protected * @return {Object} 默认属性 */ _proto.getDefaultCfg = function getDefaultCfg() { var cfg = _GeomBase.prototype.getDefaultCfg.call(this); cfg.type = 'point'; cfg.shapeType = 'point'; cfg.generatePoints = true; return cfg; }; _proto.drawPoint = function drawPoint(obj, container, shapeFactory, index) { var self = this; var shape = obj.shape; var cfg = self.getDrawCfg(obj); self._applyViewThemeShapeStyle(cfg, shape, shapeFactory); var geomShape; if (Util.isArray(obj.y)) { var hasAdjust = self.hasStack(); Util.each(obj.y, function (y, idx) { cfg.y = y; cfg.yIndex = idx; if (!hasAdjust || idx !== 0) { geomShape = shapeFactory.drawShape(shape, cfg, container); self.appendShapeInfo(geomShape, index + idx); } }); } else if (!Util.isNil(obj.y)) { geomShape = shapeFactory.drawShape(shape, cfg, container); self.appendShapeInfo(geomShape, index); } }; return Point; }(GeomBase); var PointJitter = /*#__PURE__*/function (_Point) { _inheritsLoose(PointJitter, _Point); function PointJitter() { return _Point.apply(this, arguments) || this; } var _proto2 = PointJitter.prototype; _proto2.getDefaultCfg = function getDefaultCfg() { var cfg = _Point.prototype.getDefaultCfg.call(this); cfg.hasDefaultAdjust = true; cfg.adjusts = [{ type: 'jitter' }]; return cfg; }; return PointJitter; }(Point); var PointStack = /*#__PURE__*/function (_Point2) { _inheritsLoose(PointStack, _Point2); function PointStack() { return _Point2.apply(this, arguments) || this; } var _proto3 = PointStack.prototype; _proto3.getDefaultCfg = function getDefaultCfg() { var cfg = _Point2.prototype.getDefaultCfg.call(this); cfg.hasDefaultAdjust = true; cfg.adjusts = [{ type: 'stack' }]; return cfg; }; return PointStack; }(Point); Point.Jitter = PointJitter; Point.Stack = PointStack; GeomBase.Point = Point; GeomBase.PointJitter = PointJitter; GeomBase.PointStack = PointStack; module.exports = Point; /***/ }), /* 428 */ /***/ (function(module, exports, __webpack_require__) { /** * @fileOverview point shapes * @author dxq613@gmail.com * @author sima.zhang1990@gmail.com * @author huangtonger@aliyun.com */ var Util = __webpack_require__(0); var ShapeUtil = __webpack_require__(57); var Global = __webpack_require__(8); var Shape = __webpack_require__(21); // const svgpath = require('svgpath'); var _require = __webpack_require__(18), Marker = _require.Marker; var PathUtil = Util.PathUtil; var SHAPES = ['circle', 'square', 'bowtie', 'diamond', 'hexagon', 'triangle', 'triangle-down']; var HOLLOW_SHAPES = ['cross', 'tick', 'plus', 'hyphen', 'line', 'pointerLine', 'pointerArrow']; var SQRT_3 = Math.sqrt(3); // 增加marker Util.mix(Marker.Symbols, { hexagon: function hexagon(x, y, r) { var diffX = r / 2 * SQRT_3; return [['M', x, y - r], ['L', x + diffX, y - r / 2], ['L', x + diffX, y + r / 2], ['L', x, y + r], ['L', x - diffX, y + r / 2], ['L', x - diffX, y - r / 2], ['Z']]; }, bowtie: function bowtie(x, y, r) { var diffY = r - 1.5; return [['M', x - r, y - diffY], ['L', x + r, y + diffY], ['L', x + r, y - diffY], ['L', x - r, y + diffY], ['Z']]; }, cross: function cross(x, y, r) { return [['M', x - r, y - r], ['L', x + r, y + r], ['M', x + r, y - r], ['L', x - r, y + r]]; }, tick: function tick(x, y, r) { return [['M', x - r / 2, y - r], ['L', x + r / 2, y - r], ['M', x, y - r], ['L', x, y + r], ['M', x - r / 2, y + r], ['L', x + r / 2, y + r]]; }, plus: function plus(x, y, r) { return [['M', x - r, y], ['L', x + r, y], ['M', x, y - r], ['L', x, y + r]]; }, hyphen: function hyphen(x, y, r) { return [['M', x - r, y], ['L', x + r, y]]; }, line: function line(x, y, r) { return [['M', x, y - r], ['L', x, y + r]]; } }); function getFillAttrs(cfg) { var defaultAttrs = Global.shape.point; var pointAttrs = Util.mix({}, defaultAttrs, cfg.style); ShapeUtil.addFillAttrs(pointAttrs, cfg); if (Util.isNumber(cfg.size)) { pointAttrs.radius = cfg.size; } return pointAttrs; } function getLineAttrs(cfg) { var defaultAttrs = Global.shape.hollowPoint; var pointAttrs = Util.mix({}, defaultAttrs, cfg.style); ShapeUtil.addStrokeAttrs(pointAttrs, cfg); if (Util.isNumber(cfg.size)) { pointAttrs.radius = cfg.size; } return pointAttrs; } var Point = Shape.registerFactory('point', { defaultShapeType: 'hollowCircle', getActiveCfg: function getActiveCfg(type, cfg) { // 点放大 + 颜色加亮 var radius = cfg.radius; var color; if (type && (type.indexOf('hollow') === 0 || Util.indexOf(HOLLOW_SHAPES, type) !== -1) || !type) { color = cfg.stroke || cfg.strokeStyle; } else { color = cfg.fill || cfg.fillStyle; } return { radius: radius + 1, shadowBlur: radius, shadowColor: color, stroke: color, strokeOpacity: 1, lineWidth: 1 }; }, getDefaultPoints: function getDefaultPoints(pointInfo) { return ShapeUtil.splitPoints(pointInfo); } }); function getRectPath(cfg) { var x = cfg.points[0].x; var y = cfg.points[0].y; var w = cfg.size[0]; var h = cfg.size[1]; var path = [['M', x - 0.5 * w, y - 0.5 * h], ['L', x + 0.5 * w, y - 0.5 * h], ['L', x + 0.5 * w, y + 0.5 * h], ['L', x - 0.5 * w, y + 0.5 * h], ['z']]; return path; } // 用于桑基图的节点 Shape.registerShape('point', 'rect', { draw: function draw(cfg, container) { var rectAttrs = getFillAttrs(cfg); var path = getRectPath(cfg); path = this.parsePath(path); var gShape = container.addShape('path', { attrs: Util.mix(rectAttrs, { path: path }) }); return gShape; }, getMarkerCfg: function getMarkerCfg(cfg) { var attrs = getFillAttrs(cfg); attrs.symbol = 'rect'; attrs.radius = 4.5; return attrs; } }); // 添加shapes Util.each(SHAPES, function (shape) { Shape.registerShape('point', shape, { draw: function draw(cfg, container) { // cfg.points = this.parsePoints(cfg.points); var attrs = getFillAttrs(cfg); return container.addShape('Marker', { attrs: Util.mix(attrs, { symbol: shape, x: cfg.x, y: cfg.y }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { var attrs = getFillAttrs(cfg); attrs.symbol = shape; attrs.radius = 4.5; return attrs; } }); // 添加该 shape 对应的 hollowShape Shape.registerShape('point', 'hollow' + Util.upperFirst(shape), { draw: function draw(cfg, container) { // cfg.points = this.parsePoints(cfg.points); var attrs = getLineAttrs(cfg); return container.addShape('Marker', { attrs: Util.mix(attrs, { symbol: shape, x: cfg.x, y: cfg.y }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { var attrs = getLineAttrs(cfg); attrs.symbol = shape; attrs.radius = 4.5; return attrs; } }); }); // 添加 hollowShapes Util.each(HOLLOW_SHAPES, function (shape) { Shape.registerShape('point', shape, { draw: function draw(cfg, container) { var attrs = getLineAttrs(cfg); return container.addShape('Marker', { attrs: Util.mix(attrs, { symbol: shape, x: cfg.x, y: cfg.y }) }); }, getMarkerCfg: function getMarkerCfg(cfg) { var attrs = getLineAttrs(cfg); attrs.symbol = shape; attrs.radius = 4.5; return attrs; } }); }); // image Shape.registerShape('point', 'image', { draw: function draw(cfg, container) { cfg.points = this.parsePoints(cfg.points); return container.addShape('image', { attrs: { x: cfg.points[0].x - cfg.size / 2, y: cfg.points[0].y - cfg.size, width: cfg.size, height: cfg.size, img: cfg.shape[1] } }); } }); // path var pathMetaCache = {}; Shape.registerShape('point', 'path', { draw: function draw(cfg, container) { var attrs = Util.mix({}, getLineAttrs(cfg), getFillAttrs(cfg)); var path = cfg.shape[1]; var size = cfg.size || 10; var pathMeta; if (pathMetaCache[path]) { pathMeta = pathMetaCache[path]; } else { var segments = PathUtil.parsePathString(path); var nums = Util.flatten(segments).filter(function (num) { return Util.isNumber(num); }); pathMetaCache[path] = pathMeta = { range: Math.max.apply(null, nums) - Math.min.apply(null, nums), segments: segments }; } var scale = size / pathMeta.range; var transform = []; if (attrs.rotate) { transform.push(['r', attrs.rotate / 180 * Math.PI]); delete attrs.rotate; } var shape = container.addShape('path', { attrs: Util.mix(attrs, { path: pathMeta.segments }) }); transform.push(['s', scale, scale], ['t', cfg.x, cfg.y]); shape.transform(transform); return shape; } }); module.exports = Point; /***/ }), /* 429 */, /* 430 */, /* 431 */, /* 432 */, /* 433 */, /* 434 */, /* 435 */, /* 436 */, /* 437 */, /* 438 */, /* 439 */, /* 440 */, /* 441 */, /* 442 */, /* 443 */, /* 444 */, /* 445 */, /* 446 */, /* 447 */, /* 448 */, /* 449 */, /* 450 */, /* 451 */, /* 452 */, /* 453 */, /* 454 */, /* 455 */, /* 456 */, /* 457 */, /* 458 */, /* 459 */, /* 460 */, /* 461 */, /* 462 */, /* 463 */, /* 464 */, /* 465 */, /* 466 */, /* 467 */, /* 468 */, /* 469 */, /* 470 */, /* 471 */, /* 472 */, /* 473 */, /* 474 */, /* 475 */, /* 476 */, /* 477 */, /* 478 */, /* 479 */, /* 480 */, /* 481 */, /* 482 */, /* 483 */, /* 484 */, /* 485 */, /* 486 */, /* 487 */, /* 488 */, /* 489 */, /* 490 */, /* 491 */, /* 492 */, /* 493 */, /* 494 */, /* 495 */, /* 496 */, /* 497 */, /* 498 */, /* 499 */, /* 500 */, /* 501 */, /* 502 */, /* 503 */, /* 504 */, /* 505 */, /* 506 */, /* 507 */, /* 508 */, /* 509 */, /* 510 */, /* 511 */, /* 512 */, /* 513 */, /* 514 */, /* 515 */, /* 516 */, /* 517 */, /* 518 */, /* 519 */, /* 520 */, /* 521 */, /* 522 */, /* 523 */, /* 524 */, /* 525 */, /* 526 */, /* 527 */, /* 528 */, /* 529 */, /* 530 */, /* 531 */, /* 532 */, /* 533 */, /* 534 */, /* 535 */, /* 536 */, /* 537 */, /* 538 */, /* 539 */, /* 540 */, /* 541 */, /* 542 */, /* 543 */, /* 544 */, /* 545 */, /* 546 */, /* 547 */, /* 548 */, /* 549 */, /* 550 */, /* 551 */, /* 552 */, /* 553 */, /* 554 */, /* 555 */, /* 556 */, /* 557 */, /* 558 */, /* 559 */, /* 560 */, /* 561 */, /* 562 */ /***/ (function(module, exports, __webpack_require__) { var G2 = __webpack_require__(206); // geoms __webpack_require__(423); __webpack_require__(425); __webpack_require__(427); module.exports = G2; /***/ }) /******/ ]); }); //# sourceMappingURL=g2-simple.js.map