Assign a canvas by ID as the texture

How to assign a canvas by ID as the texture?

var canvasTexture = document.getElementById("myCanvas");

function changeTexture(mesh){
     var textureGround = new BABYLON.DynamicTexture("dynamic texture", 512, scene);   
     var canvasTexture = textureGround.getContext();


     var mat = new BABYLON.StandardMaterial("mat", scene);
     var texture = new BABYLON.Texture(canvasTexture , scene); // variable does not apply
     mat.diffuseTexture = texture;
     mesh.material = mat;
}
var mesh = scene.getMeshByName("myWonderfulMesh");
changeTexture(mesh)

Hi,

My first thought is to create screenshot of the canvas and then use that image as a texture. You can check that out here.

https://doc.babylonjs.com/how_to/render_scene_on_a_png

So basically, you save canvas content as image (png) and then use that image as a texture.

1 Like

Thank you @nogalo . I’ll mark this thread as answered because that answered my question. :slight_smile:

@nogalo I do not understand how to use the screenshot in the new BABYLON.Texture(). DO I have to give the screenshot an ID and then use the id in the new BABYLON.Texture)? Can you please help me out?

function getsnapShaot(){
  BABYLON.Tools.CreateScreenshot(engine, camera, { width: 1024, height: 300 }, function (data) {
     var img = document.createElement("img");
     img.src = data;
     document.body.appendChild(img);  
  });
}

and then how to use it in the texture ?

var texture = new BABYLON.Texture(canvasTexture , scene);

var texture = new BABYLON.DynamicTexture("dynamic texture", document.getElementById("myCanvas"), scene);

1 Like

@Gijs Thank you… :slight_smile: