はじめに
- D3.jsを触ってみる。
サンプルコード
HTML
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>D3.js example</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <p>テスト</p> <p>テスト</p> <p>テスト</p> <p>テスト</p> <div class="circle"></div> <script src="https://d3js.org/d3.v6.min.js"></script> <script src="./script.js"></script> </body> </html>
JavaScript
// 背景の色を指定する d3.select("body").style("background-color", "aqua"); // Pタグを探してランダムで取得したカラーコードを設定していく。 d3.selectAll("p").style("color", function() { return "hsl(" + Math.random() * 360 + ",100%,50%)"; }); // Pタグを探してdata属性に指定した数値を順番に割り振りフォントの大きさを調整する。 d3.selectAll("p") .data([8,16, 42]) .style("font-size", function(d) { console.log(d) return d + "px"; }); d3.select("body") .selectAll("p") .data([4, 8, 15, 16, 23, 42]) .enter().append("p") .text(function(d) { return "I’m number " + d + "!"; });
アニメーション
下記のサンプルは、2秒後にfont-sizeを30pxにするアニメーション
d3.selectAll("p").transition() .style("font-size","30px").delay(2000).duration(2000);
円を描画するサンプル
var width = 400; var height = 400; var data = [10, 20, 30]; var colors = ['green', 'purple', 'yellow']; var svg = d3 .select("body") .append("svg") .attr("width", width) .attr("height", height); var g = svg.selectAll("g") .data(data) .enter() .append("g") .attr("transform", function(d, i) { return "translate(0,0)"; }) g.append("circle").attr("cx", function(d, i) { return i*75 + 50; }) .attr("cy", function(d, i) { return 75; }) .attr("r", function(d) { return d*1.5; }) .attr("fill", function(d, i){ return colors[i]; }) g.append("text").attr("x", function(d, i) { return i * 75 + 25; }) .attr("y", 80) .attr("stroke", "teal") .attr("font-size", "10px") .attr("font-family", "sans-serif").text(function(d) { return d; });
棒グラフのサンプル
<style> svg rect { fill: gray; } svg text { fill: yellow; font: 12px sans-serif; text-anchor: end; } </style> <script> var data = [10, 5, 12, 15]; var width = 300 scaleFactor = 20, barHeight = 30; var graph = d3.select("body") .append("svg") .attr("width", width) .attr("height", barHeight * data.length); var bar = graph.selectAll("g") .data(data) .enter() .append("g") .attr("transform", function(d, i) { return "translate(0," + i * barHeight + ")"; }); bar.append("rect").attr("width", function(d) { return d * scaleFactor; }) .attr("height", barHeight - 1); bar.append("text") .attr("x", function(d) { return (d*scaleFactor); }) .attr("y", barHeight / 2) .attr("dy", ".35em") .text(function(d) { return d; }); </script>
実行結果
console.logの結果