【发布时间】:2014-05-30 03:30:58
【问题描述】:
希望为下面的 SVG 设置动画,我最初已经开始使用它。但是,我希望它用我定义的点以相反的方向“绘制”第二个 SVG。
有什么办法可以做到吗?用点从左到右有效地绘制我的形状。
Codepen:http://codepen.io/anon/pen/gFcAz
【问题讨论】:
标签: css svg css-animations
希望为下面的 SVG 设置动画,我最初已经开始使用它。但是,我希望它用我定义的点以相反的方向“绘制”第二个 SVG。
有什么办法可以做到吗?用点从左到右有效地绘制我的形状。
Codepen:http://codepen.io/anon/pen/gFcAz
【问题讨论】:
标签: css svg css-animations
正常的虚线偏移动画技巧实际上只适用于实线。
这是我使用 CSS 动画获得的最接近的效果。
不幸的是,破折号会爬行,因为您无法控制 stroke-dashoffset 的步长。如果你一次可以让它一步步走 10 步,那么破折号就不会移动了。
所以我认为解决它的唯一方法是使用 Javascript。
var path = document.querySelectorAll("svg path").item(0);
animateDashedPath(path);
/*
* Animates the given path element.
* Assumes the path has a "5 5" dash array.
*/
function animateDashedPath(path)
{
var pathLength = path.getTotalLength();
var animationDuration = 2000;
var numSteps = Math.round(pathLength / (5+5) + 1);
var stepDuration = animationDuration / numSteps;
// Build the dash array so we don't have to do it manually
var dasharray = [];
while (numSteps-- > 0) {
dasharray.push(5);
dasharray.push(5);
}
dasharray.push(pathLength);
// Animation start conditions
path.setAttribute("stroke-dasharray", dasharray.join(" "));
path.setAttribute("stroke-dashoffset", -pathLength);
// We use an interval timer to do each step of the animation
var interval = setInterval(dashanim, stepDuration);
function dashanim() {
pathLength -= (5+5);
path.setAttribute("stroke-dashoffset", -pathLength);
if (pathLength <= 0) {
clearInterval(interval);
}
}
}
更新
在 FF 中似乎存在问题。如果您为路径长度创建“正确”数量的破折号,它不会完全到达路径的末端。您需要添加额外的。
【讨论】: