Export entire canvas as an image (#4125)

This has been something we've been asked about 3-4 times on the discord
so far. So here is an example to point people towards in the future.

### Change type

- [ ] `bugfix`
- [ ] `improvement`
- [ ] `feature`
- [ ] `api`
- [x] `other`

### Test plan

1. Create a shape...
2.

- [ ] Unit tests
- [ ] End to end tests

### Release notes

- [examples app] added an example of how to export the page as an image
This commit is contained in:
Taha 2024-07-10 10:53:33 +01:00 committed by GitHub
parent 76a5d98eeb
commit 720b115a7e
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 60 additions and 0 deletions

View file

@ -0,0 +1,47 @@
import { exportToBlob, Tldraw, TLUiComponents, useEditor } from 'tldraw'
import 'tldraw/tldraw.css'
function ExportCanvasButton() {
const editor = useEditor()
return (
<button
style={{ pointerEvents: 'all', fontSize: 18, backgroundColor: 'thistle' }}
onClick={async () => {
const shapeIds = editor.getCurrentPageShapeIds()
if (shapeIds.size === 0) return alert('No shapes on the canvas')
const blob = await exportToBlob({
editor,
ids: [...shapeIds],
format: 'png',
opts: { background: false },
})
const link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = 'every-shape-on-the-canvas.jpg'
link.click()
}}
>
Export canvas as image
</button>
)
}
const components: TLUiComponents = {
SharePanel: ExportCanvasButton,
}
export default function ExportCanvasImageExample() {
return (
<div className="tldraw__editor">
<Tldraw components={components} />
</div>
)
}
/*
This example shows how you can use the `exportToBlob()` function to create an image with all the shapes
on the canvas in it and then download it. The easiest way to download an image is to use the download
attribute of a link element.
To learn more about overriding UI you can check out our various custom menu examples. For more on handling
assets, check out our Local/Hosted images examples.
*/

View file

@ -0,0 +1,13 @@
---
title: Export canvas as image
component: ./ExportCanvasImageExample.tsx
category: data/assets
priority: 2
keywords: [basic, assets, svg, png, blob]
---
Export the entire canvas as an image file
---
This example shows how you can use the `exportToBlob()` function to create an image with all the shapes on the canvas in it and then download it. The easiest way to download an image is to use the download attribute of a link element.