IE 和 Edge 似乎不支持 SMIL 或 CSS 转换;需要设置 transform 属性才能对平移/位置、旋转/方向或倾斜等产生影响。
奇怪的是,javascript 能够使用 CSS 计算应用的变换,包括使用关键帧或过渡效果的部分动画,即使它们没有在浏览器中呈现。考虑到这一点,您可以为您的线条提供某种形式的标识符,使用 css 对其进行动画处理,然后每 50 毫秒(约 20 帧/秒)手动应用一次变换属性。
<svg height="210" width="500">
<line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:2"></line>
<line id="line" x1="150" y1="150" x2="200" y2="200" style="stroke:rgb(0, 0, 153);stroke-width:2"></line>
</svg>
<style>
// Switch to CSS Animations
@-webkit-keyframes line-animate {
0% {
-webkit-transform: translate(200px, 200px);
transform: translate(200px, 200px);
}
50% {
-webkit-transform: translate(-150px, -150px);
transform: translate(-150px, -150px);
}
100% {
-webkit-transform: translate(200px, 200px);
transform: translate(200px, 200px);
}
}
@keyframes line-animate {
0% {
-webkit-transform: translate(200px, 200px);
transform: translate(200px, 200px);
}
50% {
-webkit-transform: translate(-150px, -150px);
transform: translate(-150px, -150px);
}
100% {
-webkit-transform: translate(200px, 200px);
transform: translate(200px, 200px);
}
}
#line {
-webkit-animation: line-animate 5s linear infinite;
animation: line-animate 5s linear infinite;
}
</style>
<script>
(function(){
var line = document.getElementById('line');
// Iterative function
line.animate = function() {
// Set the line transform attribute to match the calculated CSS transform value.
line.setAttribute('transform', getComputedStyle(line).getPropertyValue('transform'));
setTimeout(line.animate, 50);
};
line.animate();
})();
</script>
有关此方法的说明
- 正确读取 CSS 动画和转换的浏览器在设置转换属性时可能会导致复合问题,因此最好也为 IE 添加一些浏览器检测。无论如何,大多数浏览器在应用样式转换时都会忽略 transform 属性。
- 如果您要制作动画的 SVG 元素已经具有 transform 属性,那么您需要将所有点、距离和路径转换为转换后的值。
- 需要为使用加法的 SMIL 动画重新计算变换值。
- 可能需要对动画元素的数量进行限制,以防止出现浏览器性能问题,因为我预计
getComputedStyle 会占用大量资源。