D3: Easy interaction - Circle with a click

I am learning D3. I know simple things like scatter and all. In the next step, we try to perform some simple interactive actions. For example, after I created svg, axes and meshes, now I want to create a circle by clicking a point in the svg canvas. I think I will have to write down the coordinate of the clicked point, and then add the circle using cx nad cy, but how? How to record a coordinate?

I appreciate you showing me the tutorial, giving me a hint, or best example.

+7
interactive
source share
1 answer

If you are familiar with jQuery, then D3 should have a friendly attitude to it, since it has a similar API. In particular, with regard to the syntax .on(action, fn) for attaching an event listener to a DOM selection.

If you look at jsFiddle , I created one that implements a very basic implementation of what you are after, you can see this in movement in the 21st line 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 fragment are in lines 18-20 ( .on(...) and d3.mouse(this) ). The on('click',..) event is bound to the svg element. When d3.mouse , the current region is called as an argument. Then it returns an array with x and y coordinates 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 jsFiddle and play a game !

+7
source share

All Articles