2016-11-08 72 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