如何使用JavaScript创建SVG图形?
所有浏览器都支持SVG吗?
如何使用JavaScript创建SVG图形?
所有浏览器都支持SVG吗?
可以查看维基百科上的此列表,了解哪些浏览器支持SVG。它还提供了有关注释中更多详细信息的链接。例如,Firefox支持基本的SVG,但目前缺少大多数动画功能。
有关如何使用Javascript创建SVG对象的教程可以在这里找到:
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");
evt
。请参考 themadmax 的答案,那是一个可行的解决方案。 - AldaronLauIE需要插件才能显示SVG。最常见的是Adobe提供的可下载插件;但是,Adobe不再支持或开发它。 Firefox、Opera、Chrome、Safari都可以很好地显示基本的SVG,但如果使用了高级功能,则可能会遇到问题,因为支持不完整。 Firefox不支持声明式动画。
可以使用JavaScript创建SVG元素,如下所示:
// "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规范描述了所有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);
除IE外,所有现代浏览器都支持SVG。
以下是提供逐步指南的教程,介绍如何使用javascript处理SVG:
正如Boldewyn已经说过的,如果你想要
跨浏览器实现,我强烈推荐RaphaelJS:rapaheljs.com
尽管现在我觉得这个库的大小太大了。它有很多很棒的功能,其中一些您可能不需要。
var svgns = "http://www.w3.org/2000/svg";
var svg = document.getElementById('svg');
var shape = document.createElementNS(svgns, "circle");
shape.setAttributeNS(null, "cx", 25);
shape.setAttributeNS(null, "cy", 25);
shape.setAttributeNS(null, "r", 20);
shape.setAttributeNS(null, "fill", "green");
svg.appendChild(shape);
<svg id="svg" width="100" height="100"></svg>
有多个使用Javascript的SVG图形库,例如:Snap、Raphael、D3。或者您可以直接使用纯Javascript与SVG进行交互。
目前所有最新版本的浏览器都支持SVG v1.1。SVG v2.0仍处于草案阶段,尚不宜使用。
本文介绍如何使用Javascript与SVG交互,并提供了有关浏览器支持的链接参考。与SVG交互
http://srufaculty.sru.edu/david.dailey/svg/SVGAnimations.htm
http://plugins.jquery.com/project/svg
从其介绍中:在Firefox、Opera和Safari中本地支持,通过Adobe SVG查看器或Renesis播放器在IE中支持,SVG让您可以在网页内显示图形。现在,您可以轻松地通过JavaScript代码驱动SVG画布。