graphic.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. /*
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. /**
  20. * AUTO-GENERATED FILE. DO NOT MODIFY.
  21. */
  22. /*
  23. * Licensed to the Apache Software Foundation (ASF) under one
  24. * or more contributor license agreements. See the NOTICE file
  25. * distributed with this work for additional information
  26. * regarding copyright ownership. The ASF licenses this file
  27. * to you under the Apache License, Version 2.0 (the
  28. * "License"); you may not use this file except in compliance
  29. * with the License. You may obtain a copy of the License at
  30. *
  31. * http://www.apache.org/licenses/LICENSE-2.0
  32. *
  33. * Unless required by applicable law or agreed to in writing,
  34. * software distributed under the License is distributed on an
  35. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36. * KIND, either express or implied. See the License for the
  37. * specific language governing permissions and limitations
  38. * under the License.
  39. */
  40. import * as pathTool from 'zrender/lib/tool/path.js';
  41. import * as matrix from 'zrender/lib/core/matrix.js';
  42. import * as vector from 'zrender/lib/core/vector.js';
  43. import Path from 'zrender/lib/graphic/Path.js';
  44. import Transformable from 'zrender/lib/core/Transformable.js';
  45. import ZRImage from 'zrender/lib/graphic/Image.js';
  46. import Group from 'zrender/lib/graphic/Group.js';
  47. import ZRText from 'zrender/lib/graphic/Text.js';
  48. import Circle from 'zrender/lib/graphic/shape/Circle.js';
  49. import Ellipse from 'zrender/lib/graphic/shape/Ellipse.js';
  50. import Sector from 'zrender/lib/graphic/shape/Sector.js';
  51. import Ring from 'zrender/lib/graphic/shape/Ring.js';
  52. import Polygon from 'zrender/lib/graphic/shape/Polygon.js';
  53. import Polyline from 'zrender/lib/graphic/shape/Polyline.js';
  54. import Rect from 'zrender/lib/graphic/shape/Rect.js';
  55. import Line from 'zrender/lib/graphic/shape/Line.js';
  56. import BezierCurve from 'zrender/lib/graphic/shape/BezierCurve.js';
  57. import Arc from 'zrender/lib/graphic/shape/Arc.js';
  58. import CompoundPath from 'zrender/lib/graphic/CompoundPath.js';
  59. import LinearGradient from 'zrender/lib/graphic/LinearGradient.js';
  60. import RadialGradient from 'zrender/lib/graphic/RadialGradient.js';
  61. import BoundingRect from 'zrender/lib/core/BoundingRect.js';
  62. import OrientedBoundingRect from 'zrender/lib/core/OrientedBoundingRect.js';
  63. import Point from 'zrender/lib/core/Point.js';
  64. import IncrementalDisplayable from 'zrender/lib/graphic/IncrementalDisplayable.js';
  65. import * as subPixelOptimizeUtil from 'zrender/lib/graphic/helper/subPixelOptimize.js';
  66. import { extend, isArrayLike, map, defaults, isString, keys, each, hasOwn, isArray } from 'zrender/lib/core/util.js';
  67. import { getECData } from './innerStore.js';
  68. import { updateProps, initProps, removeElement, removeElementWithFadeOut, isElementRemoved } from '../animation/basicTransition.js';
  69. /**
  70. * @deprecated export for compatitable reason
  71. */
  72. export { updateProps, initProps, removeElement, removeElementWithFadeOut, isElementRemoved };
  73. var mathMax = Math.max;
  74. var mathMin = Math.min;
  75. var _customShapeMap = {};
  76. /**
  77. * Extend shape with parameters
  78. */
  79. export function extendShape(opts) {
  80. return Path.extend(opts);
  81. }
  82. var extendPathFromString = pathTool.extendFromString;
  83. /**
  84. * Extend path
  85. */
  86. export function extendPath(pathData, opts) {
  87. return extendPathFromString(pathData, opts);
  88. }
  89. /**
  90. * Register a user defined shape.
  91. * The shape class can be fetched by `getShapeClass`
  92. * This method will overwrite the registered shapes, including
  93. * the registered built-in shapes, if using the same `name`.
  94. * The shape can be used in `custom series` and
  95. * `graphic component` by declaring `{type: name}`.
  96. *
  97. * @param name
  98. * @param ShapeClass Can be generated by `extendShape`.
  99. */
  100. export function registerShape(name, ShapeClass) {
  101. _customShapeMap[name] = ShapeClass;
  102. }
  103. /**
  104. * Find shape class registered by `registerShape`. Usually used in
  105. * fetching user defined shape.
  106. *
  107. * [Caution]:
  108. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  109. * to use user registered shapes.
  110. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  111. * `registerShape` by default. That enables users to get both built-in
  112. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  113. * the built-in shapes by using names like 'circle', 'rect' via calling
  114. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  115. * in case that it is overwritten by users, except that some features, like
  116. * `custom series`, `graphic component`, do it deliberately.
  117. *
  118. * (2) In the features like `custom series`, `graphic component`, the user input
  119. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  120. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  121. * are reserved names, that is, if some user registers a shape named `'image'`,
  122. * the shape will not be used. If we intending to add some more reserved names
  123. * in feature, that might bring break changes (disable some existing user shape
  124. * names). But that case probably rarely happens. So we don't make more mechanism
  125. * to resolve this issue here.
  126. *
  127. * @param name
  128. * @return The shape class. If not found, return nothing.
  129. */
  130. export function getShapeClass(name) {
  131. if (_customShapeMap.hasOwnProperty(name)) {
  132. return _customShapeMap[name];
  133. }
  134. }
  135. /**
  136. * Create a path element from path data string
  137. * @param pathData
  138. * @param opts
  139. * @param rect
  140. * @param layout 'center' or 'cover' default to be cover
  141. */
  142. export function makePath(pathData, opts, rect, layout) {
  143. var path = pathTool.createFromString(pathData, opts);
  144. if (rect) {
  145. if (layout === 'center') {
  146. rect = centerGraphic(rect, path.getBoundingRect());
  147. }
  148. resizePath(path, rect);
  149. }
  150. return path;
  151. }
  152. /**
  153. * Create a image element from image url
  154. * @param imageUrl image url
  155. * @param opts options
  156. * @param rect constrain rect
  157. * @param layout 'center' or 'cover'. Default to be 'cover'
  158. */
  159. export function makeImage(imageUrl, rect, layout) {
  160. var zrImg = new ZRImage({
  161. style: {
  162. image: imageUrl,
  163. x: rect.x,
  164. y: rect.y,
  165. width: rect.width,
  166. height: rect.height
  167. },
  168. onload: function (img) {
  169. if (layout === 'center') {
  170. var boundingRect = {
  171. width: img.width,
  172. height: img.height
  173. };
  174. zrImg.setStyle(centerGraphic(rect, boundingRect));
  175. }
  176. }
  177. });
  178. return zrImg;
  179. }
  180. /**
  181. * Get position of centered element in bounding box.
  182. *
  183. * @param rect element local bounding box
  184. * @param boundingRect constraint bounding box
  185. * @return element position containing x, y, width, and height
  186. */
  187. function centerGraphic(rect, boundingRect) {
  188. // Set rect to center, keep width / height ratio.
  189. var aspect = boundingRect.width / boundingRect.height;
  190. var width = rect.height * aspect;
  191. var height;
  192. if (width <= rect.width) {
  193. height = rect.height;
  194. } else {
  195. width = rect.width;
  196. height = width / aspect;
  197. }
  198. var cx = rect.x + rect.width / 2;
  199. var cy = rect.y + rect.height / 2;
  200. return {
  201. x: cx - width / 2,
  202. y: cy - height / 2,
  203. width: width,
  204. height: height
  205. };
  206. }
  207. export var mergePath = pathTool.mergePath;
  208. /**
  209. * Resize a path to fit the rect
  210. * @param path
  211. * @param rect
  212. */
  213. export function resizePath(path, rect) {
  214. if (!path.applyTransform) {
  215. return;
  216. }
  217. var pathRect = path.getBoundingRect();
  218. var m = pathRect.calculateTransform(rect);
  219. path.applyTransform(m);
  220. }
  221. /**
  222. * Sub pixel optimize line for canvas
  223. */
  224. export function subPixelOptimizeLine(shape, lineWidth) {
  225. subPixelOptimizeUtil.subPixelOptimizeLine(shape, shape, {
  226. lineWidth: lineWidth
  227. });
  228. return shape;
  229. }
  230. /**
  231. * Sub pixel optimize rect for canvas
  232. */
  233. export function subPixelOptimizeRect(param) {
  234. subPixelOptimizeUtil.subPixelOptimizeRect(param.shape, param.shape, param.style);
  235. return param;
  236. }
  237. /**
  238. * Sub pixel optimize for canvas
  239. *
  240. * @param position Coordinate, such as x, y
  241. * @param lineWidth Should be nonnegative integer.
  242. * @param positiveOrNegative Default false (negative).
  243. * @return Optimized position.
  244. */
  245. export var subPixelOptimize = subPixelOptimizeUtil.subPixelOptimize;
  246. /**
  247. * Get transform matrix of target (param target),
  248. * in coordinate of its ancestor (param ancestor)
  249. *
  250. * @param target
  251. * @param [ancestor]
  252. */
  253. export function getTransform(target, ancestor) {
  254. var mat = matrix.identity([]);
  255. while (target && target !== ancestor) {
  256. matrix.mul(mat, target.getLocalTransform(), mat);
  257. target = target.parent;
  258. }
  259. return mat;
  260. }
  261. /**
  262. * Apply transform to an vertex.
  263. * @param target [x, y]
  264. * @param transform Can be:
  265. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  266. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  267. * @param invert Whether use invert matrix.
  268. * @return [x, y]
  269. */
  270. export function applyTransform(target, transform, invert) {
  271. if (transform && !isArrayLike(transform)) {
  272. transform = Transformable.getLocalTransform(transform);
  273. }
  274. if (invert) {
  275. transform = matrix.invert([], transform);
  276. }
  277. return vector.applyTransform([], target, transform);
  278. }
  279. /**
  280. * @param direction 'left' 'right' 'top' 'bottom'
  281. * @param transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  282. * @param invert Whether use invert matrix.
  283. * @return Transformed direction. 'left' 'right' 'top' 'bottom'
  284. */
  285. export function transformDirection(direction, transform, invert) {
  286. // Pick a base, ensure that transform result will not be (0, 0).
  287. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : Math.abs(2 * transform[4] / transform[0]);
  288. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : Math.abs(2 * transform[4] / transform[2]);
  289. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  290. vertex = applyTransform(vertex, transform, invert);
  291. return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  292. }
  293. function isNotGroup(el) {
  294. return !el.isGroup;
  295. }
  296. function isPath(el) {
  297. return el.shape != null;
  298. }
  299. /**
  300. * Apply group transition animation from g1 to g2.
  301. * If no animatableModel, no animation.
  302. */
  303. export function groupTransition(g1, g2, animatableModel) {
  304. if (!g1 || !g2) {
  305. return;
  306. }
  307. function getElMap(g) {
  308. var elMap = {};
  309. g.traverse(function (el) {
  310. if (isNotGroup(el) && el.anid) {
  311. elMap[el.anid] = el;
  312. }
  313. });
  314. return elMap;
  315. }
  316. function getAnimatableProps(el) {
  317. var obj = {
  318. x: el.x,
  319. y: el.y,
  320. rotation: el.rotation
  321. };
  322. if (isPath(el)) {
  323. obj.shape = extend({}, el.shape);
  324. }
  325. return obj;
  326. }
  327. var elMap1 = getElMap(g1);
  328. g2.traverse(function (el) {
  329. if (isNotGroup(el) && el.anid) {
  330. var oldEl = elMap1[el.anid];
  331. if (oldEl) {
  332. var newProp = getAnimatableProps(el);
  333. el.attr(getAnimatableProps(oldEl));
  334. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  335. }
  336. }
  337. });
  338. }
  339. export function clipPointsByRect(points, rect) {
  340. // FIXME: This way might be incorrect when graphic clipped by a corner
  341. // and when element has a border.
  342. return map(points, function (point) {
  343. var x = point[0];
  344. x = mathMax(x, rect.x);
  345. x = mathMin(x, rect.x + rect.width);
  346. var y = point[1];
  347. y = mathMax(y, rect.y);
  348. y = mathMin(y, rect.y + rect.height);
  349. return [x, y];
  350. });
  351. }
  352. /**
  353. * Return a new clipped rect. If rect size are negative, return undefined.
  354. */
  355. export function clipRectByRect(targetRect, rect) {
  356. var x = mathMax(targetRect.x, rect.x);
  357. var x2 = mathMin(targetRect.x + targetRect.width, rect.x + rect.width);
  358. var y = mathMax(targetRect.y, rect.y);
  359. var y2 = mathMin(targetRect.y + targetRect.height, rect.y + rect.height); // If the total rect is cliped, nothing, including the border,
  360. // should be painted. So return undefined.
  361. if (x2 >= x && y2 >= y) {
  362. return {
  363. x: x,
  364. y: y,
  365. width: x2 - x,
  366. height: y2 - y
  367. };
  368. }
  369. }
  370. export function createIcon(iconStr, // Support 'image://' or 'path://' or direct svg path.
  371. opt, rect) {
  372. var innerOpts = extend({
  373. rectHover: true
  374. }, opt);
  375. var style = innerOpts.style = {
  376. strokeNoScale: true
  377. };
  378. rect = rect || {
  379. x: -1,
  380. y: -1,
  381. width: 2,
  382. height: 2
  383. };
  384. if (iconStr) {
  385. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  386. }
  387. }
  388. /**
  389. * Return `true` if the given line (line `a`) and the given polygon
  390. * are intersect.
  391. * Note that we do not count colinear as intersect here because no
  392. * requirement for that. We could do that if required in future.
  393. */
  394. export function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  395. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  396. var p = points[i];
  397. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  398. return true;
  399. }
  400. p2 = p;
  401. }
  402. }
  403. /**
  404. * Return `true` if the given two lines (line `a` and line `b`)
  405. * are intersect.
  406. * Note that we do not count colinear as intersect here because no
  407. * requirement for that. We could do that if required in future.
  408. */
  409. export function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  410. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  411. var mx = a2x - a1x;
  412. var my = a2y - a1y;
  413. var nx = b2x - b1x;
  414. var ny = b2y - b1y; // `vec_m` and `vec_n` are parallel iff
  415. // existing `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  416. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  417. if (nearZero(nmCrossProduct)) {
  418. return false;
  419. } // `vec_m` and `vec_n` are intersect iff
  420. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  421. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  422. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  423. var b1a1x = a1x - b1x;
  424. var b1a1y = a1y - b1y;
  425. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  426. if (q < 0 || q > 1) {
  427. return false;
  428. }
  429. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  430. if (p < 0 || p > 1) {
  431. return false;
  432. }
  433. return true;
  434. }
  435. /**
  436. * Cross product of 2-dimension vector.
  437. */
  438. function crossProduct2d(x1, y1, x2, y2) {
  439. return x1 * y2 - x2 * y1;
  440. }
  441. function nearZero(val) {
  442. return val <= 1e-6 && val >= -1e-6;
  443. }
  444. export function setTooltipConfig(opt) {
  445. var itemTooltipOption = opt.itemTooltipOption;
  446. var componentModel = opt.componentModel;
  447. var itemName = opt.itemName;
  448. var itemTooltipOptionObj = isString(itemTooltipOption) ? {
  449. formatter: itemTooltipOption
  450. } : itemTooltipOption;
  451. var mainType = componentModel.mainType;
  452. var componentIndex = componentModel.componentIndex;
  453. var formatterParams = {
  454. componentType: mainType,
  455. name: itemName,
  456. $vars: ['name']
  457. };
  458. formatterParams[mainType + 'Index'] = componentIndex;
  459. var formatterParamsExtra = opt.formatterParamsExtra;
  460. if (formatterParamsExtra) {
  461. each(keys(formatterParamsExtra), function (key) {
  462. if (!hasOwn(formatterParams, key)) {
  463. formatterParams[key] = formatterParamsExtra[key];
  464. formatterParams.$vars.push(key);
  465. }
  466. });
  467. }
  468. var ecData = getECData(opt.el);
  469. ecData.componentMainType = mainType;
  470. ecData.componentIndex = componentIndex;
  471. ecData.tooltipConfig = {
  472. name: itemName,
  473. option: defaults({
  474. content: itemName,
  475. formatterParams: formatterParams
  476. }, itemTooltipOptionObj)
  477. };
  478. }
  479. function traverseElement(el, cb) {
  480. var stopped; // TODO
  481. // Polyfill for fixing zrender group traverse don't visit it's root issue.
  482. if (el.isGroup) {
  483. stopped = cb(el);
  484. }
  485. if (!stopped) {
  486. el.traverse(cb);
  487. }
  488. }
  489. export function traverseElements(els, cb) {
  490. if (els) {
  491. if (isArray(els)) {
  492. for (var i = 0; i < els.length; i++) {
  493. traverseElement(els[i], cb);
  494. }
  495. } else {
  496. traverseElement(els, cb);
  497. }
  498. }
  499. } // Register built-in shapes. These shapes might be overwritten
  500. // by users, although we do not recommend that.
  501. registerShape('circle', Circle);
  502. registerShape('ellipse', Ellipse);
  503. registerShape('sector', Sector);
  504. registerShape('ring', Ring);
  505. registerShape('polygon', Polygon);
  506. registerShape('polyline', Polyline);
  507. registerShape('rect', Rect);
  508. registerShape('line', Line);
  509. registerShape('bezierCurve', BezierCurve);
  510. registerShape('arc', Arc);
  511. export { Group, ZRImage as Image, ZRText as Text, Circle, Ellipse, Sector, Ring, Polygon, Polyline, Rect, Line, BezierCurve, Arc, IncrementalDisplayable, CompoundPath, LinearGradient, RadialGradient, BoundingRect, OrientedBoundingRect, Point, Path };