首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用Javascript创建SVG图形?

使用Javascript创建SVG图形?
EN

Stack Overflow用户
提问于 2009-06-23 19:37:05
回答 10查看 116.9K关注 0票数 82

如何使用JavaScript创建SVG图形?

是否所有浏览器都支持SVG?

EN

回答 10

Stack Overflow用户

发布于 2009-06-23 19:40:46

看看this list on Wikipedia,了解哪些浏览器支持SVG。它还在脚注中提供了更多详细信息的链接。例如,Firefox支持基本的SVG,但目前缺乏大多数动画功能。

有关如何使用Javascript创建SVG对象的教程可在here中找到

代码语言:javascript
复制
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"); 
票数 31
EN

Stack Overflow用户

发布于 2009-06-26 17:54:59

这个答案来自2009年。现在是一个社区维基,如果有人愿意更新它的话。

IE需要一个插件来显示SVG。最常见的是可由Adobe下载的版本;但是,Adobe不再支持或开发它。Firefox、Opera、Chrome、Safari都可以很好地显示基本的SVG,但如果使用高级功能,则会出现问题,因为支持是不完整的。Firefox不支持声明式动画。

SVG元素可以使用javascript创建,如下所示:

代码语言: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具有中心点和半径的cxcyr属性,可以直接访问这些属性。这些是SVGAnimatedLength属性,其中baseVal属性用于normal值,animVal属性用于动画值。浏览器目前不能可靠地支持animVal属性。baseVal是一个SVGLength,它的值由value属性设置。

因此,对于脚本动画,还可以设置这些DOM属性来控制SVG。下面的代码应该等价于上面的代码:

代码语言:javascript
复制
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);
票数 23
EN

Stack Overflow用户

发布于 2009-06-24 19:06:43

要实现跨浏览器,我强烈推荐使用RaphaelJS。它有一个很好的API,并且在IE中做VML,不能理解SVG。

票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1034712

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档