How to show GLB model with texture .png in javascript?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name='viewport' content='width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no' />
<style>
body {
margin: 0;
overflow: hidden;
}
</style>
<script src='https://code.playcanvas.com/playcanvas-stable.js'></script>
<script src='playcanvas-gltf.js'></script>
<script src='playcanvas-anim.js'></script>
<script src='export-gltf.js'></script>
</head>
<body>
<script>
var canvas = document.createElement('canvas');
document.body.appendChild(canvas);
var app = new pc.Application(canvas, {});
app.start();
// fill the available space at full resolution
app.setCanvasFillMode(pc.FILLMODE_FILL_WINDOW);
app.setCanvasResolution(pc.RESOLUTION_AUTO);
// ensure canvas is resized when window changes size
window.addEventListener('resize', function() {
app.resizeCanvas();
});
// create camera entity
var camera = new pc.Entity('camera');
camera.addComponent('camera', {
clearColor: [ 0.1, 0.8, 100 ]
});
app.root.addChild(camera);
camera.setLocalPosition(0, 2, 3);
// Mouse wheel event listener for zooming
canvas.addEventListener('wheel', function (event) {
// Adjust the camera's position based on the mouse wheel delta
camera.translateLocal(0, 0, -event.deltaY * 0.01);
});
// create directional light entity
var light = new pc.Entity('light');
light.addComponent('light',);
app.root.addChild(light);
light.setEulerAngles(25, 0, 25);
// rotator script
var Rotate = pc.createScript('rotate');
Rotate.prototype.update = function (deltaTime) {
this.entity.rotate(0, deltaTime * 10, 0);
};
// glTF scene root that rotates
var gltfRoot = new pc.Entity();
gltfRoot.addComponent('script');
gltfRoot.script.create('rotate');
app.root.addChild(gltfRoot);
app.assets.loadFromUrl('/cat4_enviroment.png', 'texture', function (err, textureAsset) {
if (!err) {
// Unload existing texture if needed
// e.g., app.scene.skybox.cubeMap.unload();
app.assets.loadFromUrl('/cat4_v4.gltf', 'json', function (err, asset) {
var json = asset.resource;
var gltf = JSON.parse(json);
loadGltf(gltf, app.graphicsDevice, function (err, res) {
// add the loaded scene to the hierarchy
var gltfRoot = new pc.Entity();
app.root.addChild(gltfRoot);
gltfRoot.addComponent('model');
gltfRoot.model.model = res.model;
// Apply the loaded texture to the environment
applyEnvironmentTexture(textureAsset.resource, app.scene);
}, {
basePath: ''
});
});
} else {
console.error('Error loading texture', err);
}
});
// Function to apply the texture to the model
function applyEnvironmentTexture(texture, scene) {
// Unload existing texture if needed
// e.g., scene.skybox.cubeMap.unload();
// Create an instance of pc.StandardMaterial
var material = new pc.StandardMaterial();
// Set the cubeMap property of the material to the loaded texture
material.diffuseMap = assets.playcanvasGreyTexture.resource;
material.update();
}
</script>
</body>
</html>