解决方案 #1:
最后,我在 css 中找到了一个仅使用 css 变量的解决方案。唯一的缺点是这个 css 变量提供了每个笔划的实际路径长度(在使用任何类型的脚本语言创建笔划时,这只能计算一次)。在 svg 中,on 将 pathLength="1000" 替换为 style="--L:nnn",其中 --L 是一个 css 变量,而 nnn 是路径的实际长度:
<svg width="1000px" height="100px">
<g stroke="#FAB" stroke-width="3">
<line style="--L:500;" id="Line1" x1="20" y1="20" x2="520" y2="20"/>
<line style="--L:760;" id="Line2" x1="20" y1="50" x2="780" y2="50"/>
</g>
</svg>
在css中,在@keyframes代码中使用--L变量:
line {
animation-name: line-grow;
animation-duration: 3s;
animation-iteration-count: infinite;
}
@keyframes line-grow {
from {
stroke-dasharray: 0 var(--L);
}
to {
stroke-dasharray: var(--L) var(--L);
}
}
解决方案 #2:
如果不能或不想预先计算每个笔划的路径长度,下面是一个使用简短的 javascript 代码即时完成工作的解决方案。
CSS:
@keyframes line-grow {
from {
stroke-dasharray: 0 var(--L);
}
to {
stroke-dasharray: var(--L) var(--L);
}
}
svg:
<svg width="1000px" height="100px">
<g stroke="#FAB" stroke-width="3">
<line id="Line1" x1="20" y1="20" x2="520" y2="20"/>
<line id="Line2" x1="20" y1="50" x2="780" y2="50"/>
</g>
</svg>
javascript:
function magic()
{
var list, k, style;
list = document.querySelectorAll("line");
for (k=0; k<list.length; k++)
{
style = "--L:" + list[k].getTotalLength() + ";";
style += "animation: line-grow 3s infinite;";
list[k].setAttribute("style", style);
}
}
window.addEventListener("load", magic, false);
解决方案 #3:
作为记录,下面是一个类似于 Cigany 解决方案的以前的解决方案,但使用getTotalLength() 方法来计算线长度(因此,可以轻松计算任何类型路径的长度,包括包含 Bézier 的路径曲线)。
只需在页面末尾添加一个脚本 (javascript) 即可处理每一行:
- 使用
getTotalLength()计算它的长度
- 使用此长度添加关键帧
- 相应地更改其动画名称
- 修改其
pathLength 属性(让知道如何使用该属性的浏览器正常工作)
代码可能是:
function setKeyframes(name, len)
{
// add a specific keyframes for each line using its length
// to the style of the page
var a, e = document.createElement("style");
a = "@keyframes " + name + " {";
a += "from {stroke-dasharray: 0, " + len + ";}";
a += "to {stroke-dasharray: " + len + ", " + len + ";}";
a += "}";
e.type = 'text/css';
if (e.styleSheet) e.styleSheet.cssText = a;
else e.appendChild(document.createTextNode(a));
document.getElementsByTagName('head')[0].appendChild(e);
}
function magic()
{
// does the job for each line
var list, k, name, len;
// adapt the following instruction
// if all the lines of the document are not concerned
list = document.querySelectorAll("line");
for (k=0; k<list.length; k++)
{
name = "line-grow-" + k;
len = list[k].getTotalLength();
setKeyframes(name, len);
list[k].style.animationName = name;
list[k].setAttribute("pathLength", len);
}
}
window.addEventListener("load", magic, false);