How To Get Drag Event In D3.js In Javascript?
Following is the code for drawing a force directed graph in javascript using d3.js I'm getting the graph on the canvas. However I'm getting the following error: & when I debu
Solution 1:
You're using d3 version 6. d3.event
has been removed. Please read the change log carefully, downgrade your d3 version, or look for more up to date examples.
const graph = {
nodes: [{
name: 'john',
age: 35
},
{
name: 'simon',
age: 37
},
{
name: 'manjoor',
age: 35
},
{
name: 'lorg',
age: 34
},
{
name: 'kilvin',
age: 32
},
],
links: [{
source: 'john',
target: 'simon'
},
{
source: 'john',
target: 'manjoor'
},
{
source: 'simon',
target: 'lorg'
},
{
source: 'simon',
target: 'kilvin'
},
{
source: 'manjoor',
target: 'kilvin'
},
{
source: 'lorg',
target: 'john'
},
{
source: 'lorg',
target: 'manjoor'
},
{
source: 'kilvin',
target: 'manjoor'
},
]
}
const canvas = d3.select('#network')
const width = canvas.attr('width')
const height = canvas.attr('height')
const r = 30const ctx = canvas.node().getContext('2d')
const color = d3.scaleOrdinal(d3.schemeAccent);
const simulation = d3.forceSimulation()
.force('x', d3.forceX(width / 2))
.force('y', d3.forceY(height / 2))
.force('collide', d3.forceCollide(r + 20))
.force('charge', d3.forceManyBody().strength(-100))
.force('link', d3.forceLink().id(node => node.name))
.on('tick', update)
simulation.nodes(graph.nodes)
simulation.force('link').links(graph.links)
canvas.call(d3.drag()
.container(canvas.node())
.subject(dragsubject).on('start', dragstarted)
.on('drag', dragged).on('end', dragended)
)
functionupdate() {
ctx.clearRect(0, 0, width, height)
ctx.beginPath()
ctx.globalAlpha = 0.5
ctx.strokeStyle = 'blue'
graph.links.forEach(drawLink)
ctx.stroke()
ctx.beginPath()
ctx.globalAlpha = 1
graph.nodes.forEach(drawNode)
ctx.fill()
}
functiondragsubject(event) {
return simulation.find(event.x, event.y);
}
functiondrawNode(d) {
ctx.fillStyle = color(d.party)
ctx.moveTo(d.x, d.y)
ctx.arc(d.x, d.y, r, 0, Math.PI * 2)
}
functiondrawLink(l) {
ctx.moveTo(l.source.x, l.source.y)
ctx.lineTo(l.target.x, l.target.y)
}
functiondragstarted(event) {
if (!event.active) simulation.alphaTarget(0.3).restart();
event.subject.fx = event.subject.x;
event.subject.fy = event.subject.y;
}
functiondragged(event) {
event.subject.fx = event.x;
event.subject.fy = event.y;
}
functiondragended(event) {
if (!event.active) simulation.alphaTarget(0);
event.subject.fx = null;
event.subject.fy = null;
}
update()
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/d3/6.2.0/d3.js"></script><canvasid="network"width="600"height="300"></canvas>
Post a Comment for "How To Get Drag Event In D3.js In Javascript?"