i am trying to make a force directed graph using d3 and i am in latest version v7.
const width = 800;
const height = 800;
var layoutCanvas = d3
.select("#graphDiv")
.append("canvas")
.attr("width", width + "px")
.attr("height", height + "px")
.node();
// this.setState({ canvasAdded: true });
let context = layoutCanvas!.getContext("2d")!;
if (!context) {
console.log("no 2d context found");
return;
}
var transform = d3.zoomIdentity;
d3.json("test1.json").then((data: any) => {
console.log(data);
const simulation = d3
.forceSimulation(data.nodes)
.force("charge", null)
.force("center", d3.forceCenter())
.force("link", d3.forceLink(data.edges));
initGraph(data);
function initGraph(data) {
simulation.on("tick", simulationUpdate);
function simulationUpdate() {
context.save();
context.clearRect(0, 0, width, height);
context.translate(transform.x, transform.y);
context.scale(transform.k, transform.k);
data.edges.forEach(function (d) {
context.beginPath();
context.moveTo(d.source.x, d.source.y);
context.lineTo(d.target.x, d.target.y);
context.stroke();
});
// Draw the nodes
data.nodes.forEach(function (d, i) {
context.beginPath();
context.arc(d.x, d.y, 2, 0, 2 * Math.PI, true);
context.fillStyle = d.col ? "red" : "black";
context.fill();
});
context.restore();
}
}
});
this is my code and the test1.json file is this:source
When i log that data that is read from the d3.json() function
My major problem is that the canvas is 800x800 but when i log the node and edge position it shows above 800.
If anyone can help it would be appreciated.
Ps: the position X and Y in json is in between 0 and 1.