pattern-fill.src.js 19 KB

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