1

I am new on D3 and I am trying to detect when a shape overlap a path using D3 library. Actually the functionality of my code is that you can drag everywhere in the canvas a black rectangle and I need now to detect when the rectangle touch the circular path and attach to it like a magnet. I can't find nothing similar on the web so I wanna ask you if you can give me some hints. I think I have to detect rectangle's position and path coordinates.

Here you can see my code: https://jsfiddle.net/hsspve49/

var drag = d3.drag().on("drag", function () {
                var rect = d3.select(this);
                var theta = Math.atan2(d3.event.y - height/2, d3.event.x - width/2) * 180 / Math.PI

                rect
                    .attr("x", d3.event.x)
                    .attr("y", d3.event.y)
                    .attr('transform', `rotate(${theta + 90}, ${d3.event.x}, ${d3.event.y})`)

Thank you in advance.

Pierpaolo Ercoli
  • 1,028
  • 2
  • 11
  • 32
  • What you are looking for is called Collision Detection. There are several examples out there already. One that I remember: http://stackoverflow.com/questions/28647623/collision-overlap-detection-of-circles-in-a-d3-transition – ProgrammerV5 Apr 18 '17 at 12:56
  • ok, but, there it's about colliding between circular items, here I have a rectangle and a path. So I don't know if it's possible to use same logic of this example. There it call collide function giving it all the nodes – Pierpaolo Ercoli Apr 18 '17 at 13:01
  • 1
    It doesn't matter the shape: http://bl.ocks.org/ahmohamed/c1804b03b71d8a17bd37 – ProgrammerV5 Apr 18 '17 at 13:02
  • yes I know that it's not about the shape, but the thing is that I can move the black rectangle in all the canvas and I need to know when the rectangle touch the path. So I can't check if two nodes (brothers) touch themeselves. – Pierpaolo Ercoli Apr 18 '17 at 13:04
  • 1
    I understand that, and then again, read/search about Collision Detection in D3, that is what you are after. – ProgrammerV5 Apr 18 '17 at 13:06
  • Ok I am looking for it and I am trying to better understand the example you gave me. – Pierpaolo Ercoli Apr 18 '17 at 13:09
  • Even if you're going to use d3's collision detection, I believe you'll still have to implement the hit test. Circle-Polygon is well known, try http://stackoverflow.com/questions/401847/circle-rectangle-collision-detection-intersection – masonk Apr 18 '17 at 13:26
  • @ProgrammerV5 reading on the internet I learned that svg path as I thought is a set of points called nodes. So with getTotalLength() function now I have difficulties with finding the array of points because it is telling me node is undefined. I used this var arc2 = d3.arc() var pathEl = arc2.node(); var pathLength = pathEl.getTotalLength(); – Pierpaolo Ercoli Apr 18 '17 at 14:03

0 Answers0