☑ Save specific rendered entities to image

@max is it possible to render specific elements to some offscreen canvas?

I would like to take a screenshot of the current without GUI elements. With my current code I get a flickering for some milliseconds as I am enabling/disabling entities on the main canvas. I am doing something like this:

this.enableGUIEntities(false);

window.setTimeout(function(){

    this.renderToTexture(function(base64){

        this.enableGUIEntities(true);
        
        downloadImage(base64);

    }.bind(this) );

}.bind(this), 50);

And the actual function that does the trick:


Screen.prototype.renderToTexture = function(callback) {

   // Create a render target with a depth buffer
    var colorBuffer = new pc.Texture(this.app.graphicsDevice, {
        width: this.app.graphicsDevice.canvas.width,
        height: this.app.graphicsDevice.canvas.height,
        format: pc.PIXELFORMAT_R8_G8_B8
    });
    var renderTarget = new pc.RenderTarget(this.app.graphicsDevice, colorBuffer, {
        depth: true
    });

    this.entityCamera.camera.renderTarget = renderTarget;
    
    window.setTimeout(function(){

        var gl =  this.app.graphicsDevice.gl;
        var fb = gl.createFramebuffer();
        var pixels = new Uint8Array(colorBuffer.width * colorBuffer.height * 4);
        gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
        gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, colorBuffer._glTextureId, 0);
        gl.readPixels(0, 0, colorBuffer.width, colorBuffer.height, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
        
        
        this.entityCamera.camera.renderTarget = null;

        var canvas = document.createElement("canvas"),
            ctx = canvas.getContext("2d"),
            img = pixels;

        canvas.width = colorBuffer.width;
        canvas.height = colorBuffer.height;
        
        // first, create a new ImageData to contain our pixels
        var imgData = ctx.createImageData(colorBuffer.width, colorBuffer.height); // width x height
        var data = imgData.data;

        // copy img byte-per-byte into our ImageData
        for (var i = 0, len = colorBuffer.width * colorBuffer.height * 4; i < len; i++) {
            data[i] = img[i];
        }
        
        // now we can draw our imagedata onto the canvas
        ctx.putImageData(imgData, 0, 0);

        var image = canvas.toDataURL('image/png');
        
        callback(image);
        
        window.location.href = image.replace('image/png', 'image/octet-stream');   
    
        
    }.bind(this), 50);

};

Everything works fine but I would like to do all that on an offscreen canvas, outside of the main render loop.