PatternFill.js 21 KB

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