Matti
Matti

Reputation: 484

How to efficiently reuse canvases for several canvas-based THREE.Texture

I am building a three.js application where I have multiple textures I have to generate dynamically (and also possibly regenerate (update) later on). For now I am allocating a dedicated offscreen drawing canvas per such texture, allocated as such:

canvas = document.createElement('canvas');
canvasContext = canvas.getContext('2d');
mainTexture = new THREE.Texture(canvas);

Then when I have to update the texture, I render stuff to the canvas using Canvas API and then call

mainTexture.needsUpdate = true;

which causes the texture to reload its contents from the canvas sometime in the future. Any images I need for canvas rendering I have preloaded and cached so they won't cause any more lag when doing the render.

This process causes twitching for a while after the update cycle, apparently due to the lazy loading and / or the unnecessarily large amount of memory wasted in having multiple canvases (this is just a hunch; I have no idea how the memory is managed for allocated html5 canvases).

So my question is, how to do this more efficiently? I cannot, as such, just use a single canvas since if I were to update several textures at the same time, their updates would overwrite the ones done earlier due to the lazy loading nature of the texture. Is there a way to force the texture to reload from the canvas synchronously and immediately? Would there exist another feasible strategy to not to have multiple canvases?

ty,

Matti

Upvotes: 3

Views: 843

Answers (1)

Console-buche
Console-buche

Reputation: 405

Have you tried making spritesheets out of your canvas, then setting the UV coordinates or texture offset according to the desired texture ?

If no, give it a try, spritesheets do wonders !

Beware of canvas size, though. I wouldn't advice using canvases larger than 2048*2048 -- here's an interesting conversation that might give you hints

Upvotes: 1

Related Questions