You can change the position of the shapePath by specifying the frame’s x and y points. Like so:
shapePath.frame.x = 40
shapePath.frame.y = 100
Pretty simple right? The tricky part is knowing where the canvas is positioned over the coordinate system. It’s some function of the topmost left corner and the zoom level. Luckly there is a private method that we can utilize to get this so we don’t have to too much math.
let canvasRect = document.sketchObject.contentDrawView().visibleContentRect()
This gives us some offset from the origin as well as the width and height of the rectangle that we can see through the viewport.
Putting it all together you have something like this:
let sketch = require('sketch')
let ShapePath = sketch.ShapePath
let Rectangle = sketch.Rectangle
const document = sketch.getSelectedDocument();
const page = document.selectedPage;
let canvasRect = document.sketchObject.contentDrawView().visibleContentRect()
let centerPoint = {
x: canvasRect.origin.x+canvasRect.size.width/2,
y: canvasRect.origin.y+canvasRect.size.height/2
}
let svgPath = 'M10 10 H 90 V 90 H 10 L 10 10'
const shapePath = ShapePath.fromSVGPath(svgPath);
shapePath.style.fills = ['#FF0000']
shapePath.frame.x = centerPoint.x - shapePath.frame.width/2
shapePath.frame.y = centerPoint.y - shapePath.frame.height/2
page.layers.push(shapePath);
All that being said, I actually don’t like putting a layer in an arbitrary position on the page like this. It’s generally better usability to look and put the newly added SVG path on the page more intelligently. For example, perhaps you could put it within the currently selected object. Or perhaps you put it to the right of the currently selected object or to the right of all the canvases. Once you put it in this spot you can use the function:
document.centerOnLayer(layer)
And center on the position of where you inserted the shape layer.