pattern-fill.src.js 20 KB

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