这个答案来自 2009 年。现在是一个社区 wiki,以防有人愿意更新它。
IE 需要一个插件来显示 SVG。最常见的是可供 Adobe 下载的版本。但是,Adobe 不再支持或开发它。 Firefox、Opera、Chrome、Safari 都可以正常显示基本的 SVG,但如果使用高级功能则会遇到问题,因为支持不完整。 Firefox 不支持声明式动画。
SVG 元素可以用 javascript 创建如下:
// "circle" may be any tag name
var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
// Set any attributes as desired
shape.setAttribute("cx", 25);
shape.setAttribute("cy", 25);
shape.setAttribute("r", 20);
shape.setAttribute("fill", "green");
// Add to a parent node; document.documentElement should be the root svg element.
// Acquiring a parent element with document.getElementById() would be safest.
document.documentElement.appendChild(shape);
SVG specification 描述了所有 SVG 元素的 DOM 接口。比如上面创建的SVGCircleElement,中心点和半径都有cx、cy、r属性,可以直接访问。这些是 SVGAnimatedLength 属性,它们有一个baseVal 属性用于正常值,animVal 属性用于动画值。目前的浏览器不可靠地支持animVal 属性。 baseVal 是一个 SVGLength,其值由 value 属性设置。
因此,对于脚本动画,也可以设置这些 DOM 属性来控制 SVG。下面的代码应该和上面的代码是等价的:
var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
shape.cx.baseVal.value = 25;
shape.cy.baseVal.value = 25;
shape.r.baseVal.value = 20;
shape.setAttribute("fill", "green");
document.documentElement.appendChild(shape);