html - SVG:在圆弧中插入图像

标签 html css svg frontend

所以我有一个用 SVG 编写的“进度弧”。使用以下 CSS 规则在圆弧上绘制进度:

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

enter image description here

我想在进度弧的末尾放置一个指示器(以红色显示),但如何确定插入图像的位置?

谢谢

最佳答案

为了计算指示器的位置,您可以使用 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>

关于html - SVG:在圆弧中插入图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62083255/

相关文章:

asp.net - 启用压缩 fontawesome-webfont.svg

javascript - 将缩放圆附加到多线图

javascript - Plottable.Plots.Rectangle 创建宽度为 0 的矩形

html - 带有子弹的水平 li 不会在外部 block 上清除

html - float 未被清除

javascript - 在同一容器上切换类并显示具有选项卡效果的不同内容

php - 无法将我当前的菜单转换为 Bootstrap 菜单

css - 如何使 JPG 仅在悬停时加载?

javascript - 我在 Javascript 中的函数有问题

java - 打印输出从 arraylist 接收到的下拉列表中的值