【问题标题】:SVG: insert image in arcSVG:在弧中插入图像
【发布时间】:2020-09-16 20:43:28
【问题描述】:

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

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

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

谢谢

【问题讨论】:

    标签: html css svg frontend


    【解决方案1】:

    为了计算指标的位置,您可以使用getPointAtLength() 方法,如下所示:

    请阅读我代码中的 cmets。

    // 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>

    【讨论】:

    • 谢谢你这是一个完美的答案!你能澄清一下半径和角度的计算吗?那会有很大帮助。再次感谢。
    • 您可以根据需要更改半径和角度。请记住,您需要以弧度表示的角度。例如 30 度 = 30 * Math.PI / 180 弧度。如果 a2 为 30 度,也适用于 simetry a1 = -30 - 180 = -210 度
    猜你喜欢
    • 2021-06-06
    • 2022-01-04
    • 2023-04-05
    • 2022-11-07
    • 1970-01-01
    • 2011-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多