Last active
June 20, 2024 16:05
-
-
Save Winner95/0cdf485bf45a04dbc6fd63afdc783621 to your computer and use it in GitHub Desktop.
JS-script for Adobe Photoshop 2017, that finds centroid of svg figures
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Get_Centroid_coordinates.jsx | |
A Javascript for Adobe Photoshop 2017. | |
Purpose: Find the centroid (center of gravity) of SVG path and point by guidelines. | |
Based on formula for finding Centroid of non-self-intersecting closed polygon | |
To Use: Select layer which includes normal path. Call the script. | |
Author: Ivan Grekov | |
*/ | |
// reset unites for proper navigation & sizes | |
app.preferences.rulerUnits = Units.PIXELS; | |
app.preferences.typeUnits = TypeUnits.PIXELS; | |
var doc = app.activeDocument; | |
var svgPaths = doc.pathItems; | |
function Point(x, y) { | |
this.x = x; | |
this.y = y; | |
} | |
function Region(points) { | |
this.points = points || []; | |
this.length = points.length; | |
} | |
Region.prototype.area = function () { | |
var area = 0, | |
i, | |
j, | |
point1, | |
point2; | |
for (i = 0, j = this.length - 1; i < this.length; j=i,i++) { | |
point1 = this.points[i]; | |
point2 = this.points[j]; | |
area += point1.x * point2.y; | |
area -= point1.y * point2.x; | |
} | |
area /= 2; | |
return area; | |
}; | |
Region.prototype.centroid = function () { | |
var x = 0, | |
y = 0, | |
i, | |
j, | |
f, | |
point1, | |
point2; | |
for (i = 0, j = this.length - 1; i < this.length; j=i,i++) { | |
point1 = this.points[i]; | |
point2 = this.points[j]; | |
f = point1.x * point2.y - point2.x * point1.y; | |
x += (point1.x + point2.x) * f; | |
y += (point1.y + point2.y) * f; | |
} | |
f = this.area() * 6; | |
return new Point(x / f, y / f); | |
}; | |
var figureCoords = []; | |
// call loop iteration for each svg layer | |
for(i = 0; i < svgPaths.length; i++){ | |
var svgPath = svgPaths[i]; | |
var subPaths = svgPath.subPathItems; | |
// call loop iteration for each svg path | |
for(k = 0; k < subPaths.length; k++){ | |
var subPath = subPaths[k]; | |
var points = subPath.pathPoints; | |
// call loop iteration for each point | |
for(l = 0; l < points.length; l++){ | |
var anchor = points[l].anchor; | |
var x = anchor[0]; | |
var y = anchor[1]; | |
figureCoords.push({x: x, y: y}); | |
} | |
// | |
var region = new Region(figureCoords); | |
var centroidData = region.centroid(); | |
activeDocument.guides.add(Direction.VERTICAL, parseInt(doc.width) - centroidData.x + " pixels"); | |
activeDocument.guides.add(Direction.HORIZONTAL, parseInt(doc.height) - centroidData.y + " pixels"); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment