在JavaScript中引用SVG文件到SVG对象

Reference SVG file to SVG object in JavaScript

本文关键字:SVG 文件 对象 引用 JavaScript      更新时间:2023-09-26

我的问题是如何使用javascript创建的SVG对象引用SVG文件?到目前为止,我所做的似乎都不起作用

  var svg = document.getElementById("svg");
	  svg.setAttribute('width', '2048');
	  svg.setAttribute('height', '784'); 
  var background = document.createElementNS("http://www.w3.org/2000/svg", "svg");
	  background.setAttribute('width', '2048');
	  background.setAttribute('height', '784');
	  background.setAttributeNS('http://www.w3.org/1999/xlink', 'href', 'myimg.svg');
	  background.setAttribute('x', '0');
	  background.setAttribute('y', '0');	
svg.appendChild(background);	
svg
{
	border-style: solid;
    border-width: 5px;
}
<body>
	<svg id="svg"></svg>		
</body>

看一下这段代码

var svgDocument, svg;
var obj=document.createElement('object');
obj.addEventListener('load', function(e) {
    svgDocument = this.contentDocument;
    svg = svgDocument.querySelector('svg');
});
obj.data = 'myimg.svg';
document.body.appendChild(obj);

创建一个包含svg文件数据集的object。加载后,可以获得"根"元素(SVG元素),如图

所示。

注意:你不能访问contentDocument,直到svg已经加载。