You tagged svg.js so I assume that you are using it.
So here is how I would do it.
// assuming that you have a div with the id "canvas" here
var canvas = SVG('canvas')
var angle = 20
// draw polygon
var polygon = canvas.polygon([ [-18, 587.25], [-14, 197.25], [544, 169.25], [554, 551.25] ])
.fill('none')
.stroke('black')
// we clone it so we have something to compare
var clone = polygon.clone()
// get center of polygon
var box = polygon.bbox()
var {cx, cy} = box
// get the values of the points
var rotatedPoints = polygon.array().valueOf().map((p) => {
// transform every point
var {x, y} = new SVG.Point(p)
.transform(new SVG.Matrix().rotate(angle, cx, cy))
return [x, y]
})
// update polygon with points
polygon.plot(rotatedPoints)
Fiddle: https://jsfiddle.net/Fuzzy/3qzubk5y/1/
Ofc you dont need to make a polygon first to rotate the points. You can go straight withy our array and call the same map function on it. But in this case you need to figure out the cx and cy yourself:
function getCentroid(coord) {
var center = coord.reduce(function (x,y) {
return [x[0] + y[0]/coord.length, x[1] + y[1]/coord.length]
}, [0,0])
return center;
}
var canvas = SVG("canvas")
var points = [ [-18, 587.25], [-14, 197.25], [544, 169.25], [554, 551.25] ]
var center = getCentroid(points)
var angle = 20
// polygon before rotation
canvas.polygon(points).fill('none').stroke('black')
// get the values of the points
var rotatedPoints = points.map((p) => {
// transform every point
var {x, y} = new SVG.Point(p)
.transform(new SVG.Matrix().rotate(angle, center[0], center[1]))
return [x, y]
})
// polygon after rotation
canvas.polygon(rotatedPoints).fill('none').stroke('black')
Fiddle: https://jsfiddle.net/Fuzzy/g90w10gg/
So since your centroid function seems to work, your mistake has to be somewhere in your rotate function. However, I prefer to use the capcabilities of the libraries when I have them there. No need to reinvent the weel :)
// EDIT:
I pimped your centroid function a bit so the variable naming is a bit more clear:
function getCentroid(coord) {
var length = coord.length
var center = coord.reduce(function (last, current) {
last.x += current[0] / length
last.y += current[1] / length
return last
}, {x: 0, y: 0})
return center;
}