你好
我正在使用此代码创建 SVG 线,然后对其进行动画处理,第一个代码不起作用,但其余所有代码都可以,我缺少什么?
var newElement = document.createElementNS('http://www.w3.org/2000/svg','line');
newElement.setAttribute('class','travelPath');
newElement.setAttribute('x1',currentCity.x);
newElement.setAttribute('y1',currentCity.y);
newElement.setAttribute('x2',nextCity.x+10);
newElement.setAttribute('y2',nextCity.y+10);
newElement.style.stroke="#3541b1";
$("#theSVG").append(newElement);
var length = newElement.getTotalLength();
$(newElement).css({
'stroke-dasharray': length+1,
'stroke-dashoffset': length+1
});
$(newElement).animate({'stroke-dashoffset': 0}, 3000, mina.bounce);
length 变量在第一个 console.log 上返回为 0,但是当我稍后再次运行它时,它会返回正确的值,并显示动画。
几乎就像在尝试制作动画之前尚未绘制线条一样。
最佳答案
根据我对“line”元素的理解,getTotalLength 并没有得到很好的支持。
您可以将其转换为路径。例如...
var newElement = document.createElementNS('http://www.w3.org/2000/svg','path');
newElement.setAttribute('class','travelPath');
newElement.setAttribute('d', "M50,50L100,100")
newElement.style.stroke="#3541b1";
$("#theSVG").append(newElement);
var length = newElement.getTotalLength();
console.log( length )
看看这是否有帮助。
关于javascript - 在 JavaScript 中对 SVG 线条进行动画处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43046154/