6

I have a telerik RadHtmlChart which generates some svg for a graph.

http://jsfiddle.net/L8Gcg/3/

The graph currently looks like this:

enter image description here

Each circle has a label associated with it. Unfortunately they tend to bunch up and overlap each other.

I'd like to move the text elements up/down with javascript so they don't all overlap but I'm not sure the best way to go about it.

I wrote some code to loop through the <text> svg elements but am stuck on the overlap detection/moving part.

var svg = document.getElementsByTagName("svg")[0];
var svgLabels = svg.getElementsByTagName("text");

for (i = 0; i < svgLabels.length; i++) {
    //Check for overlap, move if necessary
}

Is there some way to do this nicely?

Andrew Walters
  • 4,763
  • 6
  • 35
  • 49

1 Answers1

0

This is actually a question that I am struggling with for making d3 driven data maps. I've seen answers similar to the what I'm providing below in other stack overflow channels but right now I can't seem to find them. I think that what you are looking for is something like .getBoundingClientRect(). The general logic is to loop through each element and compare it to all the others through an embedded loop to determine if there is overlap. You can use this algorithm to determine if there is overlap like in here: http://www.inkfood.com/collision-detection-with-svg/;

Here's what the code might look like minus the actual block that moves the text:

for(var i = 0; i < svgLabels.length; i++){
var self = svgLabels[i],
    a = self.getBoundingClientRect();
for(var j = 0; j < svgLabels.length; j++ ){
    var that = svgLabels[j];
  if(self != that){
    var b = that.getBoundingClientRect();
    if( !( b.left > a.right  ||
         b.right < a.left ||
       b.top > a.bottom || 
       b.bottom < a.top
       ) ){
       // move text
       }
  }
}
}
DimeZilla
  • 98
  • 7
  • Thank you. This is very neat. If anyone has pointers on how to do this with an svg that isn't contained in the html I'd like to know. – ChameleonScales Jan 05 '23 at 10:21