vue中引入three.js

<template>
    <div id="app"></div>
</template>


<script>
    import * as THREE from "three";
    import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';
    export default {
        data() {
            return {
                camera: null,
                scene: null,
                renderer: null,
                mesh: null,

            };
        },
        mounted() {
            this.init();
            this.animate();
            window.addEventListener('resize', this.onWindowSize())
        },
        methods: {
            //初始化
            init() {
                //  创建场景对象Scene
                this.scene = new THREE.Scene();

                //网格模型添加到场景中
                let geometry = new THREE.BoxGeometry(20, 20, 20);
                let material = new THREE.MeshBasicMaterial({
                    color: 0xff0000
                });
                this.mesh = new THREE.Mesh(geometry, material);
                this.scene.add(this.mesh);

                /**
                 * 相机设置
                 */

                let container = document.getElementById("app");
                this.camera = new THREE.PerspectiveCamera(
                    70,
                    container.clientWidth / container.clientHeight,
                    0.01,
                    1000
                );
                this.camera.position.set(50, 50, 50)
                this.camera.lookAt(this.scene.position)
                /**
                 * 创建渲染器对象
                 */
                this.renderer = new THREE.WebGLRenderer({ antialias: true });
                this.renderer.setSize(container.clientWidth, container.clientHeight);
                this.renderer.setPixelRatio(window.devicePixelRatio)
                container.appendChild(this.renderer.domElement);

                //创建控件对象
                new OrbitControls(this.camera, this.renderer.domElement);
            },

            // 窗口变化
            onWindowSize() {
                let container = document.getElementById("app");
                this.camera.aspect = container.clientWidth / container.clientHeight,
                this.camera.updateProjectionMatrix()
                this.renderer.setSize(container.clientWidth, container.clientHeight);


            },
            // 动画
            animate() {
                requestAnimationFrame(this.animate);
                this.mesh.rotation.x += 0.01;
                this.mesh.rotation.y += 0.02;
                this.renderer.render(this.scene, this.camera);
            }
        }
    };
</script>

<style>
    #app {
        position: absolute;
        width: 100%;
        height: 100%;
    }
</style>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容