import * as d3 from 'd3'; // d3js module: animated line export default () => { // defaults const options = { strokewidth: 2, duration: 1500, endval: 0.10, width: 800, height: 26, round: 1, margin: { right: 50 }, colors: [ '#E3E3E3', '#D0021B' ] }; // start const draw = selection => { const textWidth = 40; const yval = options.strokewidth; const yvalText = options.height - options.strokewidth * 2; const xval = options.width * options.endval; const xvalText = options.endval < 0.51 ? xval : xval - textWidth; // add svg const svg = selection .append('svg') .attr('width', options.width) .attr('height', options.height); // append first line svg.append('line') .attr('x1', 0) .attr('y1', yval) .attr('x2', options.width) .attr('y2', yval) .attr('stroke-width', options.strokewidth) .attr('stroke', options.colors[0]) .attr('stroke-linecap', 'round'); // append second line svg.append('line') .attr('x1', 0) .attr('y1', yval) .attr('x2', 0) .attr('y2', yval) .attr('stroke-width', options.strokewidth) .attr('stroke', options.colors[1]) .attr('stroke-linecap', 'round') .transition() .duration(options.duration) .attr('x2', xval) .attr('y2', yval); // append text svg.append('text') .data([ options.endval * 100 ]) .text(0) .attr('x', 0) .attr('y', yvalText) .transition() .duration(options.duration) .attr('x', xvalText) .attr('y', yvalText) .tween('text', (endval, index, curObj) => { const i = d3.interpolate(curObj[index].textContent, endval); return t => { const val = Math.round(i(t) * options.round) / options.round; const localeString = parseFloat(val.toFixed(0)).toLocaleString('de-DE'); curObj[index].textContent = `${localeString}%`; }; }); }; // "setter" draw.options = input => { Object.assign(options, input); return draw; }; return draw; };