bar.js 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. import * as d3 from 'd3';
  2. // d3js module: animated line
  3. export default () => {
  4. // defaults
  5. const options = {
  6. strokewidth: 2,
  7. duration: 1500,
  8. endval: 0.10,
  9. width: 800,
  10. height: 26,
  11. round: 1,
  12. margin: { right: 50 },
  13. colors: [ '#E3E3E3', '#D0021B' ]
  14. };
  15. // start
  16. const draw = selection => {
  17. const textWidth = 40;
  18. const yval = options.strokewidth;
  19. const yvalText = options.height - options.strokewidth * 2;
  20. const xval = options.width * options.endval;
  21. const xvalText = options.endval < 0.51 ? xval : xval - textWidth;
  22. // add svg
  23. const svg = selection
  24. .append('svg')
  25. .attr('width', options.width)
  26. .attr('height', options.height);
  27. // append first line
  28. svg.append('line')
  29. .attr('x1', 0)
  30. .attr('y1', yval)
  31. .attr('x2', options.width)
  32. .attr('y2', yval)
  33. .attr('stroke-width', options.strokewidth)
  34. .attr('stroke', options.colors[0])
  35. .attr('stroke-linecap', 'round');
  36. // append second line
  37. svg.append('line')
  38. .attr('x1', 0)
  39. .attr('y1', yval)
  40. .attr('x2', 0)
  41. .attr('y2', yval)
  42. .attr('stroke-width', options.strokewidth)
  43. .attr('stroke', options.colors[1])
  44. .attr('stroke-linecap', 'round')
  45. .transition()
  46. .duration(options.duration)
  47. .attr('x2', xval)
  48. .attr('y2', yval);
  49. // append text
  50. svg.append('text')
  51. .data([ options.endval * 100 ])
  52. .text(0)
  53. .attr('x', 0)
  54. .attr('y', yvalText)
  55. .transition()
  56. .duration(options.duration)
  57. .attr('x', xvalText)
  58. .attr('y', yvalText)
  59. .tween('text', (endval, index, curObj) => {
  60. const i = d3.interpolate(curObj[index].textContent, endval);
  61. return t => {
  62. const val = Math.round(i(t) * options.round) / options.round;
  63. const localeString = parseFloat(val.toFixed(0)).toLocaleString('de-DE');
  64. curObj[index].textContent = `${localeString}%`;
  65. };
  66. });
  67. };
  68. // "setter"
  69. draw.options = input => {
  70. Object.assign(options, input);
  71. return draw;
  72. };
  73. return draw;
  74. };