【发布时间】:2015-09-23 12:04:24
【问题描述】:
我有一个需要旋转元素的 SVG 动画。基于 SMIL 和 css 的动画是不可能的,因为 IE 不支持它们,并且 IE 或 Firefox 也不支持 beginElement() 属性。 IE 大小不是问题,因为 CSS 很好地解决了这个问题。
问题在于它不是标准形状(矩形、圆形等),因此 svg 动画属性以惊人的方式失败,因为默认情况下没有中心点 - getBBox() 是首选方法。
我有一个plunk,其中包含 html 中的 svg 示例。为了便于移植,脚本必须在 svg 中,我已经让它在 Chrome、Firefox 和 Opera 中工作,但 IE 无法旋转元素,尽管没有显示错误。 JS如下:
var svgNS = "http://www.w3.org/2000/svg";
function init(evt) {
addRotateTransform('spinner', 1.5, 1);
}
function addRotateTransform(target_id, dur, dir) {
var my_element = document.getElementById(target_id);
var a = document.createElementNS(svgNS, "animateTransform");
var bb = my_element.getBBox();
var cx = bb.x + bb.width/2;
var cy = bb.y + bb.height/2;
a.setAttributeNS(null, "attributeName", "transform");
a.setAttributeNS(null, "attributeType", "XML");
a.setAttributeNS(null, "type", "rotate");
a.setAttributeNS(null, "dur", dur + "s");
a.setAttributeNS(null, "repeatCount", "indefinite");
a.setAttributeNS(null, "from", "0 "+cx+" "+cy);
a.setAttributeNS(null, "to", 360*dir+" "+cx+" "+cy);
my_element.appendChild(a);
try {
a.beginElement(); // this works in Chrome
}
catch(err) {
window.setTimeout(init, 0); // this works in FF
}
}
【问题讨论】:
-
IE 不支持 SMIL。你可以试试 fakeSmile (leunen.me/fakesmile)
-
谢谢罗伯特,在这里使用另一个库将无济于事,因为它需要是一个封装的 thingemebob,而 fakeSmile 似乎(还)不支持旋转。
-
您需要使用纯 javascript 并操作 DOM。
-
这就是我提出上述问题的原因。我一直找不到合适的解决方案 - 或者至少不知道正确的问题,所以 plunk 是我最喜欢的方法,因为它在 IE 中查看时会将其置于上下文中。
标签: javascript internet-explorer animation svg