Texture toDataUrl?

Hello !
Today, I wanted to generate a displacement map with a perlin noise, and then apply it to a mesh.
I checked the doc : I can use a ProceduralTexture to generate a nice perlin noise texture. And there is also a mesh method to apply a displacement map to the geometry.
Looks like everything I need is here.
But no : you actually need an image url to apply a displacement map to a mesh, not a texture !
So, to make it work that I can either draw a perlin noise in canvas, and to dataurl it or draw the perlin texture on screen, take a screenshot and generate an url for it ?
It seems to me me that an export to dataUrl for proceduralTextures (or textures in general) could be a nice feature, it would solve my problem and allow user to create procedural textures from babylon and use them in the DOM.
Otherwise, the applyDisplacementMap function could also accept a texture instead of an url in first parameter.
What do you think about this ?

1 Like

Hi, you can use applyDisplacementMapFromBuffer instead, and get the buffer from readPixels.

A toDataUrl method would be great:

        let size = texture.getSize();
        let canvas = document.createElement('canvas'); // or use some temporary canvas from elsewere
        canvas.width = size.width;
        canvas.height = size.height;
        let ctx = canvas.getContext('2d');
        ctx.putImageData(new ImageData(new Uint8ClampedArray(texture.readPixels()), size.width, size.height), 0, 0);
        let dataUrl = canvas.toDataURL();

But then first a separate toImageData function to use in the toDataUrl function. Then we might as well add a toImageBitmap function; ImageBitmaps can be drawn using the drawImage function on a CanvasRenderingContext2D / DynamicTexture.

4 Likes

Thanks for your help. I’ll try it out monday.
You’re right, a toImageBitmap function would be great.