d3.js使用svg

更新日期: 2019-03-24阅读: 2.6k标签: d3

相比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>


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的使用,但核心思想还是不变的


链接: https://www.fly63.com/article/detial/2488

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!