使用javascript以编程方式创建SVG图像元素 [英] Programmatically creating an SVG image element with javascript
问题描述
就像我的标题所说,我正在尝试使用javascript以编程方式在HTML页面中创建SVG图像元素。由于某些原因,我的基本javascript代码无法正常工作,但是如果我使用raphaeljs库它可以正常工作。所以我的js显然有问题 - 我似乎无法弄清楚它是什么。
Like my title says, I'm trying to programmatically creating an SVG image element in a HTML page using javascript. For some reason my basic javascript code isn't working, however if I use the raphaeljs library it works fine. So there's obviously a problem with my js - I just can't seem to figure out what it is.
(注意:目标浏览器是FF4 +)
(note: the target browser is FF4+)
这是一个基本页面,其中包含我想要达到顶部的html版本:
Here is the basic page with an html version of what I'm trying to achieve up the top:
<html>
<head>
<script type="text/javascript" src="http://raphaeljs.com/raphael.js"></script>
</head>
<body>
<svg
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
id="test1"
height="200px"
width="200px">
<image
id="testimg1"
xlink:href="http://i.imgur.com/LQIsf.jpg"
width="100"
height="100"
x="0"
y="0"/>
</svg>
<hr />
<p id="testP1">
</p>
<hr />
<p id="testP2">
</p>
</body>
</html>
这是我的javascript:
And here is my javascript:
var paper = Raphael(document.getElementById("testP1"), 200, 200);
paper.image("http://i.imgur.com/LQIsf.jpg", 0,0, 100, 100);
var svg = document.createElementNS('http://www.w3.org/2000/svg','svg');
svg.setAttributeNS('http://www.w3.org/2000/svg','xlink','http://www.w3.org/1999/xlink');
svg.setAttributeNS('http://www.w3.org/2000/svg','height','200');
svg.setAttributeNS('http://www.w3.org/2000/svg','width','200');
svg.setAttributeNS('http://www.w3.org/2000/svg','id','test2');
var svgimg = document.createElementNS('http://www.w3.org/2000/svg','image');
svgimg.setAttributeNS('http://www.w3.org/2000/svg','height','100');
svgimg.setAttributeNS('http://www.w3.org/2000/svg','width','100');
svgimg.setAttributeNS('http://www.w3.org/2000/svg','id','testimg2');
svgimg.setAttributeNS('http://www.w3.org/1999/xlink','href','http://i.imgur.com/LQIsf.jpg');
svgimg.setAttributeNS('http://www.w3.org/2000/svg','x','0');
svgimg.setAttributeNS('http://www.w3.org/2000/svg','y','0');
svg.appendChild(svgimg);
document.querySelector('#testP2').appendChild(svg);
实例: http://jsfiddle.net/Yansky/UVFBj/5/
推荐答案
SVG本机属性(不包括 xlink:href
)不共享SVG名称空间;您可以使用 setAttribute
而不是 setAttributeNS
,或使用
SVG native attributes (not including xlink:href
) do not share the SVG namespace; you can either use just setAttribute
instead of setAttributeNS
, or use
svgimg.setAttributeNS(null,'x','0');
例如。
这是,工作: http://jsfiddle.net/UVFBj/8/
请注意,我改变了你的小提琴以正确使用XHTML,因此SVG可以在所有主流浏览器中很好地运行。
Note that I changed your fiddle to properly use XHTML, so that SVG works nicely within it in all major browsers.
这篇关于使用javascript以编程方式创建SVG图像元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!