How to use WebGLRenderer for offscreen rendering

Hi all!
I’m working on a little JRPG project (the engine is almost finished) using another language/tool, but i am considering the idea of moving to JS (Electron/nwjs) to improve my knowledge.

I’ve been playing around with various libraries/framework (Pixi.js and melonJS) to find out if they suits my needs.

One of the core functionality i’d like to achieve before deciding to move to JS is rendering to a texture (offscreen rendering?) and then using that texture for sprites, windows, etc…

I’ve managed to achieve this result in melonjs with CanvasRenderer but not with WebGLRenderer and i’d like to know if i’m missing something:

The code i’ve written is the following:

class RenderTexture {

	constructor(a, b) {
		this._w = b ? a : a.width
		this._h = b ? b : a.height
		this._renderer = new me.CanvasRenderer({width: this._w, height: this._h, canvas: document.createElement("canvas")})
		if (!b) {
			this._renderer.drawImage(a, 0, 0)
		}
	}

	get w() {
		return this._w
	}

	get h() {
		return this._h
	}
	
	clear() {
		// TODO
	}
	
	fillRect(x, y, w, h, color) {
		// TODO
	}
	
	drawBitmap(bitmap, sx, sy, sw, sh, dx, dy, dw, dh) {
		// TODO
	}
	
	draw(renderer, sx, sy, sw, sh, dx, dy, dw, dh) {
		renderer.drawImage(this._renderer.canvas, sx, sy, sw, sh, dx, dy, dw, dh)
	}
}

The constructor accepts an Image or a width and a height. In the first case, when creating a canvas and its renderer, the image passed as a parameter is drawn on the canvas itself. In the second case, an empty canvas is created with the given size.

To test out my class i’ve created a Sprite class with a “bitmap” property extending Renderable and overriding the “draw” method to call my bitmap’s “draw” method and i’ve added it to the game world.

The code above works fine but, when i switch from CanvasRenderer to WebGLRenderer, nothing is drawn on the screen.

Am i missing something?

Thank you in advance and sorry for the bad english

Hi, interesting !

I wanted to add such a feature in melonJS, where you could pass a texture to the renderer and have it render the whole scene (current frame) to it. We even added that new CanvasTexture object (melonJS/canvas_texture.js at master · melonjs/melonJS · GitHub), but focus shifted to other higher priority features.

Which version of melonJS are you using ?

Would you be able to share a minimal working example ? Just easier than just building one from scratch.