gpt4 book ai didi

javascript - 更改 d3.js 强制节点 Canvas 布局中节点组的颜色

转载 作者:行者123 更新时间:2023-12-03 06:22:34 24 4
gpt4 key购买 nike

我有一个强制图表:

var canvas = document.querySelector("canvas"),
context = canvas.getContext("2d"),
width = canvas.width,
height = canvas.height,
min = 5;

var simulation = d3.forceSimulation()
.force("link", d3.forceLink()
.id(function(d) { return d.id; })
.iterations(2)
.distance(function(d) {
return Math.sqrt((600 - d.value)) / 10;
})
.strength(8)
)
.force("charge", d3.forceManyBody()
.strength(-300)
.theta(0.9)
.distanceMax(400)
)
.force("center", d3.forceCenter(width / 2, height / 2)
)
.force("collision", d3.forceCollide(1))
;


d3.json("/contigderivatives/data/", function(error, graph) {
if (error) throw error;

simulation
.nodes(graph.nodes)
.on("tick", ticked);

simulation.force("link")
.links(graph.links);

d3.select(canvas)
.call(d3.drag()
.container(canvas)
.subject(dragsubject)
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));

function ticked() {
context.clearRect(0, 0, width, height);

context.beginPath();
graph.links.forEach(drawLink);
context.strokeStyle = "#aaa";
context.stroke();

context.beginPath();
graph.nodes.forEach(drawNode);
context.strokeStyle = "#fff";
context.fillStyle = 'steelblue';
context.stroke();
context.fill();
}
function dragsubject() {
return simulation.find(d3.event.x, d3.event.y);
}
});

function dragstarted() {
if (!d3.event.active) simulation.alphaTarget(0.1).restart();
d3.event.subject.fx = d3.event.subject.x;
d3.event.subject.fy = d3.event.subject.y;
}

function dragged() {
d3.event.subject.fx = d3.event.x;
d3.event.subject.fy = d3.event.y;
}

function dragended() {
if (!d3.event.active) simulation.alphaTarget(0);
d3.event.subject.fx = null;
d3.event.subject.fy = null;
}

function drawLink(d) {
context.moveTo(d.source.x, d.source.y);
context.lineTo(d.target.x, d.target.y);
}

function drawNode(d){
d.x = Math.max(min, Math.min(width - min, d.x));
d.y = Math.max(min, Math.min(height - min, d.y));
context.moveTo(d.x + 3, d.y);
context.arc(d.x, d.y, 3, 0, 2 * Math.PI);
}

我尝试根据 JSON 中指定的整数分组来更改节点的颜色,其中 0 = 红色,1 = 蓝色。有很多关于如何在使用 SVG 时更改节点样式的示例,但在使用 Canvas 时却没有很多。更改行 context.fillStyle = 'steelblue'; 会更改所有节点的填充颜色。使用 Canvas 时如何更改单个节点的样式和属性?

最佳答案

我做了一个色标

 var color = d3.scaleOrdinal(d3.schemeCategory10);

然后在每个节点上根据节点数据属性绘制 I 颜色:

  function drawNode(d) {
context.beginPath();//for each node do begin path as context fill style and stroke are different.
context.moveTo(d.x + 3, d.y);
context.arc(d.x, d.y, 3, 0, 2 * Math.PI);
context.fillStyle = color(d.group);//coloring on the basis of the group
context.strokeStyle = color(d.group);
context.fill();
context.stroke();
}

根据您在评论中提到的 bl.ock 图,我制作了一个小型工作示例 here

希望这能解决您的问题。

关于javascript - 更改 d3.js 强制节点 Canvas 布局中节点组的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38799493/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com