d3.js——运用svg

比拟HTML元素,运用SVG能够绘制出更多的图形,此文尝试将d3.js与SVG连系
因为我也是第一次运用SVG,所以重要根据此篇blog的递次来Let’s Make a Bar Chart, II

静态SVG运用

手打SVG

<style>
.chart rect {
  fill: steelblue;
}
.chart text {
  fill: white;
  font: 10px sans-serif;
  text-anchor: end;
}
</style>
<svg class="chart" width="420" height="120">
  <g transform="translate(0,0)">
    <rect width="40" height="19"></rect>
    <text x="37" y="9.5" dy=".35em">4</text>
  </g>
  <g transform="translate(0,20)">
    <rect width="80" height="19"></rect>
    <text x="77" y="9.5" dy=".35em">8</text>
  </g>
  <g transform="translate(0,40)">
    <rect width="150" height="19"></rect>
    <text x="147" y="9.5" dy=".35em">15</text>
  </g>
  <g transform="translate(0,60)">
    <rect width="160" height="19"></rect>
    <text x="157" y="9.5" dy=".35em">16</text>
  </g>
  <g transform="translate(0,80)">
    <rect width="230" height="19"></rect>
    <text x="227" y="9.5" dy=".35em">23</text>
  </g>
  <g transform="translate(0,100)">
    <rect width="420" height="19"></rect>
    <text x="417" y="9.5" dy=".35em">42</text>
  </g>
</svg>

《d3.js——运用svg》

g元素:用于组合对象的容器,添加到g元素上的变更会应用到一切子元素上
rect与text就没啥好讲了
同时,在SVG中有一个轻易殽杂的点:哪些款式一定要写在属性当中(比方rect的width),哪些款式能够经由过程style表现(如fill,固然他们也能够写在属性当中,但不晓得为何优先级低于class赋予的款式)。一个比较好记的要领就是:外形多少(如rect的width)要写在属性当中,润饰类的(如fill)可经由过程style表现

d3天生SVG

先贴代码,CSS稳定

    let data = [4, 8, 15, 16, 23, 42];
    let width = 420,
        barHeight = 20;
    let x = d3.scaleLinear()
        .domain([0, d3.max(data)])
        .range([0, width]);
    let chart = d3.select('.chart')
        .attr('width', width)
        .attr('height', barHeight * data.length);
    let bar = chart.selectAll('g')  //数据绑定在g上
        .data(data)
        .enter().append('g')
        .attr('transform', (d, i) => { return 'translate(0,' + i * barHeight + ')'});
    bar.append('rect')
        .attr('width', d => x(d))
        .attr('height', barHeight - 1);
    bar.append('text')
        .attr('x', d => x(d) - 3) //字符x轴位置
        .attr('y', barHeight/2) //字符y轴位置
        .attr('dy', '.35em') //字符相对位置
        .text(d => d);

实在差异不是迥殊多,只不过是用了SVG,而且把数据绑在g上,不用做别的的数据绑定

加载数据

d3.tsv()能够用于加载剖析TSV花样的数据

总结

本文重如果报告了对svg的运用,但中心头脑照样稳定的

参考资料

Let’s Make a Bar Chart, II
SVG 文本

    原文作者:Jonithan
    原文地址: https://segmentfault.com/a/1190000018628159
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞