graphic.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549
  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';
  41. import * as matrix from 'zrender/lib/core/matrix';
  42. import * as vector from 'zrender/lib/core/vector';
  43. import Path from 'zrender/lib/graphic/Path';
  44. import Transformable from 'zrender/lib/core/Transformable';
  45. import ZRImage from 'zrender/lib/graphic/Image';
  46. import Group from 'zrender/lib/graphic/Group';
  47. import ZRText from 'zrender/lib/graphic/Text';
  48. import Circle from 'zrender/lib/graphic/shape/Circle';
  49. import Ellipse from 'zrender/lib/graphic/shape/Ellipse';
  50. import Sector from 'zrender/lib/graphic/shape/Sector';
  51. import Ring from 'zrender/lib/graphic/shape/Ring';
  52. import Polygon from 'zrender/lib/graphic/shape/Polygon';
  53. import Polyline from 'zrender/lib/graphic/shape/Polyline';
  54. import Rect from 'zrender/lib/graphic/shape/Rect';
  55. import Line from 'zrender/lib/graphic/shape/Line';
  56. import BezierCurve from 'zrender/lib/graphic/shape/BezierCurve';
  57. import Arc from 'zrender/lib/graphic/shape/Arc';
  58. import CompoundPath from 'zrender/lib/graphic/CompoundPath';
  59. import LinearGradient from 'zrender/lib/graphic/LinearGradient';
  60. import RadialGradient from 'zrender/lib/graphic/RadialGradient';
  61. import BoundingRect from 'zrender/lib/core/BoundingRect';
  62. import OrientedBoundingRect from 'zrender/lib/core/OrientedBoundingRect';
  63. import Point from 'zrender/lib/core/Point';
  64. import IncrementalDisplayable from 'zrender/lib/graphic/IncrementalDisplayable';
  65. import * as subPixelOptimizeUtil from 'zrender/lib/graphic/helper/subPixelOptimize';
  66. import { extend, isArrayLike, map, defaults, isString, keys, each, hasOwn } from 'zrender/lib/core/util';
  67. import { getECData } from './innerStore';
  68. import { updateProps, initProps, removeElement, removeElementWithFadeOut, isElementRemoved } from '../animation/basicTrasition';
  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 register 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 rearly happen. So we dont 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(param) {
  225. subPixelOptimizeUtil.subPixelOptimizeLine(param.shape, param.shape, param.style);
  226. return param;
  227. }
  228. /**
  229. * Sub pixel optimize rect for canvas
  230. */
  231. export function subPixelOptimizeRect(param) {
  232. subPixelOptimizeUtil.subPixelOptimizeRect(param.shape, param.shape, param.style);
  233. return param;
  234. }
  235. /**
  236. * Sub pixel optimize for canvas
  237. *
  238. * @param position Coordinate, such as x, y
  239. * @param lineWidth Should be nonnegative integer.
  240. * @param positiveOrNegative Default false (negative).
  241. * @return Optimized position.
  242. */
  243. export var subPixelOptimize = subPixelOptimizeUtil.subPixelOptimize;
  244. /**
  245. * Get transform matrix of target (param target),
  246. * in coordinate of its ancestor (param ancestor)
  247. *
  248. * @param target
  249. * @param [ancestor]
  250. */
  251. export function getTransform(target, ancestor) {
  252. var mat = matrix.identity([]);
  253. while (target && target !== ancestor) {
  254. matrix.mul(mat, target.getLocalTransform(), mat);
  255. target = target.parent;
  256. }
  257. return mat;
  258. }
  259. /**
  260. * Apply transform to an vertex.
  261. * @param target [x, y]
  262. * @param transform Can be:
  263. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  264. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  265. * @param invert Whether use invert matrix.
  266. * @return [x, y]
  267. */
  268. export function applyTransform(target, transform, invert) {
  269. if (transform && !isArrayLike(transform)) {
  270. transform = Transformable.getLocalTransform(transform);
  271. }
  272. if (invert) {
  273. transform = matrix.invert([], transform);
  274. }
  275. return vector.applyTransform([], target, transform);
  276. }
  277. /**
  278. * @param direction 'left' 'right' 'top' 'bottom'
  279. * @param transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  280. * @param invert Whether use invert matrix.
  281. * @return Transformed direction. 'left' 'right' 'top' 'bottom'
  282. */
  283. export function transformDirection(direction, transform, invert) {
  284. // Pick a base, ensure that transform result will not be (0, 0).
  285. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : Math.abs(2 * transform[4] / transform[0]);
  286. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : Math.abs(2 * transform[4] / transform[2]);
  287. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  288. vertex = applyTransform(vertex, transform, invert);
  289. return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  290. }
  291. function isNotGroup(el) {
  292. return !el.isGroup;
  293. }
  294. function isPath(el) {
  295. return el.shape != null;
  296. }
  297. /**
  298. * Apply group transition animation from g1 to g2.
  299. * If no animatableModel, no animation.
  300. */
  301. export function groupTransition(g1, g2, animatableModel) {
  302. if (!g1 || !g2) {
  303. return;
  304. }
  305. function getElMap(g) {
  306. var elMap = {};
  307. g.traverse(function (el) {
  308. if (isNotGroup(el) && el.anid) {
  309. elMap[el.anid] = el;
  310. }
  311. });
  312. return elMap;
  313. }
  314. function getAnimatableProps(el) {
  315. var obj = {
  316. x: el.x,
  317. y: el.y,
  318. rotation: el.rotation
  319. };
  320. if (isPath(el)) {
  321. obj.shape = extend({}, el.shape);
  322. }
  323. return obj;
  324. }
  325. var elMap1 = getElMap(g1);
  326. g2.traverse(function (el) {
  327. if (isNotGroup(el) && el.anid) {
  328. var oldEl = elMap1[el.anid];
  329. if (oldEl) {
  330. var newProp = getAnimatableProps(el);
  331. el.attr(getAnimatableProps(oldEl));
  332. updateProps(el, newProp, animatableModel, getECData(el).dataIndex);
  333. }
  334. }
  335. });
  336. }
  337. export function clipPointsByRect(points, rect) {
  338. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  339. // and when element have border.
  340. return map(points, function (point) {
  341. var x = point[0];
  342. x = mathMax(x, rect.x);
  343. x = mathMin(x, rect.x + rect.width);
  344. var y = point[1];
  345. y = mathMax(y, rect.y);
  346. y = mathMin(y, rect.y + rect.height);
  347. return [x, y];
  348. });
  349. }
  350. /**
  351. * Return a new clipped rect. If rect size are negative, return undefined.
  352. */
  353. export function clipRectByRect(targetRect, rect) {
  354. var x = mathMax(targetRect.x, rect.x);
  355. var x2 = mathMin(targetRect.x + targetRect.width, rect.x + rect.width);
  356. var y = mathMax(targetRect.y, rect.y);
  357. var y2 = mathMin(targetRect.y + targetRect.height, rect.y + rect.height); // If the total rect is cliped, nothing, including the border,
  358. // should be painted. So return undefined.
  359. if (x2 >= x && y2 >= y) {
  360. return {
  361. x: x,
  362. y: y,
  363. width: x2 - x,
  364. height: y2 - y
  365. };
  366. }
  367. }
  368. export function createIcon(iconStr, // Support 'image://' or 'path://' or direct svg path.
  369. opt, rect) {
  370. var innerOpts = extend({
  371. rectHover: true
  372. }, opt);
  373. var style = innerOpts.style = {
  374. strokeNoScale: true
  375. };
  376. rect = rect || {
  377. x: -1,
  378. y: -1,
  379. width: 2,
  380. height: 2
  381. };
  382. if (iconStr) {
  383. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZRImage(innerOpts)) : makePath(iconStr.replace('path://', ''), innerOpts, rect, 'center');
  384. }
  385. }
  386. /**
  387. * Return `true` if the given line (line `a`) and the given polygon
  388. * are intersect.
  389. * Note that we do not count colinear as intersect here because no
  390. * requirement for that. We could do that if required in future.
  391. */
  392. export function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  393. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  394. var p = points[i];
  395. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  396. return true;
  397. }
  398. p2 = p;
  399. }
  400. }
  401. /**
  402. * Return `true` if the given two lines (line `a` and line `b`)
  403. * are intersect.
  404. * Note that we do not count colinear as intersect here because no
  405. * requirement for that. We could do that if required in future.
  406. */
  407. export function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  408. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  409. var mx = a2x - a1x;
  410. var my = a2y - a1y;
  411. var nx = b2x - b1x;
  412. var ny = b2y - b1y; // `vec_m` and `vec_n` are parallel iff
  413. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  414. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  415. if (nearZero(nmCrossProduct)) {
  416. return false;
  417. } // `vec_m` and `vec_n` are intersect iff
  418. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  419. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  420. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  421. var b1a1x = a1x - b1x;
  422. var b1a1y = a1y - b1y;
  423. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  424. if (q < 0 || q > 1) {
  425. return false;
  426. }
  427. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  428. if (p < 0 || p > 1) {
  429. return false;
  430. }
  431. return true;
  432. }
  433. /**
  434. * Cross product of 2-dimension vector.
  435. */
  436. function crossProduct2d(x1, y1, x2, y2) {
  437. return x1 * y2 - x2 * y1;
  438. }
  439. function nearZero(val) {
  440. return val <= 1e-6 && val >= -1e-6;
  441. }
  442. export function setTooltipConfig(opt) {
  443. var itemTooltipOption = opt.itemTooltipOption;
  444. var componentModel = opt.componentModel;
  445. var itemName = opt.itemName;
  446. var itemTooltipOptionObj = isString(itemTooltipOption) ? {
  447. formatter: itemTooltipOption
  448. } : itemTooltipOption;
  449. var mainType = componentModel.mainType;
  450. var componentIndex = componentModel.componentIndex;
  451. var formatterParams = {
  452. componentType: mainType,
  453. name: itemName,
  454. $vars: ['name']
  455. };
  456. formatterParams[mainType + 'Index'] = componentIndex;
  457. var formatterParamsExtra = opt.formatterParamsExtra;
  458. if (formatterParamsExtra) {
  459. each(keys(formatterParamsExtra), function (key) {
  460. if (!hasOwn(formatterParams, key)) {
  461. formatterParams[key] = formatterParamsExtra[key];
  462. formatterParams.$vars.push(key);
  463. }
  464. });
  465. }
  466. var ecData = getECData(opt.el);
  467. ecData.componentMainType = mainType;
  468. ecData.componentIndex = componentIndex;
  469. ecData.tooltipConfig = {
  470. name: itemName,
  471. option: defaults({
  472. content: itemName,
  473. formatterParams: formatterParams
  474. }, itemTooltipOptionObj)
  475. };
  476. } // Register built-in shapes. These shapes might be overwirtten
  477. // by users, although we do not recommend that.
  478. registerShape('circle', Circle);
  479. registerShape('ellipse', Ellipse);
  480. registerShape('sector', Sector);
  481. registerShape('ring', Ring);
  482. registerShape('polygon', Polygon);
  483. registerShape('polyline', Polyline);
  484. registerShape('rect', Rect);
  485. registerShape('line', Line);
  486. registerShape('bezierCurve', BezierCurve);
  487. registerShape('arc', Arc);
  488. 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 };