BabylonJS - Create ScreenShot
Babylon.js - Creating Screenshots
Section titled “Babylon.js - Creating Screenshots”Capturing the current view of your Babylon.js scene as an image file is a common requirement. While OS-level screenshots are possible, they might not offer the desired resolution or capture only the canvas content. Babylon.js provides dedicated tools for creating high-quality screenshots directly from the rendered scene.
The primary method is BABYLON.Tools.CreateScreenshotUsingRenderTarget. This function offers more control and generally performs better than older methods, especially when the engine’s preserveDrawingBuffer option is disabled (which is recommended for performance).
Syntax
Section titled “Syntax”To take a screenshot, you typically provide the engine, camera, and desired dimensions or a specific render target.
import * as BABYLON from '@babylonjs/core';
// Assuming 'engine' and 'camera' are already initializedconst size = { width: 1920, height: 1080 }; // Desired screenshot dimensions
BABYLON.Tools.CreateScreenshotUsingRenderTarget(engine, camera, size, (data) => { // 'data' contains the screenshot as a Base64 encoded data URL (e.g., "data:image/png;base64,...")
// Example: Display the image on the page const img = document.createElement("img"); img.src = data; img.style.position = 'absolute'; img.style.bottom = '10px'; img.style.right = '10px'; img.style.width = '150px'; // Optional: resize for display document.body.appendChild(img);
// Example: Trigger download // const link = document.createElement('a'); // link.download = 'screenshot.png'; // link.href = data; // link.click();}, 'image/png', 8, true); // mimeType, samples, antialiasing, fileName (optional)You might wrap this call within a button click handler to allow users to trigger the screenshot.
Engine Configuration Note
Section titled “Engine Configuration Note”Older methods sometimes required setting preserveDrawingBuffer: true and stencil: true during engine creation. While CreateScreenshotUsingRenderTarget often works without preserveDrawingBuffer, be aware that enabling it can negatively impact performance on some devices. It’s generally recommended to keep preserveDrawingBuffer: false (the default) and use CreateScreenshotUsingRenderTarget.
// Example engine creation (defaults are usually fine for screenshots with the modern method)const engine = new BABYLON.Engine(canvas, true); // 'true' enables anti-aliasingBelow is a complete example demonstrating how to set up a scene and add a button to take a screenshot.
<!DOCTYPE html><html><head> <meta charset="utf-8"/> <title>Babylon.js - Screenshot Demo</title> <script src="https://cdn.babylonjs.com/babylon.js"></script> <script src="https://cdn.babylonjs.com/loaders/babylonjs.loaders.min.js"></script> <!-- Optional: For loading textures --> <style> html, body { overflow: hidden; width: 100%; height: 100%; margin: 0; padding: 0; } #renderCanvas { width: 100%; height: 100%; touch-action: none; } #screenshotBtn { position: absolute; top: 20px; right: 20px; padding: 10px 15px; cursor: pointer; } </style></head><body> <canvas id="renderCanvas"></canvas> <button id="screenshotBtn">Take Screenshot (1920x1080)</button>
<script type="text/javascript"> const canvas = document.getElementById("renderCanvas"); const engine = new BABYLON.Engine(canvas, true, { /* preserveDrawingBuffer: false (default) */ });
const createScene = function () { const scene = new BABYLON.Scene(engine); scene.clearColor = new BABYLON.Color4(0.2, 0.3, 0.4, 1.0);
const camera = new BABYLON.ArcRotateCamera("camera", -Math.PI / 2, Math.PI / 2.5, 15, BABYLON.Vector3.Zero(), scene); camera.attachControl(canvas, true);
const light = new BABYLON.HemisphericLight("light", new BABYLON.Vector3(1, 1, 0), scene); light.intensity = 0.7;
const sphere = BABYLON.MeshBuilder.CreateSphere("sphere", { diameter: 2, segments: 32 }, scene); sphere.position.y = 1;
const ground = BABYLON.MeshBuilder.CreateGround("ground", { width: 6, height: 6 }, scene);
// Optional: Add some materials const sphereMat = new BABYLON.StandardMaterial("sphereMat", scene); sphereMat.diffuseColor = new BABYLON.Color3(0.8, 0.3, 0.3); sphere.material = sphereMat;
const groundMat = new BABYLON.StandardMaterial("groundMat", scene); groundMat.diffuseColor = new BABYLON.Color3(0.5, 0.8, 0.5); ground.material = groundMat;
return scene; };
const scene = createScene();
engine.runRenderLoop(function () { scene.render(); });
window.addEventListener("resize", function () { engine.resize(); });
// Screenshot Button Logic const screenshotBtn = document.getElementById("screenshotBtn"); screenshotBtn.addEventListener("click", function () { const screenshotSize = { width: 1920, height: 1080 }; BABYLON.Tools.CreateScreenshotUsingRenderTarget(engine, scene.activeCamera, screenshotSize, (data) => { // Trigger download const link = document.createElement('a'); link.download = 'babylonjs_screenshot.png'; link.href = data; document.body.appendChild(link); // Required for Firefox link.click(); document.body.removeChild(link); console.log("Screenshot taken!"); }, 'image/png'); }); </script></body></html>Output Description
Section titled “Output Description”Running the code above will display a 3D scene with a red sphere sitting on a green ground. A button labeled “Take Screenshot (1920x1080)” will be positioned in the top-right corner. Clicking this button will generate a 1920x1080 PNG image of the current view and trigger a download of the file named babylonjs_screenshot.png.