Skip to content

Commit 68befa8

Browse files
feat: add print functionality to capture and download viewport image (#148)
Co-authored-by: Tomás Grüner <47506558+MegaRedHand@users.noreply.github.com>
1 parent 25b94bd commit 68befa8

File tree

2 files changed

+50
-2
lines changed

2 files changed

+50
-2
lines changed

src/index.ts

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import PauseSvg from "./assets/pause-icon.svg";
2323
import UndoSvg from "./assets/left-curve-arrow.svg";
2424
import RedoSvg from "./assets/right-curve-arrow.svg";
2525
import { layerToName } from "./types/devices/layer";
26+
import { captureAndDownloadViewport } from "./utils";
2627

2728
const assets = [
2829
RouterSvg,
@@ -127,9 +128,12 @@ async function loadAssets(otherPromises: Promise<void>[]) {
127128
deselectElement();
128129
loadFromFile(ctx);
129130
};
130-
printButton.onclick = () => {
131+
printButton.onclick = async () => {
132+
const viewport = ctx.getViewport();
133+
captureAndDownloadViewport(app, viewport);
131134
ctx.print();
132135
};
136+
133137
// Undo button’s logic
134138
const undoButton = document.getElementById(
135139
"undo-button",

src/utils.ts

Lines changed: 45 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
import { GraphicsContext } from "pixi.js";
1+
import { Viewport } from "pixi-viewport";
2+
import { Application, GraphicsContext, RenderTexture } from "pixi.js";
23

34
export enum Colors {
45
Violet = 0x4b0082,
@@ -29,3 +30,46 @@ export enum ZIndexLevels {
2930
Packet = 16,
3031
Label = 19,
3132
}
33+
34+
/**
35+
* Captures the current viewport and downloads it as an image.
36+
* @param app - The PixiJS application instance.
37+
* @param viewport - The viewport instance to capture.
38+
*/
39+
export function captureAndDownloadViewport(
40+
app: Application,
41+
viewport: Viewport,
42+
) {
43+
if (!viewport) {
44+
alert("Viewport not found.");
45+
return;
46+
}
47+
48+
// Step 1: Create a texture and render the viewport into it
49+
const renderTexture = RenderTexture.create({
50+
width: app.renderer.width,
51+
height: app.renderer.height,
52+
});
53+
54+
// Step 2: Render the viewport into the texture
55+
app.renderer.render({
56+
container: viewport,
57+
target: renderTexture,
58+
});
59+
60+
// Step 3: Extract the RenderTexture as a canvas
61+
const extractedCanvas = app.renderer.extract.canvas(renderTexture);
62+
63+
// Step 4: Convert the extracted canvas to a Blob and download it
64+
extractedCanvas.toBlob((blob) => {
65+
if (!blob) {
66+
alert("Failed to generate image.");
67+
return;
68+
}
69+
70+
const link = document.createElement("a");
71+
link.href = URL.createObjectURL(blob);
72+
link.download = "viewport-snapshot.png";
73+
link.click();
74+
}, "image/png");
75+
}

0 commit comments

Comments
 (0)