2013-07-09 44 views
2

我需要動態地在svg中添加圓圈。這裏它正確地添加到svg中,但不在正確的位置。 在這裏,我創建了svg中的圓,並通過單擊svg來添加新的圓來獲取x和y的位置。它從屏幕上正確地獲取clientX和clientY的位置,但新添加的圓不能正確添加到正確的位置。我需要在所選位置上的svg上添加新的圓圈。未正確添加正確的位置svg與圓框的圓?

這裏是DEMO.

var xpos, ypos; 
$("svg").click(function (e) { 
    xpos = e.clientX; 
    ypos = e.clientY; 
    alert(xpos+' '+ypos); 
}); 

$("#create").click(function (e) { 
    var svgNS = "http://www.w3.org/2000/svg"; 
    var myCircle = document.createElementNS(svgNS, "circle"); 
    myCircle.setAttributeNS(null, "id", "mycircle"); 
    myCircle.setAttributeNS(null, "fill", 'blue'); 
    myCircle.setAttributeNS(null, "cx", xpos); 
    myCircle.setAttributeNS(null, "cy", ypos); 
    myCircle.setAttributeNS(null, "r", '6'); 
    myCircle.setAttributeNS(null, "stroke", "none"); 
    var svg = document.querySelector("svg"); 
    svg.appendChild(myCircle); 
}); 

任何建議應當理解。

回答

1

這樣的事情應該這樣做。

$("#create").click(function (e) { 
    var svgNS = "http://www.w3.org/2000/svg"; 
    var myCircle = document.createElementNS(svgNS, "circle"); 
    myCircle.setAttributeNS(null, "id", "mycircle"); 
    myCircle.setAttributeNS(null, "fill", 'blue'); 
    myCircle.setAttributeNS(null, "r", '6'); 
    myCircle.setAttributeNS(null, "stroke", "none"); 
    var svg = document.querySelector("svg"); 
    svg.appendChild(myCircle); 
    var pt = svg.createSVGPoint(); 
    pt.x = xpos; 
    pt.y = ypos; 
    var globalPoint = pt.matrixTransform(myCircle.getScreenCTM().inverse()); 
    var globalToLocal = myCircle.getTransformToElement(svg).inverse(); 
    var inObjectSpace = globalPoint.matrixTransform(globalToLocal); 
    myCircle.setAttributeNS(null, "cx", inObjectSpace.x); 
    myCircle.setAttributeNS(null, "cy", inObjectSpace.y); 
}); 

這個question有更多的細節。儘管其解決方案並不完全正確。

+0

非常感謝你剛剛偉大.... – karthik

+0

一個疑問,我怎樣才能使用它在打字稿? – karthik

1

問題是由兩兩件事來:

  1. e.clientXe.clientY在頁面的位置。因此,不完全相關的svg內部。爲了提供有價值的信息,我們使用jQuery offset。這使在像素以下的座標:

    var offset = $(this).offset(); 
    xpos = e.clientX - offset.left; 
    ypos = e.clientY - offset.top; 
    
  2. 另一個問題來自於路視和SVG定位interract。事實是,在您的設置中,我們有一個200px*200px的框,其中左上角的座標爲0,-100,右下角爲400,300。

    爲了解決您的問題,我使用的解決方案如下:在背景中添加一個白色矩形(這樣svg就可以有效地使用我們提供的所有空間)。並使用輕微的翻譯調整到SVG協調,這是

    xpos = (e.clientX - offset.left)*2; 
    ypos = (e.clientY - offset.top)*2 - 100; 
    

請參閱更新的小提琴here