[英]Embed an svg file in svg document, access it's objects via JavaScript
I am looking for a way how to load the svg content from external file, in a placeholder element, and when it's loaded, access it's objects for manipulation/modifictation. 我正在寻找一种方法,如何在占位符元素中从外部文件加载svg内容,并在加载时访问其对象以进行操作/修改。
Something like this: 像这样:
Host file:
<body>
<svg width="700" height="500">
<rect x="10" y="10" height="480" width="680" fill="red"/>
<g id="placeholder"></g>
</svg>
</body>
drawing.svg file:
<svg>
<circle id="obj1" cx="300" y="250" r="100" fill="blue"/>
</svg>
And here's some pseudo-code: 这是一些伪代码:
var placeholder = document.getElementById("placeholder");
loadSVGFile("drawing.svg", placeholder, function(svg) {
// Callback called when the file has loaded
var obj = svg.document.getElementById("obj1");
obj.setAttribute("fill", "black");
});
Currently I am creating in memory a new <object>
element, load the svg file, hook up an onload event handler that copies the document content to the target placeholder element with recursive node crawler. 当前,我正在内存中创建一个新的<object>
元素,加载svg文件,连接一个onload事件处理程序,该事件处理程序使用递归节点搜寻器将文档内容复制到目标占位符元素。 Not pretty, but it works. 不漂亮,但是有效。 I am hoping there's a better way. 我希望有更好的方法。
Something like the following should work. 像下面这样的东西应该起作用。 I haven't properly tested it. 我没有正确测试。 But it is a cut-down version of some other code, so it should at least be very close. 但这是其他一些代码的精简版,因此至少应该非常接近。
function loadSVGFile(svgURL, placeholderElem, callbackFn) { var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState == 4 && xhr.status == 200) { var svg = xhr.responseXML.getElementsByTagName('svg')[0]; placeholderElem.parentElement.replaceChild(svg, placeholderElem); // Replace the placeholder node //targetNode.appendChild(svg); // Insert into the placeholder node if (callbackFn) { callbackFn(svg); } } } xhr.open('GET', svgURL, true); xhr.send(null); } var placeholder = document.getElementById("placeholder"); loadSVGFile("drawing.svg", placeholder, function(svg) { // Callback called when the file has loaded var obj = svg.ownerDocument.getElementById("obj1"); obj.setAttribute("fill", "black"); });
<body> <svg width="700" height="500"> <rect x="10" y="10" height="480" width="680" fill="red"/> <g id="placeholder"></g> </svg> </body>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.