pattern-fill.src.js 21 KB

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