Use canvas as texture

Now I want to use canvas as the texture of the mesh. Using HtmlElementTexture and PBRMaterial can meet my requirements, but I am not sure if this is the best way. And I found that the fill color of canvas is black. If I want the fill color to be How should I do transparent color? Because I use an external library, I cannot provide a playground. The following is part of my code.I can provide this base64 if needed.Looking forward to your reply!


 const canvas1 = document.querySelector('.heatmap').children[0];
                var texture = new BABYLON.HtmlElementTexture("", canvas1, {
                // const textureInBase64 = canvas1.toDataURL();
                // console.log(textureInBase64);
                // var texture = new BABYLON.Texture.CreateFromBase64String(
                //     textureInBase64,
                //     "theTexture",
                //     scene
                // )

                var material = new BABYLON.PBRMaterial("", scene);
                material.unlit = true;
                material.alpha = 1;
                material.albedoTexture = texture;
                // material.albedoColor = new BABYLON.Color3(1, 0, 0);
                box.material = material;

This is the result of demo:

PBRMaterial | Babylon.js Documentation (
If your albedoTexture has an alpha channel, you can enable this property to get the corresponding transparent rendering.
If your image itself does not have an alpha channel, just the background is filled with black, you can use the canvas API to change the black pixels to transparent pixels.

PBRMaterial | Babylon.js Documentation (
Or you can choose to use opacityTexture.

I made a playground using base64 of canvas. I tried two methods but neither achieved the desired effect. Please help!

Babylon.js Playground (
texture.hasAlpha the default value is false, which ignores the alpha value.Change to true and alpha will take effect.

1 Like

Wow!This is just what I need! Thank you for your help! i learned a lot :crossed_fingers: