Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

D3: Simple Interaction - Circle with a click

I am learning D3. I know easy things like making a scatter plot and all. My next step is trying some simple interactive moves. For example, after I have an svg appended, axes and grids made, now I wish to make a circle by clicking a point within the svg canvas. I guess I will have to record coordinate of the clicked point and then append a circle with its cx nad cy, but how? How to record the coordinate?

I appreciate you show me a tutorial, give a hint or best of all an example.

like image 749
ngungo Avatar asked Oct 06 '14 19:10

ngungo


1 Answers

If you are familiar with JQuery then D3 should have a friendly feel to it, as it shares a similar API. Specifically in regards to .on(action, fn) syntax for attaching an event listener to a DOM selection.

If you check out the jsFiddle I have created which implements a very basic implementation of what you are after then you can see this in motion in 21 lines of JS.

(function() {
    var svg = d3.select('svg');

    function getRandom(min, max) {
      return Math.floor(Math.random() * (max - min) + min);
    }

    function drawCircle(x, y, size) {
        console.log('Drawing circle at', x, y, size);
        svg.append("circle")
            .attr('class', 'click-circle')
            .attr("cx", x)
            .attr("cy", y)
            .attr("r", size);
    }

    svg.on('click', function() {
        var coords = d3.mouse(this);
        console.log(coords);
        drawCircle(coords[0], coords[1], getRandom(5,50));
    });
})();

The most important aspects of this snippet are on lines 18-20 (.on(...) and d3.mouse(this)). The on('click',..) event is attached to the svg element. When a click occurs d3.mouse is called with the current scope as its argument. It then returns an array with x and y coords of the mouse event. This information is then passed to drawCircle, along with a random radius to draw a circle on the current SVG canvas.

I advise you to take the jsFiddle and have a play!

like image 59
GordyD Avatar answered Nov 16 '22 05:11

GordyD