insurg3nt3 insurg3nt3 - 26 days ago 11
Javascript Question

Get updated polygon points after transformations (SVG)

Is there any function or method to get updated points in a SVG polygon after applying transformations? I'm doing transformations in JavaScript and I noticed points still the same after transformations.

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
}


How can I get updated points like: 300, 100, 400, 100 400, 200 300, 200 or get another polygon with updated points?

Edited: The first answer from Francis Hemsher is working well if we don't have a viewbox, now I'm having a problem, I have a viewbox in my 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)

Please do you know how can I get updated points like in figure 1, I know the viewbox have something to do. Thanks

Answer

Try the following:

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

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