【问题标题】:How can I achieve a percentage-based line length on an SVG with stroke-dasharray?如何使用 stroke-dasharray 在 SVG 上实现基于百分比的线长?
【发布时间】:2020-07-11 09:58:49
【问题描述】:

我正在尝试在 SVG 矩形元素上实现基于百分比的类似边框的效果,如下图所示。我被告知我需要使用stroke-dasharray 来执行此操作,但是尽管使用了 JSFiddle,但我一直无法找到一种普遍适用于任何高度和宽度的 SVG 的解决方案。任何帮助或建议将不胜感激。

这是我目前在 JSFiddle 中使用的内容:

<html>
  <body>
    <div>
      <svg>
        <rect
          x="10"
          y="10"
          rx="10"
          ry="10"
          height="48"
          width="48"
          stroke-dasharray="50% 100%"
          style="stroke: black; fill: none;"
        />
      </svg>
    </div>
  </body>
</html>

Image of desired functionality

【问题讨论】:

  • 在 SVG 上使用 viewBox,然后不要使用百分比,因为您不需要它们。

标签: css svg frontend stroke-dasharray


【解决方案1】:

正如@enxaneta 评论的那样,总路径长度可以使用getTotalLength() 找到 方法

<html>
  <body>
    <div>
	<input  type="button" value="Total"  onclick="TotalLength()"/>
      <svg width="20%" height="20%" viewBox="0 0 60 60">
        <rect id="rect"
          x="10"
          y="10"
          rx="10"
          ry="10"
          height="48"
          width="48"
          style="stroke: black; fill: none;"
        />
      </svg>
    </div> 
	<script>
	 function TotalLength(){
          var path = document.querySelector('#rect');
        var len = (path.getTotalLength() );
        alert("Path length - " + len);
        };
	 
	</script>
  </body>
</html>

总路径长度为:174.42px

stroke-dasharray 属性是一个表示属性 定义用于绘制轮廓的虚线和间隙模式 形状;

当填充64%时,我们计算笔画长度:174.42 * 0.64 = 111.62

间隙长度:174.42 * 0.36 = 62.79stroke-dasharray = 111.62, 62.79

<html>
  <body>
    <div>
	  <svg width="20%" height="20%" viewBox="0 0 60 60">
        <rect id="rect"
          x="10"
          y="10"
          rx="10"
          ry="10"
          height="48"
          width="48"
          stroke-dasharray="111.62, 62.79"
          style="stroke: black; fill: none;"
        /> 
		  <text x="20" y ="40" font-size="16px" > 64% </text>
      </svg>
    </div> 
	
  </body>
</html>

【讨论】:

  • @Jimmy Rowe 如果答案有帮助,请记得将其标记为解决方案
猜你喜欢
  • 2018-05-12
  • 2019-04-03
  • 2014-04-02
  • 2018-11-11
  • 2021-08-08
  • 2016-03-13
  • 2019-08-18
  • 2013-12-23
  • 2014-10-01
相关资源
最近更新 更多