How To Add Mouse Events To Force Directed Graph Using The D3 Canvas Renderer?
Solution 1:
In D3 v4.x, you add a click event pretty much the same way you do in v3.x:
selection.on("click", function(d){
//do whatever you want with the datum
});
The problem in your question is not v3 versus v4, that's not the issue in the code you shared. The problem with that code is that it uses HTML canvas, not SVG, to render the dataviz.
Unlike SVG, canvas doesn't have a node tree of elements. You cannot "select something" and add an event handler to it.
Think of canvas as a raster image, like a BMP or a JPEG. You can find on what x and y position you clicked, you can even find the colour of that pixel, but you cannot select a given node element, because canvas has none.
For instance, check this tutorial from Nadieh Bremer to see how complicated is to get the circle the user clicks on when you use HTML canvas.
Solution 2:
Since I used the canvas renderer, I just cheated and used the d3 dragstart event already in the example. There's probably a way to do it like this I'd like to know.
d3.select(canvas)
.call(d3.drag()
.container(canvas)
.subject(dragsubject)
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d3.event.subject.fx = d3.event.subject.x;
d3.event.subject.fy = d3.event.subject.y;
//broadcast the selection to parent
emitter.emit( d3.event.subject );
}
Solution 3:
Expanded FlavorScape's hack with double click
d3.select(canvas)
.call(d3.drag()
.container(canvas)
.subject(dragsubject)
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended));
var clickDate = new Date();
var difference_ms;
function dragstarted(d) {
if (!d3.event.active) simulation.alphaTarget(0.3).restart();
d3.event.subject.fx = d3.event.subject.x;
d3.event.subject.fy = d3.event.subject.y;
difference_ms = (new Date()).getTime() - clickDate.getTime();
clickDate = new Date();
//if clicks less than 200ms apart (double click)if(difference_ms < 200)
console.log( d3.event.subject );
}
Post a Comment for "How To Add Mouse Events To Force Directed Graph Using The D3 Canvas Renderer?"