PatternFill.js 21 KB

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