When the element exceeds the frame, a deviation in size and position

Hello, I found that when uploading with Meaxure, if the elements exceed the frame, there may be deviations in the position and size of the annotations. Three examples of exceeding the frame are shown in the following figure. We are using the official Sketch.Export API. Is there a way to solve it?

Hello there,

Yes unfortunately sketch.export doesn’t allow you to crop the out-of-bounds layer effects, so you always end up with a full image with shadows, outside borders, etc.

One workaround is to insert an artificial Slice of desired size just above your target layer, export this slice, and then remove it afterwards:

const sketch = require('sketch')

function exportLayerCropped(layer, options) {
  const slice = new sketch.Slice({ frame: layer.frame })
  layer.parent.layers.splice(layer.index, 0, slice)
  
  sketch.export(slice, options)
  
  slice.remove()
}

// [...]

const layer = // ...
exportLayerCropped(layer, {
  output: '/path/to/export/folder',
  filename: 'export.png',
  formats: ['png'],
})
2 Likes

A quick followup–

The workaround with an artificial Slice only works if your target layer is 100% opaque: if there’s translucency, the slice might actually capture some of the layer’s background. In order to mitigate that, pass the group-contents-only option as well:

function exportLayerCropped(layer, options) {
  // ...
  
  sketch.export(slice, {
    ...options,
    'group-contents-only': true // 👈
  })
  
  // ...
}
1 Like