threejs 使用base64编码的图片作为贴图

 使用base64作为贴图可以从接口直接传输(如果特别大需要压缩),可以省去很多操作

 

代码如下

// 纹理加载器
const texLoader = new THREE.TextureLoader();
const base64Str = "data:image/png;base64,...";
texLoader.load(base64Str, (texture) => {

        const aspectRatio = texture.image.width / texture.image.height;
        // 创建平面几何体
        const geometry = new THREE.PlaneGeometry(100 * aspectRatio , 100 ); // 根据比例放大

        // 创建材质
        const material = new THREE.MeshLambertMaterial({
            map: texture,
        });
// 创建网格对象
        const plane = new THREE.Mesh(geometry, material);
        scene.add(plane);
        })

渲染时需要在贴图加载完成后进行渲染,贴图需要光照才能显示
完整代码

 1  <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
 2     <script>
 3         // 创建场景
 4         const scene = new THREE.Scene();
 5 
 6         // 创建相机
 7         const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
 8         camera.position.z = 300;
 9 
10         // 创建渲染器
11         const renderer = new THREE.WebGLRenderer();
12         renderer.setSize(window.innerWidth, window.innerHeight);
13         document.body.appendChild(renderer.domElement);
14 
15         // 添加光源
16         const light = new THREE.DirectionalLight(0xffffff, 1);
17         light.position.set(0, 1, 1).normalize();
18         scene.add(light);
19 
20 
21 
22         // 纹理加载器
23         const texLoader = new THREE.TextureLoader();
24         const base64Str = "data:image/png;base64,..."
25         texLoader.load(base64Str, (texture) => {
26 
27         const aspectRatio = texture.image.width / texture.image.height;
28         // 创建平面几何体
29         const geometry = new THREE.PlaneGeometry(100 * aspectRatio , 100 ); // 根据比例放大
30 
31         // 创建材质
32         const material = new THREE.MeshLambertMaterial({
33             map: texture,
34         });
35 
36         // 创建网格对象
37         const plane = new THREE.Mesh(geometry, material);
38         scene.add(plane);
39         })
40 
41         // 渲染
42         function animate() {
43             requestAnimationFrame(animate);
44             renderer.render(scene, camera);
45         }
46         animate();
47 </script>
View Code

 

posted @ 2024-09-24 11:58  怎么还不周末1  阅读(78)  评论(0)    收藏  举报