Нарисуйте круг, разделенный пополам - PullRequest
0 голосов
/ 28 октября 2018

Я хочу создать svg, подобный этому:

enter image description here

Итак, окружность разделена аккордом на две части.Два раздела должны иметь разные цвета.

Я хочу нарисовать этот объект в SVG.Я думаю, что мне нужно использовать тег PATH, верно?Или есть другой способ сделать это?Какие точки мне нужно нарисовать объект?Я немного смущен ..

1 Ответ

0 голосов
/ 28 октября 2018

Да.Это элемент <path>, который вам понадобится.

Пути всегда начинаются с M (перемещение) команды .Вам также понадобится команда A (дуга) и, возможно, L строка команды для линии, которая делит пополам окружность.

ДляКоманда дуги, вам просто нужно знать координаты X и Y начальной и конечной точек (B и C).Плюс радиус круга.Важно иметь точные координаты для начальной и конечной точек команды дуги.Небольшие расхождения могут привести к небольшому смещению положения круга.

В следующей демонстрации я выбрал для вычисления положения B и C на основе их угла от центра.Кроме того, установка атрибута описания пути из кода позволяет мне задокументировать, для чего предназначен каждый из параметров.

// Radius of the circle
var radius = 80;

// Centre coordinate of the circle
var Ox = 100;
var Oy = 100;

// Angles of each point from which we calculate their X and Y coordinates.
// Here, 0 degrees is East, and angle increases in a clockwise direction.
var angleB = 285;  // degrees
var angleC = 35;

var B = angleToCoords(angleB, Ox, Oy, radius);
var C = angleToCoords(angleC, Ox, Oy, radius);

// Get the "major segment" path element
var majorPath = document.getElementById("major");

// Set the path description for the "major segment"
majorPath.setAttribute("d", ['M', B.x, B.y,         // Move to point B
                             'L', C.x, C.y,         // Line to point C
                             'A', radius, radius,   // X radius and Y radius of the arc
                                  0,                // ellipse angle
                                  1,                // large arc flag (1 indicates we want the larger of the two possible arcs between the points
                                  1,                // clockwise direction flag
                                  B.x, B.y,         // arc end point is back at point B
                             'Z'].join(" "));       // Z command closes the path

// Get the "minor segment" path element
var minorPath = document.getElementById("minor");

// Set the path description for the "minor segment"
minorPath.setAttribute("d", ['M', B.x, B.y,         // Move to point B
                             'A', radius, radius,   // X radius and Y radius of the arc
                                  0,                // ellipse angle
                                  0,                // large arc flag (0 indicates we want the smaller of the two possible arcs between the points
                                  1,                // clockwise direction flag
                                  C.x, C.y,         // arc end point is at point C
                             'L', B.x, B.y,         // Line to point B
                             'Z'].join(" "));       // Z command closes the path


// Function to convert from an angle to an X and Y position
function angleToCoords(angleInDegrees, centreX, centreY, radius)
{
  var angleInRadians = angleInDegrees * Math.PI / 180;
  return {
    'x': centreX + (radius * Math.cos(angleInRadians)),
    'y': centreY + (radius * Math.sin(angleInRadians))
  }
}
path {
  stroke: black;
  stroke-width: 1;
}

#major {
  fill: #78dcdc;
}

#minor {
  fill: #aaffaa;
}
<svg width="200" height="200">

  <path id="major" d="" />
  <path id="minor" d="" />

</svg>
...