Skip to content

Instantly share code, notes, and snippets.

@rogie
Last active May 24, 2022 14:19
Show Gist options
  • Select an option

  • Save rogie/49240b2352eed513639bb39271c7079f to your computer and use it in GitHub Desktop.

Select an option

Save rogie/49240b2352eed513639bb39271c7079f to your computer and use it in GitHub Desktop.
Figma Plugin API: Download exportAsync
/* code.ts (scene) */
node.exportAsync({
format: "PNG",
constraint: {
type: "WIDTH",
value: 1000
}
}).then(imageData => {
// Send the image data to the plugin window
figma.ui.postMessage({
function: "download",
imageData
})
}).catch(e => {
console.log('ERROR exportAsync: ', e)
})
/* ui.html (plugin iframe) */
function downloadBlob(blob, name = 'download') {
// Convert your blob into a Blob URL (a special url that points to an object in the browser's memory)
const blobUrl = URL.createObjectURL(blob)
// Create a link element
const link = document.createElement("a")
// Set link's href to point to the Blob URL
link.href = blobUrl
link.download = name
// Append link to the body
document.body.appendChild(link)
// Dispatch click event on the link
// This is necessary as link.click() does not work on the latest firefox
link.dispatchEvent(
new MouseEvent('click', {
bubbles: true,
cancelable: true,
view: window
})
)
// Remove link from body
document.body.removeChild(link)
}
window.addEventListener("message", (event) => {
let message = event.data;
if(event.data.pluginMessage){
message = event.data.pluginMessage
if(message.function === "download"){
let imgBlob = new Blob([message.imageData.buffer], { type: 'image/png' } )
downloadBlob(imgBlob,"download.png")
}
}
}, false);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment