D3.js forceSimulationのラジアルフォース
D3.js forceSimulationのラジアルフォースを説明する。
サンプルプログラム
D3.js forceSimulationのforceRadialデモである。要素を円形に配置できる。
サンプルコード
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>D3 v7 force simulation force radial</title>
</head>
<body>
<svg width="800" height="600"></svg>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
// 1. 描画するデータを用意
var width = document.querySelector("svg").clientWidth;
var height = document.querySelector("svg").clientHeight;
var nodesData = [];
for (var i = 0; i < 50; i++) {
nodesData.push({
"x": width * Math.random(),
"y": height * Math.random(),
"r": parseInt(20 * Math.random() + 2)
});
}
// 2. SVG要素を追加
var node = d3.select("svg")
.selectAll("circle")
.data(nodesData)
.enter()
.append("circle")
.attr("r", function (d) { return d.r })
.attr("fill", "Gold")
.attr("stroke", "black")
.attr("opacity", 0.7)
.call(d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
// 3. forceSimulationを設定
var simulation = d3.forceSimulation()
.force("collide",
d3.forceCollide()
.radius(function (d) { return d.r + 1 })
.iterations(16))
.force("charge", d3.forceManyBody().strength(-30))
.force("r",
d3.forceRadial()
.radius(height * 0.35)
.x(width / 2)
.y(height / 2)
.strength(0.5)
);
simulation.velocityDecay(0.2);
simulation
.nodes(nodesData)
.on("tick", ticked);
// 4. forceSimulationの描画更新関数
function ticked() {
node
.attr("cx", function (d) { return d.x; })
.attr("cy", function (d) { return d.y; });
}
// 5. ドラッグイベント関数
function dragstarted(event, d) {
if (!event.active) simulation.alphaTarget(0.3).restart();
d.fx = d.x;
d.fy = d.y;
}
function dragged(event, d) {
d.fx = event.x;
d.fy = event.y;
}
function dragended(event, d) {
if (!event.active) simulation.alphaTarget(0);
d.fx = null;
d.fy = null;
}
</script>
</body>
</html>
説明
基本はノード相互作用のサンプルと同じである。ここでは「3. forceSimulationを設定」だけを説明する。
3. forceSimulationを設定
// 3. forceSimulationを設定
var simulation = d3.forceSimulation()
.force("collide",
d3.forceCollide()
.radius(function(d) { return d.r + 1 })
.iterations(16))
.force("charge", d3.forceManyBody().strength(-30))
// ここから説明 ---------------
.force("r",
d3.forceRadial()
.radius(height / 2 * 0.7)
.x(width / 2)
.y(height / 2)
.strength(0.5)
);
// ここまで説明 -----------------
simulation.velocityDecay(0.2);
simulation
.nodes(nodesData)
.on("tick", ticked);
forceSimulation.force()で設定できるパラメータを以下にまとめる。
“r”: ラジアルフォース
| 関数 | 説明 |
|---|---|
radius |
円の半径。 値を指定しない場合は現在の設定値を返す。 |
x |
円の中心x座標。デフォルトは 0である。 |
y |
円の中心y座標。デフォルトは 0である。 |
strength |
円の位置へノードが移動する速度。 1ステップで 距離 * strengthの分だけ変化する。1.0以上の数値は現在は使用しない。0.0から1.0の小数で設定する。デフォルトは 0.1である。 |