簡體   English   中英

通過javascript創建SVG元素

[英]Create SVG element via javascript

我只需要使用javascript創建這個結構:

<svg>
    <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#circle"></use>
</svg>

但是我在創建xmlns:xlink屬性時遇到了麻煩。 這是我的js代碼:

var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
var use = document.createElementNS('http://www.w3.org/2000/svg', 'use');
// throws error here
use.setAttributeNS('http://www.w3.org/2000/xmlns', 'xmlns:xlink', 'http://www.w3.org/1999/xlink');
use.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', '#circle');
svg.appendChild(use);

如果我用設置xmlns:xlink注釋字符串一切正常,並使svg與上面相同,但沒有xmlns:xlink

我看到很多類似於我的問題,但他們沒有解決我的問題。

關於

use.setAttributeNS('http://www.w3.org/2000/xmlns', 'xmlns:xlink', 'http://www.w3.org/1999/xlink');

你不需要那條線,實際上它是無效的。

如果您在XML文檔中創建元素/屬性,則在使用createElementNS創建元素時會自動設置xmlns:xlink屬性;如果您在html文檔中創建元素,則不需要xmlns:xlink屬性。

開始了:

// "circle" may be any tag name
var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");

// Set any attributes as desired
shape.setAttribute("cx", 25);
shape.setAttribute("cy", 25);
shape.setAttribute("r",  20);
shape.setAttribute("fill", "green");

// Add to a parent node; document.documentElement should be the root svg element.
// Acquiring a parent element with document.getElementById() would be safest.
document.documentElement.appendChild(shape);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM