2016-11-08 22 views
1

是否有任何函數或方法在應用轉換後獲取SVG多邊形中的更新點?我在JavaScript中進行轉換,我注意到轉換後點數仍然相同。轉換後獲取更新的多邊形點(SVG)

function drawPolygon(){ 

    var points = "100,100 200,100 200,200 100,200"; 
    var polygon = document.createElementNS(svgURL, "polygon"); 
    polygon.setAttribute("style", "fill: gray; stroke: black; stroke-width: 1; cursor: pointer;"); 

    polygon.setAttribute("points", points); 

    mySVG.appendChild(polygon); 

    console.log(polygon.points); 
    // Points: 100,100 200,100 200,200 100,200 

    polygon.setAttribute("transform", "translate(200,0)"); 

    console.log(polygon.points); 
    //Points: 100,100 200,100 200,200 100,200 
} 

我該如何得到更新的點如:300,100,400,100 400,200 300,200或者獲得更新點的另一個多邊形?

編輯:弗朗西斯Hemsher第一個答案是工作好,如果我們沒有視框,現在我有一個問題,我在我的SVG視框:

<svg id="my_svg" version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/svg" width="300px" height="300px" viewBox="-150 -150 300 300" style="background-color: lightblue"> 

</svg> 

function drawRoom(){ 

    var points = "-100,0 100,0 100,100 -100,100"; 

    var polygon = document.createElementNS(svgURL, "polygon"); 
    polygon.setAttribute("style", "fill: gray; stroke: black; stroke-width: 1; cursor: pointer;"); 

    polygon.setAttribute("points", points); 

    mySVG.appendChild(polygon); 

    //Points: "-100,0 100,0 100,100 -100,100"; 
    polygon.setAttribute("transform", "translate(0,-50)"); 

    screenPolygon(polygon); 

    //Points should be: "-100,-50 100,-50 100,50 -100,50" if I apply function provided by Francis 

    //But points are: "50, 100 250,100 250,200 50,200" 

} 

polygon after transformation

polygon after apply function screenPolygon(myPoly)

請你知道我怎樣才能得到像圖1那樣的更新點,我知道viewbox有事情要做。由於

回答

1

嘗試以下操作:

function screenPolygon(myPoly) 
 
{ 
 
\t var sCTM = myPoly.getCTM() 
 
\t var svgRoot = myPoly.ownerSVGElement 
 

 
\t var pointsList = myPoly.points; 
 
\t var n = pointsList.numberOfItems; 
 
\t for(var m=0;m<n;m++) 
 
\t { 
 
\t \t var mySVGPoint = svgRoot.createSVGPoint(); 
 
\t \t mySVGPoint.x = pointsList.getItem(m).x 
 
\t \t mySVGPoint.y = pointsList.getItem(m).y 
 
\t \t mySVGPointTrans = mySVGPoint.matrixTransform(sCTM) 
 
\t \t pointsList.getItem(m).x=mySVGPointTrans.x 
 
\t \t pointsList.getItem(m).y=mySVGPointTrans.y 
 
\t } 
 
\t //---force removal of transform-- 
 
\t myPoly.setAttribute("transform","") 
 
\t myPoly.removeAttribute("transform") 
 
}

+0

什麼的呼叫的setAttribute前夕點的removeAttribute來?此外,我認爲你現在可以迭代「for(var item of myPoly.points)」。 –

+0

@RobertLongson僅供參考,早期版本的IE不會僅使用removeAttribute刪除轉換,但由於某種原因,它必須在刪除之前爲空。 –

+0

謝謝@FrancisHemsher,正是我所需要的。 – insurg3nt3