簡體   English   中英

用SVG畫圓

[英]draw circle with SVG

我想用SVG畫一個圓。 圓的中心位於數組中。 arr [i] [0] .x是x中心,arr [i] [0] .y是y中心,arr [i] [0] .r是半徑。

我這樣嘗試過

svg.appendChild(circle);
        circle.cx.appendItem(arr[i][0].x);
        circle.cy.appendItem(arr[i][0].y);
        circle.r.appendItem(arr[i][0].r);

但這不起作用。 我該如何解決?

使用setAttribute設置圓值。

 var circle = document.getElementById("circle")
        circle.setAttribute("cx", 60);
        circle.setAttribute("cy", 70);
        circle.setAttribute("r", 5);
 var svg = document.getElementById("svg1")
 svg.appendChild(circle);

假設要創建一個圓,則必須使用createElementNS創建/繪制svg對象,並且還必須使用setAttribute

var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle");
// it does not matter whether appendChild is put before or after setAttribute
svg.appendChild(circle);

circle.setAttribute("cx",100);
circle.setAttribute("cy",100);
circle.setAttribute("r",80);

希望能幫助到你。

這也是可行的例子。

 var svgn = "http://www.w3.org/2000/svg"; var svg = document.getElementById('svg'); var circle = document.createElementNS(svgn, "circle"); circle.setAttributeNS(null, "cx", 25); circle.setAttributeNS(null, "cy", 25); circle.setAttributeNS(null, "r", 20); svg.appendChild(circle); 
 <svg id="svg"></svg> 

SVG DOM有點冗長,但是如果您想使用element.property.baseVal.value,則可以直接設置值,如下所示。 您可以插入數組值而不是我使用的硬編碼數字。

 var svg = document.getElementById('svg'); var circle = document.createElementNS("http://www.w3.org/2000/svg", "circle"); circle.cx.baseVal.value = 25; circle.cy.baseVal.value = 25; circle.r.baseVal.value = 20; svg.appendChild(circle); 
 <svg id="svg"></svg> 

暫無
暫無

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

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