使用javascript

时间:2017-11-12 01:11:40

标签: javascript svg dynamically-generated object-tag

我确实在javascript中的变量中有svg代码作为文本。我需要将它设置为对象标签(不是SVG或IMG)中的图像。这可能吗?

Create SVG Object tag with Cached SVG code对此进行了讨论,没有任何回应。

1 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点,但它们不会都允许您访问对象的contentDocument ...

最简单的方法是将SVG标记转换为数据URI。

但是浏览器会将此文档视为跨源资源,然后禁止您通过js访问它。



// an svg string
const svgStr = `<svg width="120" height="120" viewBox="0 0 120 120"
    xmlns="http://www.w3.org/2000/svg">

  <rect x="10" y="10" width="100" height="100"/>
</svg>`;
// as dataURI
const dataURI = 'data:image/svg+xml;charset=utf8, '+ encodeURIComponent(svgStr);
obj.data = dataURI;

// do some checks after it has loaded
obj.onload = e => {
  console.log('loaded');
  try{  
    console.log(obj.contentDocument.documentElement.nodeName);
    }
  catch(err){
    console.log('but cant access the document...');
    console.error(err);
  }
};
&#13;
<object id="obj"></object>
&#13;
&#13;
&#13;

在大多数浏览器中避免这种情况的一种方法是使用blobURI,标记文档的来源,从而允许我们访问文档。 但IE,并没有在blobURI上设置这个来源......所以这个浏览器也不允许你访问contentDocument。

以下代码段将在所有浏览器中充当IE,因为StackSnippets iframe是空的:

&#13;
&#13;
// an svg string
const svgStr = `<svg width="120" height="120" viewBox="0 0 120 120"
    xmlns="http://www.w3.org/2000/svg">

  <rect x="10" y="10" width="100" height="100"/>
</svg>`;

// as blobURI
const blob = new Blob([svgStr], {type:'image/svg+xml'})
const blobURI = URL.createObjectURL(blob);
obj.data = blobURI;

// do some checks after it has loaded
obj.onload = e => {
  console.log('loaded');
  try{  
    console.log(obj.contentDocument.documentElement.nodeName);
    }
  catch(err){
    console.log('but cant access the document...');
    console.error(err);
  }
};
&#13;
<object id="obj"></object>
&#13;
&#13;
&#13;

this fiddle可以在除IE浏览器之外的所有浏览器中使用。

因此,对IE也适用的一种方法是使用一个空的HTML文档,从同一个源提供,我们会在加载后附加svg。

// first load an same-origin document (not sure if about:blank works in IE...)
obj.data = 'empty.html';

// once it has loaded
obj.onload = e => {
  // parse our svgString to a DOM element
  const svgDoc = new DOMParser().parseFromString(svgStr, 'image/svg+xml');
  const objDoc = obj.contentDocument;
  // ask the object's document to adopt the svg node
  const toAppend = objDoc.adoptNode(svgDoc.documentElement);
  // now we can append it and it will display
  objDoc.documentElement.appendChild(toAppend);
};

As a fiddle.