【问题标题】:How to clip border partially with CSS (or SVG)?如何使用 CSS(或 SVG)部分剪切边框?
【发布时间】:2018-07-04 21:35:20
【问题描述】:

我想剪裁div 的边框,其中有一些border-radius 来模仿计时器如何到期。
但是除了clip-path: polygon(...)
之外找不到任何方法 但是构建自定义多边形似乎很难控制边框长度。

是否有一些更简单/更优雅的方式来使用 CSS(或者可能是 SVG)?
这是理想结果的图像,状态很少⇩⇩

【问题讨论】:

  • SVG - 和 stroke-dash-array
  • @Paulie_D 感谢您的指导!似乎stroke-dasharraystroke-dashoffset 的组合可以完成这项工作。我会试试的

标签: css svg border clip


【解决方案1】:

纯svg

使用线stroke-dashoffset的属性来实现画线的效果,即从行首缩进。

stroke-dashoffset达到最大值时该行隐藏,stroke-dashoffset = "0"时完全可见

因此,将stroke-dashoffset的值从最大值改为零,就得到了画线的效果。

<svg version="1.1" id="map_line_svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300" viewBox="0 0 300 300" >

    <rect x="50" y="100" width="200" height="100" rx="50" fill="#E0E9F6" stroke-width="4"  stroke="grey" stroke-dashoffset="600" stroke-dasharray="600">
	<animate attributeName="stroke-dashoffset" begin="1s" from="600" to="0" dur="7s" repeatCount="indefinite" />
	</rect>

</svg>

【讨论】:

  • 谢谢!这正是我想要的。此外,我发现了解stroke-dasharray 长度很有用。可以通过js函数rect.getTotalLength()获取
  • @Jamland 谢谢!如果你稍等一下,我会制作第二个版本的 CSS 并有更详细的描述
  • 有什么方法可以在 React 中实现相同的功能?以及如何找到 SVG 的长度?
  • @georgekrax 计算路径长度jsfiddle.net/mzy2wt91
  • @Alexandr_TT 感谢您的帮助!
【解决方案2】:

CSS+SVG

这个例子和第一个例子完全一样,只是将显示样式的样式转移到了外部样式表中。更多关于绘图技术的信息可以在这里找到 - Chris Coyier - stroke-dashoffset

你没看错,线的长度可以用JS的方法来计算——getTotalLength ()

下面是一个脚本示例,该脚本打印使用path 绘制的图形的路径长度:

<script>
  function TotalLength(){
   var path = document.querySelector('#check');
   var len = Math.round(path.getTotalLength() );
    alert("Path length - " + len);
        };
  </script>

下面是一个完整的动画示例:

#rect1 {
  stroke-dasharray: 600;
  stroke-dashoffset: 600;
  animation: dash 5s linear alternate infinite;
}

@keyframes dash {
  from {
    stroke-dashoffset: 600;
  }
  to {
    stroke-dashoffset: 0;
  }
} 
#rect1 {
fill:#E0E9F6;
stroke-width:4;  
stroke:grey;
}
<svg version="1.1" id="map_line_svg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="300" height="300" viewBox="0 0 300 300" >

    <rect id="rect1" x="50" y="100" width="200" height="100" rx="50"  />
</svg>  

如果您需要线条在一个方向上的移动动画,请将alternate 替换为forwards

【讨论】:

    【解决方案3】:

    我认为在这种情况下您不需要为偏移设置动画。在通过零点的情况下以及如果您想不从零点开始可能会出现问题。 我会使用 2 个参数 - 笔画长度和笔画空间,例如:

    <animate attributeName="stroke-dasharray" from="0 600" to="600 0" />
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-22
      • 2015-06-15
      • 1970-01-01
      • 2013-07-28
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 1970-01-01
      相关资源
      最近更新 更多