SVG: вставить изображение по дуге - PullRequest
2 голосов
/ 29 мая 2020

Итак, у меня есть «прогресс c», написанный на SVG. Прогресс отображается на ar c с использованием этого правила CSS:

--percent: 30;
stroke-dashoffset: calc(436 - (var(--percent) * 436 / 100));

enter image description here

Я хочу поставить индикатор в конце прогресса ar c (отображается красным), но как я могу определить позицию для вставки изображения?

Спасибо

1 Ответ

1 голос
/ 29 мая 2020

Для расчета позиции индикатора вы можете использовать метод getPointAtLength(), например:

Пожалуйста, прочтите комментарии в моем коде.

// the center of the progress arc
let c= {x:0,y:90}
// the radius of the progress arc
let r = 70;
// the starting and the ending angle for the progress arc
let a1 = -210 * Math.PI / 180;
let a2 = 30 * Math.PI / 180;
// the starting point for the progress arc
let p1 = {
  x: c.x+r*Math.cos(a1),
  y: c.y+r*Math.sin(a1)
}
// the ending point for the progress arc
let p2 = {
  x: c.x+r*Math.cos(a2),
  y: c.y+r*Math.sin(a2)
}
//the value of the d attribute for the base (silver) and the arc (red)
let d = `M${p1.x}, ${p1.y}A${r},${r},0 1 1 ${p2.x}, ${p2.y}`;
base.setAttributeNS(null,"d",d);
arc.setAttributeNS(null,"d",d);


let percent = 30;
//the total length of the arc and the base
//also the value used for the stroke-dasharray
let sda = arc.getTotalLength();
//the value for the stroke-dashoffset
let sdo = sda - (percent*sda/100);
//set the "stroke-dasharray" and the "stroke-dashoffset" for the arc
arc.setAttributeNS(null,"stroke-dasharray",sda);
arc.setAttributeNS(null,"stroke-dashoffset",sdo);


//calculate the position for the indicator: a golden point in this case
let p = arc.getPointAtLength(percent*sda/100)
img.setAttributeNS(null,"cx",p.x);
img.setAttributeNS(null,"cy",p.y);
svg{border:solid;width:300px}
<svg viewBox="-100 0 200 150">
  <path id="base" fill="none" stroke="silver" stroke-width="8" stroke-linecap ="round" />
  <path id="arc" fill="none" stroke="red" stroke-width="8" stroke-linecap ="round" />
  
  <circle id="img" r="2" fill="gold"/>
</svg>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...