簡體   English   中英

使用DOM將SVG元素添加到現有SVG中

[英]Add SVG element to existing SVG using DOM

我有一個類似於以下代碼的HTML構造:

<div id='intro'>
<svg>
//draw some svg elements
<svg>
</div>

我希望能夠使用javascript和DOM向上面定義的SVG中添加一些元素。 我該怎么做? 我在想

var svg1=document.getElementById('intro').getElementsByTagName('svg');
svg1[0].appendChild(element);//element like <line>, <circle>

我對使用DOM或如何創建要傳遞給appendChild的元素不是很熟悉,因此請幫助我解決這個問題,或者向我展示解決該問題的其他替代方法。 非常感謝。

如果要創建HTML元素,請使用document.createElement函數。 SVG使用名稱空間,這就是為什么必須使用document.createElementNS函數的原因。

var svg = document.getElementsByTagName('svg')[0]; //Get svg element
var newElement = document.createElementNS("http://www.w3.org/2000/svg", 'path'); //Create a path in SVG's namespace
newElement.setAttribute("d","M 0 0 L 10 10"); //Set path's data
newElement.style.stroke = "#000"; //Set stroke colour
newElement.style.strokeWidth = "5px"; //Set stroke width
svg.appendChild(newElement);

這段代碼將產生如下內容:

<svg>
 <path d="M 0 0 L 10 10" style="stroke: #000; stroke-width: 5px;" />
</svg>



createElementhttps : //developer.mozilla.org/zh-CN/docs/Web/API/Document/createElement

createElementNShttps : //developer.mozilla.org/zh-CN/docs/Web/API/Document/createElementNS

如果您使用JS處理大量SVG,建議您使用d3.js。 將其包含在您的頁面上,然后執行以下操作:

d3.select("#svg1").append("circle");

暫無
暫無

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

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