PatternFill.js 21 KB

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