如何使用JavaScript创建SVG图形?
是否所有浏览器都支持SVG?
发布于 2009-06-23 19:40:46
看看this list on Wikipedia,了解哪些浏览器支持SVG。它还在脚注中提供了更多详细信息的链接。例如,Firefox支持基本的SVG,但目前缺乏大多数动画功能。
有关如何使用Javascript创建SVG对象的教程可在here中找到
var svgns = "http://www.w3.org/2000/svg";
var svgDocument = evt.target.ownerDocument;
var shape = svgDocument.createElementNS(svgns, "circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r", 20);
shape.setAttributeNS(null, "fill", "green");
发布于 2009-06-26 17:54:59
这个答案来自2009年。现在是一个社区维基,如果有人愿意更新它的话。
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
属性用于normal值,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);
发布于 2009-06-24 19:06:43
要实现跨浏览器,我强烈推荐使用RaphaelJS。它有一个很好的API,并且在IE中做VML,不能理解SVG。
https://stackoverflow.com/questions/1034712
复制相似问题