[英]Populate object tag with SVG code with javascript
我確實有可用的svg代碼作為javascript變量中的文本。 我需要將其設置為對象標簽(不是SVG或IMG)中的圖像。 這可能嗎?
沒有任何響應的“ 使用緩存的SVG代碼創建SVG對象”標簽中對此進行了討論。
有幾種方法可以做到這一點,但它們並不能全部允許您訪問對象的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); } };
<object id="obj"></object>
在大多數瀏覽器中規避此問題的一種方法是使用blobURI,該地址應標有文檔的來源,從而使我們能夠訪問該文檔。 但是IE不會在blobURIs上設置此來源...因此,該瀏覽器也將不允許您訪問contentDocument。
以下代碼段將在所有瀏覽器中充當IE,因為StackSnippets iframe的來源是null:
// 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); } };
<object id="obj"></object>
但是這個小提琴將在除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);
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.