Hey guys,
I’m developing an AR project in PlayCanvas using WebXR, after entering AR mode and tapping on screenshot button, it takes the entities only not the environment
here is the screenshot.js:
var Screenshot = pc.createScript('screenshot');
Screenshot.prototype.initialize = function () {
// Find the button entity by its name or tag
this.button = this.entity.findByName('Button-TakeScreenshot');
// Add event listeners for click and touch
this.button.element.on('click', this.takeScreenshot, this);
this.button.element.on('touchend', this.takeScreenshot, this);
};
Screenshot.prototype.takeScreenshot = function () {
// Get the XR session (WebXR)
var xr = this.app.xr;
if (xr && xr.session) {
// Capture the WebXR frame
xr.session.requestAnimationFrame((time, frame) => {
// Get the WebGL framebuffer
const gl = this.app.graphicsDevice.gl;
const framebuffer = frame.session.renderState.baseLayer.framebuffer;
// Bind the framebuffer
gl.bindFramebuffer(gl.FRAMEBUFFER, framebuffer);
// Read the pixels from the framebuffer
const width = frame.session.renderState.baseLayer.framebufferWidth;
const height = frame.session.renderState.baseLayer.framebufferHeight;
const pixels = new Uint8Array(width * height * 4);
gl.readPixels(0, 0, width, height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
// Create a canvas to render the pixels
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
// Flip the image vertically (WebGL pixels are upside-down)
const imageData = ctx.createImageData(width, height);
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; x++) {
const srcIndex = (y * width + x) * 4;
const dstIndex = ((height - y - 1) * width + x) * 4;
imageData.data[dstIndex] = pixels[srcIndex]; // R
imageData.data[dstIndex + 1] = pixels[srcIndex + 1]; // G
imageData.data[dstIndex + 2] = pixels[srcIndex + 2]; // B
imageData.data[dstIndex + 3] = pixels[srcIndex + 3]; // A
}
}
// Draw the image data onto the canvas
ctx.putImageData(imageData, 0, 0);
// Convert the canvas to a Blob and trigger a download
canvas.toBlob((blob) => {
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'screenshot.png';
link.click();
URL.revokeObjectURL(link.href);
}, 'image/png');
});
} else {
console.warn('WebXR session is not active.');
}
};