d3.js——使用svg

相比HTML元素,使用SVG能夠繪製出更多的圖形,此文嘗試將d3.js與SVG結合
因爲我也是第一次使用SVG,因此主要根據此篇blog的順序來Let’s Make a Bar Chart, IIhtml

靜態SVG使用

手打SVGapp

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

clipboard.png

g元素:用於組合對象的容器,添加到g元素上的變換會應用到全部子元素上
rect與text就沒啥好講了
同時,在SVG中有一個容易混淆的點:哪些樣式必定要寫在屬性之中(好比rect的width),哪些樣式能夠經過style表現(如fill,固然他們也能夠寫在屬性之中,但不知道爲何優先級低於class給予的樣式)。一個比較好記的方法就是:形狀幾何(如rect的width)要寫在屬性之中,修飾類的(如fill)可經過style表現dom

d3生成SVG

先貼代碼,CSS不變svg

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上,不用作另外的數據綁定spa

加載數據

d3.tsv()能夠用於加載解析TSV格式的數據code

總結

本文主要是講述了對svg的使用,但核心思想仍是不變的orm

參考資料

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

相關文章
相關標籤/搜索