|
1 | 1 | import { AppBar, Button, Toolbar, useTheme } from '@material-ui/core'; |
2 | 2 | import { ClickEvent, Menu, MenuItem, SubMenu } from '@szhsin/react-menu'; |
| 3 | +import html2canvas from 'html2canvas'; |
3 | 4 | import React, { ChangeEvent } from 'react'; |
4 | 5 | import logo from '../../assets/images/logo.png'; |
5 | 6 | import { PROJECT_FILE_EXTENSION } from '../../core/constants'; |
@@ -196,6 +197,34 @@ function MenuBar(props: MenuBarProps) { |
196 | 197 | } |
197 | 198 | } |
198 | 199 |
|
| 200 | + /** |
| 201 | + * Export the current canvas as a PNG image. |
| 202 | + * Captures the element with id 'canvas-container' using html2canvas and triggers a download. |
| 203 | + */ |
| 204 | + const exportAsPNG = (_event: ClickEvent) => { |
| 205 | + const container = document.getElementById('canvas-container'); |
| 206 | + if (!container) { |
| 207 | + alert('Canvas area not found.'); |
| 208 | + return; |
| 209 | + } |
| 210 | + // The promise chain ensures the handler executes synchronously within the menu component. |
| 211 | + |
| 212 | + html2canvas(container as HTMLElement, { backgroundColor: null }) |
| 213 | + .then((canvas: HTMLCanvasElement) => { |
| 214 | + const url = canvas.toDataURL('image/png'); |
| 215 | + const link = document.createElement('a'); |
| 216 | + link.href = url; |
| 217 | + link.download = editor.getName() + '.png'; |
| 218 | + document.body.appendChild(link); |
| 219 | + link.click(); |
| 220 | + document.body.removeChild(link); |
| 221 | + }) |
| 222 | + .catch((err: any) => { |
| 223 | + console.error('Error exporting canvas as PNG:', err); |
| 224 | + alert('Could not export canvas as PNG. See console for details.'); |
| 225 | + }); |
| 226 | + } |
| 227 | + |
199 | 228 | /** |
200 | 229 | * Recursive helper function to generate menu options for the Blocks menu. |
201 | 230 | * @param blocks Map containing Blocks menu structure |
@@ -235,6 +264,7 @@ function MenuBar(props: MenuBarProps) { |
235 | 264 | <MenuItem onClick={saveBlock}>Save Block</MenuItem> |
236 | 265 | <MenuItem onClick={addAsBlock}>Add as block</MenuItem> |
237 | 266 | <MenuItem onClick={buildAndDownload}>Build and Download</MenuItem> |
| 267 | + <MenuItem onClick={exportAsPNG}>Export as PNG</MenuItem> |
238 | 268 | </Menu> |
239 | 269 | <Menu |
240 | 270 | menuButton={<Button className='menu-button'>Edit</Button>} |
|
0 commit comments