【THREE.JS学习(2)】在VUE中使用ThreeJS

5 篇文章 1 订阅
2 篇文章 0 订阅

在使用THREE的过程中,发现很多例子都是用了ES6的语法,在调试时,需要将其进行编译。笔者尝试了用parcel进行搭建个人应用环境,也可以,但是相对而言,还是VUE更加方便。

该处以VUE2 为例,介绍THREE(案例一)在VUE中的使用。

首先创建VUE项目

vue create <project name> 

接着安装Three

npm install three

在使用three需要引入对应的文件

本文以创建的默认文件【HelloWorld.vue】为例,直接对该文件进行修改。

<script>
    //核心库
    import * as THREE from "three"
    //控制器,可以让用户在场景中自由移动和旋转相机,以便更好地查看场景
    import {OrbitControls} from "three/examples/jsm/controls/OrbitControls"
</script>

依旧和【文章一】中的步骤一样,{场景、相机、渲染器}三者的创建。

首先在data中建立对应的字段

data(){
    return {
        scene:null,
        camera:null,
        renderer:null,
        //宽高声明
        width:0,
        height:0
    }
}

同样,我们需要设置div。

<template>
  <div class="webgl-container">
    <div id="webglDom" ref="webglDom"></div>
  </div>
</template>

接着,在使用时,我们需要获取当前屏幕的可视大小

const container = this.$refs.webglDom;
this.width = container.offsetWidth;
this.height = container.offsetHeight;

这样初始条件就设置好了,接下来就可以生成对应的条件了

this.scene = new THREE.Scene();

this.camera = new THREE.PerspectiveCamera(45, this.width / this.height, 0.01, 10000);
this.camera.position.z = 5;
this.add(this.camera);
this.camera.lookAt(this.scene.position);

// AxesHelper
let axisHelper = new THREE.AxesHelper(100, 100);
this.add(axisHelper);

const geometry = new THREE.BoxGeometry(1, 1, 1);
const material = new THREE.MeshBasicMaterial({
color: "skyblue"
});
const mesh = new THREE.Mesh(geometry, material);
this.add(mesh);

// 渲染器
this.renderer = new THREE.WebGLRenderer({
antialias: true
})
this.renderer.setSize(this.width, this.height);
document.getElementById("webglDom").appendChild(this.renderer.domElement);

// OrbitControls
new OrbitControls(this.camera, this.renderer.domElement);
this.render();
//部分需求函数,存放在methods中 
add (obj) {
      this.scene.add(obj);
    },
render() {
  this.renderer.render(this.scene, this.camera);
  requestAnimationFrame(this.render);
}

样式设置

#webglDom{
  width: 100%;
  height: 800px;
  overflow: hidden;
}
.webgl-container{
  width: 100%;
  height: 800px;
  overflow: hidden;
}

通过

npm run serve

即可运行。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值