pattern-fill.src.js 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571
  1. /**
  2. * @license Highcharts JS v8.0.0 (2019-12-10)
  3. *
  4. * Module for adding patterns and images as point fills.
  5. *
  6. * (c) 2010-2019 Highsoft AS
  7. * Author: Torstein Hønsi, Øystein Moseng
  8. *
  9. * License: www.highcharts.com/license
  10. */
  11. 'use strict';
  12. (function (factory) {
  13. if (typeof module === 'object' && module.exports) {
  14. factory['default'] = factory;
  15. module.exports = factory;
  16. } else if (typeof define === 'function' && define.amd) {
  17. define('highcharts/modules/pattern-fill', ['highcharts'], function (Highcharts) {
  18. factory(Highcharts);
  19. factory.Highcharts = Highcharts;
  20. return factory;
  21. });
  22. } else {
  23. factory(typeof Highcharts !== 'undefined' ? Highcharts : undefined);
  24. }
  25. }(function (Highcharts) {
  26. var _modules = Highcharts ? Highcharts._modules : {};
  27. function _registerModule(obj, path, args, fn) {
  28. if (!obj.hasOwnProperty(path)) {
  29. obj[path] = fn.apply(null, args);
  30. }
  31. }
  32. _registerModule(_modules, 'modules/pattern-fill.src.js', [_modules['parts/Globals.js'], _modules['parts/Utilities.js']], function (H, U) {
  33. /* *
  34. *
  35. * Module for using patterns or images as point fills.
  36. *
  37. * (c) 2010-2019 Highsoft AS
  38. * Author: Torstein Hønsi, Øystein Moseng
  39. *
  40. * License: www.highcharts.com/license
  41. *
  42. * !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
  43. *
  44. * */
  45. /**
  46. * Pattern options
  47. *
  48. * @interface Highcharts.PatternOptionsObject
  49. */ /**
  50. * Background color for the pattern if a `path` is set (not images).
  51. * @name Highcharts.PatternOptionsObject#backgroundColor
  52. * @type {Highcharts.ColorString}
  53. */ /**
  54. * URL to an image to use as the pattern.
  55. * @name Highcharts.PatternOptionsObject#image
  56. * @type {string}
  57. */ /**
  58. * Width of the pattern. For images this is automatically set to the width of
  59. * the element bounding box if not supplied. For non-image patterns the default
  60. * is 32px. Note that automatic resizing of image patterns to fill a bounding
  61. * box dynamically is only supported for patterns with an automatically
  62. * calculated ID.
  63. * @name Highcharts.PatternOptionsObject#width
  64. * @type {number}
  65. */ /**
  66. * Analogous to pattern.width.
  67. * @name Highcharts.PatternOptionsObject#height
  68. * @type {number}
  69. */ /**
  70. * For automatically calculated width and height on images, it is possible to
  71. * set an aspect ratio. The image will be zoomed to fill the bounding box,
  72. * maintaining the aspect ratio defined.
  73. * @name Highcharts.PatternOptionsObject#aspectRatio
  74. * @type {number}
  75. */ /**
  76. * Horizontal offset of the pattern. Defaults to 0.
  77. * @name Highcharts.PatternOptionsObject#x
  78. * @type {number|undefined}
  79. */ /**
  80. * Vertical offset of the pattern. Defaults to 0.
  81. * @name Highcharts.PatternOptionsObject#y
  82. * @type {number|undefined}
  83. */ /**
  84. * Either an SVG path as string, or an object. As an object, supply the path
  85. * string in the `path.d` property. Other supported properties are standard SVG
  86. * attributes like `path.stroke` and `path.fill`. If a path is supplied for the
  87. * pattern, the `image` property is ignored.
  88. * @name Highcharts.PatternOptionsObject#path
  89. * @type {string|Highcharts.SVGAttributes}
  90. */ /**
  91. * Pattern color, used as default path stroke.
  92. * @name Highcharts.PatternOptionsObject#color
  93. * @type {Highcharts.ColorString}
  94. */ /**
  95. * Opacity of the pattern as a float value from 0 to 1.
  96. * @name Highcharts.PatternOptionsObject#opacity
  97. * @type {number}
  98. */ /**
  99. * ID to assign to the pattern. This is automatically computed if not added, and
  100. * identical patterns are reused. To refer to an existing pattern for a
  101. * Highcharts color, use `color: "url(#pattern-id)"`.
  102. * @name Highcharts.PatternOptionsObject#id
  103. * @type {string|undefined}
  104. */
  105. /**
  106. * Holds a pattern definition.
  107. *
  108. * @sample highcharts/series/pattern-fill-area/
  109. * Define a custom path pattern
  110. * @sample highcharts/series/pattern-fill-pie/
  111. * Default patterns and a custom image pattern
  112. * @sample maps/demo/pattern-fill-map/
  113. * Custom images on map
  114. *
  115. * @example
  116. * // Pattern used as a color option
  117. * color: {
  118. * pattern: {
  119. * path: {
  120. * d: 'M 3 3 L 8 3 L 8 8 Z',
  121. * fill: '#102045'
  122. * },
  123. * width: 12,
  124. * height: 12,
  125. * color: '#907000',
  126. * opacity: 0.5
  127. * }
  128. * }
  129. *
  130. * @interface Highcharts.PatternObject
  131. */ /**
  132. * Pattern options
  133. * @name Highcharts.PatternObject#pattern
  134. * @type {Highcharts.PatternOptionsObject}
  135. */ /**
  136. * Animation options for the image pattern loading.
  137. * @name Highcharts.PatternObject#animation
  138. * @type {boolean|Highcharts.AnimationOptionsObject|undefined}
  139. */ /**
  140. * Optionally an index referencing which pattern to use. Highcharts adds
  141. * 10 default patterns to the `Highcharts.patterns` array. Additional
  142. * pattern definitions can be pushed to this array if desired. This option
  143. * is an index into this array.
  144. * @name Highcharts.PatternObject#patternIndex
  145. * @type {number|undefined}
  146. */
  147. var animObject = U.animObject, erase = U.erase, pick = U.pick, wrap = U.wrap;
  148. var addEvent = H.addEvent, merge = H.merge;
  149. // Add the predefined patterns
  150. H.patterns = (function () {
  151. var patterns = [], colors = H.getOptions().colors;
  152. [
  153. 'M 0 0 L 10 10 M 9 -1 L 11 1 M -1 9 L 1 11',
  154. 'M 0 10 L 10 0 M -1 1 L 1 -1 M 9 11 L 11 9',
  155. 'M 3 0 L 3 10 M 8 0 L 8 10',
  156. 'M 0 3 L 10 3 M 0 8 L 10 8',
  157. 'M 0 3 L 5 3 L 5 0 M 5 10 L 5 7 L 10 7',
  158. 'M 3 3 L 8 3 L 8 8 L 3 8 Z',
  159. 'M 5 5 m -4 0 a 4 4 0 1 1 8 0 a 4 4 0 1 1 -8 0',
  160. 'M 10 3 L 5 3 L 5 0 M 5 10 L 5 7 L 0 7',
  161. 'M 2 5 L 5 2 L 8 5 L 5 8 Z',
  162. 'M 0 0 L 5 10 L 10 0'
  163. ].forEach(function (pattern, i) {
  164. patterns.push({
  165. path: pattern,
  166. color: colors[i],
  167. width: 10,
  168. height: 10
  169. });
  170. });
  171. return patterns;
  172. })();
  173. /**
  174. * Utility function to compute a hash value from an object. Modified Java
  175. * String.hashCode implementation in JS. Use the preSeed parameter to add an
  176. * additional seeding step.
  177. *
  178. * @private
  179. * @function hashFromObject
  180. *
  181. * @param {object} obj
  182. * The javascript object to compute the hash from.
  183. *
  184. * @param {boolean} [preSeed=false]
  185. * Add an optional preSeed stage.
  186. *
  187. * @return {string}
  188. * The computed hash.
  189. */
  190. function hashFromObject(obj, preSeed) {
  191. var str = JSON.stringify(obj), strLen = str.length || 0, hash = 0, i = 0, char, seedStep;
  192. if (preSeed) {
  193. seedStep = Math.max(Math.floor(strLen / 500), 1);
  194. for (var a = 0; a < strLen; a += seedStep) {
  195. hash += str.charCodeAt(a);
  196. }
  197. hash = hash & hash;
  198. }
  199. for (; i < strLen; ++i) {
  200. char = str.charCodeAt(i);
  201. hash = ((hash << 5) - hash) + char;
  202. hash = hash & hash;
  203. }
  204. return hash.toString(16).replace('-', '1');
  205. }
  206. /**
  207. * Set dimensions on pattern from point. This function will set internal
  208. * pattern._width/_height properties if width and height are not both already
  209. * set. We only do this on image patterns. The _width/_height properties are set
  210. * to the size of the bounding box of the point, optionally taking aspect ratio
  211. * into account. If only one of width or height are supplied as options, the
  212. * undefined option is calculated as above.
  213. *
  214. * @private
  215. * @function Highcharts.Point#calculatePatternDimensions
  216. *
  217. * @param {Highcharts.PatternOptionsObject} pattern
  218. * The pattern to set dimensions on.
  219. *
  220. * @return {void}
  221. *
  222. * @requires modules/pattern-fill
  223. */
  224. H.Point.prototype.calculatePatternDimensions = function (pattern) {
  225. if (pattern.width && pattern.height) {
  226. return;
  227. }
  228. var bBox = this.graphic && (this.graphic.getBBox &&
  229. this.graphic.getBBox(true) ||
  230. this.graphic.element &&
  231. this.graphic.element.getBBox()) || {}, shapeArgs = this.shapeArgs;
  232. // Prefer using shapeArgs, as it is animation agnostic
  233. if (shapeArgs) {
  234. bBox.width = shapeArgs.width || bBox.width;
  235. bBox.height = shapeArgs.height || bBox.height;
  236. bBox.x = shapeArgs.x || bBox.x;
  237. bBox.y = shapeArgs.y || bBox.y;
  238. }
  239. // For images we stretch to bounding box
  240. if (pattern.image) {
  241. // If we do not have a bounding box at this point, simply add a defer
  242. // key and pick this up in the fillSetter handler, where the bounding
  243. // box should exist.
  244. if (!bBox.width || !bBox.height) {
  245. pattern._width = 'defer';
  246. pattern._height = 'defer';
  247. return;
  248. }
  249. // Handle aspect ratio filling
  250. if (pattern.aspectRatio) {
  251. bBox.aspectRatio = bBox.width / bBox.height;
  252. if (pattern.aspectRatio > bBox.aspectRatio) {
  253. // Height of bBox will determine width
  254. bBox.aspectWidth = bBox.height * pattern.aspectRatio;
  255. }
  256. else {
  257. // Width of bBox will determine height
  258. bBox.aspectHeight = bBox.width / pattern.aspectRatio;
  259. }
  260. }
  261. // We set the width/height on internal properties to differentiate
  262. // between the options set by a user and by this function.
  263. pattern._width = pattern.width ||
  264. Math.ceil(bBox.aspectWidth || bBox.width);
  265. pattern._height = pattern.height ||
  266. Math.ceil(bBox.aspectHeight || bBox.height);
  267. }
  268. // Set x/y accordingly, centering if using aspect ratio, otherwise adjusting
  269. // so bounding box corner is 0,0 of pattern.
  270. if (!pattern.width) {
  271. pattern._x = pattern.x || 0;
  272. pattern._x += bBox.x - Math.round(bBox.aspectWidth ?
  273. Math.abs(bBox.aspectWidth - bBox.width) / 2 :
  274. 0);
  275. }
  276. if (!pattern.height) {
  277. pattern._y = pattern.y || 0;
  278. pattern._y += bBox.y - Math.round(bBox.aspectHeight ?
  279. Math.abs(bBox.aspectHeight - bBox.height) / 2 :
  280. 0);
  281. }
  282. };
  283. /* eslint-disable no-invalid-this */
  284. /**
  285. * Add a pattern to the renderer.
  286. *
  287. * @private
  288. * @function Highcharts.SVGRenderer#addPattern
  289. *
  290. * @param {Highcharts.PatternObject} options
  291. * The pattern options.
  292. *
  293. * @param {boolean|Highcharts.AnimationOptionsObject} [animation]
  294. * The animation options.
  295. *
  296. * @return {Highcharts.SVGElement|undefined}
  297. * The added pattern. Undefined if the pattern already exists.
  298. *
  299. * @requires modules/pattern-fill
  300. */
  301. H.SVGRenderer.prototype.addPattern = function (options, animation) {
  302. var pattern, animate = pick(animation, true), animationOptions = animObject(animate), path, defaultSize = 32, width = options.width || options._width || defaultSize, height = (options.height || options._height || defaultSize), color = options.color || '#343434', id = options.id, ren = this, rect = function (fill) {
  303. ren.rect(0, 0, width, height)
  304. .attr({ fill: fill })
  305. .add(pattern);
  306. }, attribs;
  307. if (!id) {
  308. this.idCounter = this.idCounter || 0;
  309. id = 'highcharts-pattern-' + this.idCounter + '-' + (this.chartIndex || 0);
  310. ++this.idCounter;
  311. }
  312. // Do nothing if ID already exists
  313. this.defIds = this.defIds || [];
  314. if (this.defIds.indexOf(id) > -1) {
  315. return;
  316. }
  317. // Store ID in list to avoid duplicates
  318. this.defIds.push(id);
  319. // Create pattern element
  320. pattern = this.createElement('pattern').attr({
  321. id: id,
  322. patternUnits: 'userSpaceOnUse',
  323. patternContentUnits: options.patternContentUnits || 'userSpaceOnUse',
  324. width: width,
  325. height: height,
  326. x: options._x || options.x || 0,
  327. y: options._y || options.y || 0
  328. }).add(this.defs);
  329. // Set id on the SVGRenderer object
  330. pattern.id = id;
  331. // Use an SVG path for the pattern
  332. if (options.path) {
  333. path = options.path;
  334. // The background
  335. if (options.backgroundColor) {
  336. rect(options.backgroundColor);
  337. }
  338. // The pattern
  339. attribs = {
  340. 'd': path.d || path
  341. };
  342. if (!this.styledMode) {
  343. attribs.stroke = path.stroke || color;
  344. attribs['stroke-width'] = pick(path.strokeWidth, 2);
  345. attribs.fill = path.fill || 'none';
  346. }
  347. if (path.transform) {
  348. attribs.transform = path.transform;
  349. }
  350. this.createElement('path').attr(attribs).add(pattern);
  351. pattern.color = color;
  352. // Image pattern
  353. }
  354. else if (options.image) {
  355. if (animate) {
  356. this.image(options.image, 0, 0, width, height, function () {
  357. // Onload
  358. this.animate({
  359. opacity: pick(options.opacity, 1)
  360. }, animationOptions);
  361. H.removeEvent(this.element, 'load');
  362. }).attr({ opacity: 0 }).add(pattern);
  363. }
  364. else {
  365. this.image(options.image, 0, 0, width, height).add(pattern);
  366. }
  367. }
  368. // For non-animated patterns, set opacity now
  369. if (!(options.image && animate) && typeof options.opacity !== 'undefined') {
  370. [].forEach.call(pattern.element.childNodes, function (child) {
  371. child.setAttribute('opacity', options.opacity);
  372. });
  373. }
  374. // Store for future reference
  375. this.patternElements = this.patternElements || {};
  376. this.patternElements[id] = pattern;
  377. return pattern;
  378. };
  379. // Make sure we have a series color
  380. wrap(H.Series.prototype, 'getColor', function (proceed) {
  381. var oldColor = this.options.color;
  382. // Temporarely remove color options to get defaults
  383. if (oldColor &&
  384. oldColor.pattern &&
  385. !oldColor.pattern.color) {
  386. delete this.options.color;
  387. // Get default
  388. proceed.apply(this, Array.prototype.slice.call(arguments, 1));
  389. // Replace with old, but add default color
  390. oldColor.pattern.color =
  391. this.color;
  392. this.color = this.options.color = oldColor;
  393. }
  394. else {
  395. // We have a color, no need to do anything special
  396. proceed.apply(this, Array.prototype.slice.call(arguments, 1));
  397. }
  398. });
  399. // Calculate pattern dimensions on points that have their own pattern.
  400. addEvent(H.Series, 'render', function () {
  401. var isResizing = this.chart.isResizing;
  402. if (this.isDirtyData || isResizing || !this.chart.hasRendered) {
  403. (this.points || []).forEach(function (point) {
  404. var colorOptions = point.options && point.options.color;
  405. if (colorOptions &&
  406. colorOptions.pattern) {
  407. // For most points we want to recalculate the dimensions on
  408. // render, where we have the shape args and bbox. But if we
  409. // are resizing and don't have the shape args, defer it, since
  410. // the bounding box is still not resized.
  411. if (isResizing &&
  412. !(point.shapeArgs &&
  413. point.shapeArgs.width &&
  414. point.shapeArgs.height)) {
  415. colorOptions.pattern._width =
  416. 'defer';
  417. colorOptions.pattern._height =
  418. 'defer';
  419. }
  420. else {
  421. point.calculatePatternDimensions(colorOptions.pattern);
  422. }
  423. }
  424. });
  425. }
  426. });
  427. // Merge series color options to points
  428. addEvent(H.Point, 'afterInit', function () {
  429. var point = this, colorOptions = point.options.color;
  430. // Only do this if we have defined a specific color on this point. Otherwise
  431. // we will end up trying to re-add the series color for each point.
  432. if (colorOptions && colorOptions.pattern) {
  433. // Move path definition to object, allows for merge with series path
  434. // definition
  435. if (typeof colorOptions.pattern.path === 'string') {
  436. colorOptions.pattern.path = {
  437. d: colorOptions.pattern.path
  438. };
  439. }
  440. // Merge with series options
  441. point.color = point.options.color = merge(point.series.options.color, colorOptions);
  442. }
  443. });
  444. // Add functionality to SVG renderer to handle patterns as complex colors
  445. H.addEvent(H.SVGRenderer, 'complexColor', function (args) {
  446. var color = args.args[0], prop = args.args[1], element = args.args[2], chartIndex = (this.chartIndex || 0);
  447. var pattern = color.pattern, value = '#343434';
  448. // Handle patternIndex
  449. if (typeof color.patternIndex !== 'undefined' && H.patterns) {
  450. pattern = H.patterns[color.patternIndex];
  451. }
  452. // Skip and call default if there is no pattern
  453. if (!pattern) {
  454. return true;
  455. }
  456. // We have a pattern.
  457. if (pattern.image ||
  458. typeof pattern.path === 'string' ||
  459. pattern.path && pattern.path.d) {
  460. // Real pattern. Add it and set the color value to be a reference.
  461. // Force Hash-based IDs for legend items, as they are drawn before
  462. // point render, meaning they are drawn before autocalculated image
  463. // width/heights. We don't want them to highjack the width/height for
  464. // this ID if it is defined by users.
  465. var forceHashId = element.parentNode &&
  466. element.parentNode.getAttribute('class');
  467. forceHashId = forceHashId &&
  468. forceHashId.indexOf('highcharts-legend') > -1;
  469. // If we don't have a width/height yet, handle it. Try faking a point
  470. // and running the algorithm again.
  471. if (pattern._width === 'defer' || pattern._height === 'defer') {
  472. H.Point.prototype.calculatePatternDimensions.call({ graphic: { element: element } }, pattern);
  473. }
  474. // If we don't have an explicit ID, compute a hash from the
  475. // definition and use that as the ID. This ensures that points with
  476. // the same pattern definition reuse existing pattern elements by
  477. // default. We combine two hashes, the second with an additional
  478. // preSeed algorithm, to minimize collision probability.
  479. if (forceHashId || !pattern.id) {
  480. // Make a copy so we don't accidentally edit options when setting ID
  481. pattern = merge({}, pattern);
  482. pattern.id = 'highcharts-pattern-' + chartIndex + '-' +
  483. hashFromObject(pattern) + hashFromObject(pattern, true);
  484. }
  485. // Add it. This function does nothing if an element with this ID
  486. // already exists.
  487. this.addPattern(pattern, !this.forExport && pick(pattern.animation, this.globalAnimation, { duration: 100 }));
  488. value = "url(" + this.url + "#" + pattern.id + ")";
  489. }
  490. else {
  491. // Not a full pattern definition, just add color
  492. value = pattern.color || value;
  493. }
  494. // Set the fill/stroke prop on the element
  495. element.setAttribute(prop, value);
  496. // Allow the color to be concatenated into tooltips formatters etc.
  497. color.toString = function () {
  498. return value;
  499. };
  500. // Skip default handler
  501. return false;
  502. });
  503. // When animation is used, we have to recalculate pattern dimensions after
  504. // resize, as the bounding boxes are not available until then.
  505. H.addEvent(H.Chart, 'endResize', function () {
  506. if ((this.renderer && this.renderer.defIds || []).filter(function (id) {
  507. return (id &&
  508. id.indexOf &&
  509. id.indexOf('highcharts-pattern-') === 0);
  510. }).length) {
  511. // We have non-default patterns to fix. Find them by looping through
  512. // all points.
  513. this.series.forEach(function (series) {
  514. series.points.forEach(function (point) {
  515. var colorOptions = point.options && point.options.color;
  516. if (colorOptions &&
  517. colorOptions.pattern) {
  518. colorOptions.pattern._width =
  519. 'defer';
  520. colorOptions.pattern._height =
  521. 'defer';
  522. }
  523. });
  524. });
  525. // Redraw without animation
  526. this.redraw(false);
  527. }
  528. });
  529. // Add a garbage collector to delete old patterns with autogenerated hashes that
  530. // are no longer being referenced.
  531. H.addEvent(H.Chart, 'redraw', function () {
  532. var usedIds = [], renderer = this.renderer,
  533. // Get the autocomputed patterns - these are the ones we might delete
  534. patterns = (renderer.defIds || []).filter(function (pattern) {
  535. return (pattern.indexOf &&
  536. pattern.indexOf('highcharts-pattern-') === 0);
  537. });
  538. if (patterns.length) {
  539. // Look through the DOM for usage of the patterns. This can be points,
  540. // series, tooltips etc.
  541. [].forEach.call(this.renderTo.querySelectorAll('[color^="url("], [fill^="url("], [stroke^="url("]'), function (node) {
  542. var id = node.getAttribute('fill') ||
  543. node.getAttribute('color') ||
  544. node.getAttribute('stroke');
  545. if (id) {
  546. usedIds.push(id
  547. .substring(id.indexOf('url(') + 5)
  548. .replace(')', ''));
  549. }
  550. });
  551. // Loop through the patterns that exist and see if they are used
  552. patterns.forEach(function (id) {
  553. if (usedIds.indexOf(id) === -1) {
  554. // Remove id from used id list
  555. erase(renderer.defIds, id);
  556. // Remove pattern element
  557. if (renderer.patternElements[id]) {
  558. renderer.patternElements[id].destroy();
  559. delete renderer.patternElements[id];
  560. }
  561. }
  562. });
  563. }
  564. });
  565. });
  566. _registerModule(_modules, 'masters/modules/pattern-fill.src.js', [], function () {
  567. });
  568. }));