美文网首页three.js
关于Vue中使用three.js加载模型问题

关于Vue中使用three.js加载模型问题

作者: 朋_朋 | 来源:发表于2019-09-30 11:06 被阅读0次
import * as THREE from 'three'
import {STLLoader} from ‘three/examples/jsm/loaders/STLLoader’                    //一定要从jsm中引入loader文件,否则会报错导致文件无法加载,同时STLLoader需要用大括号包含,作为一个结构体
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'           //同样需要从jsm中引入,也要作为一个结构体

后续就可以正常按照three.js加载模型语法进行编写了(因为使用的是Vue,所以data中定义省略)

    <template>

        <div id="Container" style="width: 1000px;height: 800px;"></div>

    </template>



    <script>
        let container = document.getElementById('container')
        this.camera = new THREE.PerspectiveCamera(30, document.getElementById('container').clientWidth / 
       document.getElementById('container').clientHeight, 1, 2000);
        this.camera.position.set(-200, 150, 250);
        this.scene = new THREE.Scene()


        var pointLight = new THREE.PointLight(0xffffff, 1);
        this.camera.add(pointLight);
        this.scene.add(this.camera);

        // 显示坐标系
        var axes = new THREE.AxesHelper(50);
        this.scene.add(axes)

        this.renderer = new THREE.WebGLRenderer({alpha: true});
        this.renderer.setClearAlpha(0);
        this.renderer.setPixelRatio(window.devicePixelRatio);
        this.renderer.setSize(container.clientWidth, container.clientHeight)
        container.appendChild(this.renderer.domElement)
    </script>


在写完相机和场景之后,就可以进行进行模型的加载了,代码如下:

            new STLLoader().load('/static/BMW.stl', geometry => {
                console.log(geometry)
                let material = new THREE.MeshPhongMaterial({
                    color: 0xffffff,
                    wireframe: true
                })

                this.mesh = new THREE.Mesh(geometry, material)
                this.mesh.position.set(0, 0, 0)
                this.scene.add(this.mesh)
                this.renderer.render(this.scene, this.camera)
            }, event => {
            console.log(event)
            },
            onerror => {
                console.log(onerror)
          })

在引用时,请注意一下几点:
1.要从three.js的examples/jsm中引用loader函数,从js目录下引用会产生错误
2.模型文件放到static目录下,个人尝试,放到相同目录使用相对路径查找,无法显示

相关文章

网友评论

    本文标题:关于Vue中使用three.js加载模型问题

    本文链接:https://www.haomeiwen.com/subject/nppcpctx.html