Как рассчитать минимальное расстояние от края любых двух круговых SVG - PullRequest
3 голосов
/ 03 февраля 2020

Я знаю, что вы обычно используете теорему Пифагора, чтобы получить расстояние между точками, но у круга нет x1 и x2. Вот пример. Без этих значений, как я могу рассчитать расстояния?

circle {
  fill: orange;
}
<svg transform="translate(0, 22)">
  <circle class="point" cx="121.78235294117647" cy="13.200000000000001" r="3.1058823529411765" stroke="rgb(0, 0, 0)" stroke-width="1" data-values="[0.047]"></circle>
  <circle class="point" cx="125.2764705882353" cy="30.28235294117647" r="3.1058823529411765" stroke="rgb(0, 0, 0)" stroke-width="1" data-values="[0.042]"></circle>
  <circle class="point" cx="112.8529411764706" cy="30.67058823529412" r="3.1058823529411765" stroke="rgb(0, 0, 0)" stroke-width="1" data-values="[0.037]"></circle>
  <circle class="point" cx="103.53529411764706" cy="32.22352941176471" r="3.1058823529411765" stroke="rgb(0, 0, 0)" stroke-width="1" data-values="[0.047]">
</svg>

Ответы [ 3 ]

3 голосов
/ 03 февраля 2020

Расстояние между двумя кругами равно расстоянию между их центрами минус сумма их радиусов.

function distanceOfPoints(p0, p1) {
    let dx = p0.x - p1.x;
    let dy = p0.y - p1.y;
    return Math.sqrt(dx*dx + dy*dy);
}

function distanceOfCircles(cen0, rad0, cen1, rad1) {
    // if the circles intersect, our distance might be negative
    return Math.max(0, distanceOfPoints(cen0, cen1) - rad0 - rad1);
}

В SVG cx и cy являются центрами круга ( cen0, cen1) и r - их радиус (rad0, rad1).

Чтобы получить минимальное расстояние между ВСЕМИ кружками, вы можете l oop через все пары круги и обновите результат-расстояние, когда вы найдете более низкое значение.

2 голосов
/ 03 февраля 2020

Чтобы вычислить минимальное расстояние между двумя кругами, сначала вы берете вектор, который соединяет два центра окружности, и вычисляете его длину. После этого вы вычитаете радиусы обоих кругов, потому что ближайшие точки обоих кругов должны находиться вдали от центра круга точно на расстоянии каждого радиуса.

Редактировать: Расстояние по горизонтали и вертикали значения не обязательно должны быть положительными, потому что они все равно будут возведены в квадрат на следующем шаге (спасибо @Jan Schultke за совет).

const circle1 = {
  x: 13,      // horizontal center coordinate
  y: 4,       // vertical center coordinate
  radius: 5
};

const circle2 = {
  x: 9,      // horizontal center coordinate
  y: 24,       // vertical center coordinate
  radius: 3
};

function minimumDistance(circle1, circle2) {
  const horizontalDistance = circle1.x - circle2.x;
  const verticalDistance = circle1.y - circle2.y;

  const distanceBetweenCenter = Math.sqrt(horizontalDistance**2 + verticalDistance**2);  // pythagoras

  return distanceBetweenCenter - circle1.radius - circle2.radius;
}

console.log(minimumDistance(circle1, circle2));
1 голос
/ 04 февраля 2020

Я нашел этот вопрос интересным вчера.

Мой ответ более буквален к вопросу, основанному на @ Spark Fountain и @ Jan Schultke отличных ответах. Концепции принадлежат им.

Ниже javascript основан на каждом svg круге, имеющем свой уникальный идентификатор.

// find our distance between two svg circles by id
function distance(circle1,circle2) {

    // get our specified circles by id
    let c1 = document.getElementById(circle1);
    let c2 = document.getElementById(circle2);
    
    // circle one attributes
    c1 = {
      x: c1.getAttribute("cx"),
      y: c1.getAttribute("cy"),
      r: c1.getAttribute("r")
    };
		
    // circle two attributes
    c2 = {
      x: c2.getAttribute("cx"),   
      y: c2.getAttribute("cy"),
      r: c2.getAttribute("r")
    };
     
    // lets work out each x and y axis distance
    // not too worry about negative values
    let x = c1.x - c2.x;
    let y = c1.y - c2.y;
    
    // lets work out the hypotenuse between x and y using pythagoras
    // negative x or y values become absolute when squared
    let distance = Math.sqrt(x**2 + y**2);
    
    // now minus the radius of both circles from our distance
    // to equal the distance from the edge of the circles
    // math.max largest of zero or more incase circles overlap
    distance = Math.max(0, distance - c1.r - c2.r);
      
    console.log('distance between circle ' + circle1 + ' and ' + circle2 + ' is ' + distance);
    
    // return the distance
    return distance;
    
}

// check your console for distance
distance('4','3');
distance('1','2');
distance('3','1');
distance('2','3');
<svg transform="translate(0, 22)">
  <circle id="1" class="point" cx="121.78235294117647" cy="13.200000000000001" r="3.1058823529411765" stroke="rgb(0, 0, 0)" stroke-width="1" data-values="[0.047]"></circle>
  <circle id="2" class="point" cx="125.2764705882353" cy="30.28235294117647" r="3.1058823529411765" stroke="rgb(0, 0, 0)" stroke-width="1" data-values="[0.042]"></circle>
  <circle id="3" class="point" cx="112.8529411764706" cy="30.67058823529412" r="3.1058823529411765" stroke="rgb(0, 0, 0)" stroke-width="1" data-values="[0.037]"></circle>
  <circle id="4" class="point" cx="103.53529411764706" cy="32.22352941176471" r="3.1058823529411765" stroke="rgb(0, 0, 0)" stroke-width="1" data-values="[0.047]"></circle>
</svg>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...