我有以下代码(在 TypeScript 中)创建一条折线(基于 4 个不同的点 x1y1、xCy1、xCy1、x2y2,其中 Xc 是平面上 x1 和 x2 之间的一半距离),因此它不是圆形.
private createPolyline(points: Array<[number, number]>): SVGPolylineElement {
let polyline: SVGPolylineElement = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
let pointsAttr: string = points.map(point => point.join(',')).join(' ');
polyline.setAttribute('points', pointsAttr);
polyline.setAttribute('stroke', 'green');
polyline.setAttribute('stroke-width', '2');
polyline.setAttribute('fill', 'none');
polyline.setAttribute('stroke-dasharray', '25');
polyline.setAttribute('stroke-dashoffset', '40');
polyline.style.animation = 'dash 5s linear infinite';
return polyline;
}
我想要的基本上是具有连续流动的虚线的外观。上述方法实现了这一点,但 5 秒后它将重置到破折号的原始位置并重新启动动画。
有没有办法让这个无限连续?
有2个选项。
选择足够高的动画延迟和
stroke-dashoffset
。例如,300 秒和 2400。很简单。下面的例子。
自己使用动画,不断增加
stroke-dashoffset
。请参阅使用 CSS 和 JavaScript 创建无限向前的 SVG 动画。
function createPolyline(points) {
let polyline = document.createElementNS('http://www.w3.org/2000/svg', 'polyline');
let pointsAttr = points.map(point => point.join(',')).join(' ');
polyline.setAttribute('points', pointsAttr);
polyline.setAttribute('stroke', 'green');
polyline.setAttribute('stroke-width', '2');
polyline.setAttribute('fill', 'none');
polyline.setAttribute('stroke-dasharray', '25');
polyline.setAttribute('stroke-dashoffset', '4000');
polyline.style.animation = 'dash 300s linear infinite';
return polyline;
}
var poly = createPolyline([[50,0], [21,90], [98,35], [2,35], [79,90]])
document.querySelector("#mySomething").append(poly)
@keyframes dash {
to {
stroke-dashoffset: 0;
}
}
<svg id="mySomething" viewBox="-10 -10 240 240" xmlns="http://www.w3.org/2000/svg">