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);
        })

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

<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
    <script>
        // 创建场景
        const scene = new THREE.Scene();

        // 创建相机
        const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
        camera.position.z = 300;

        // 创建渲染器
        const renderer = new THREE.WebGLRenderer();
        renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(renderer.domElement);

        // 添加光源
        const light = new THREE.DirectionalLight(0xffffff, 1);
        light.position.set(0, 1, 1).normalize();
        scene.add(light);



        // 纹理加载器
        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);
        })

        // 渲染
        function animate() {
            requestAnimationFrame(animate);
            renderer.render(scene, camera);
        }
        animate();
</script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值