vue中使用three.js

首先在html页面中引入<script src="http://www.yanhuangxueyuan.com/versions/threejsR92/build/three.js"></script>

页面中

<template>

  <div>

    <div id="demo"></div>

  </div>

</template>

<script>

export default {

  data() {

    return {

      mesh: null,

      renderer: null,

      scene: null,

      camera: null,

    };

  },

  mounted() {

    this.init();

  },

  methods: {

    init() {

      // 创建场景

      this.scene = new THREE.Scene();

      // 创建相机(第一个参数视野夹角0~180°,第二参数相机大小,第三,四参数可看像素)

      this.camera = new THREE.PerspectiveCamera(

        75,

        window.innerWidth / window.innerHeight,

        1,

        1000

      );

      // 创建渲染器

      this.renderer = new THREE.WebGLRenderer();

      // 设置渲染器大小

      this.renderer.setSize(window.innerWidth, window.innerHeight);

      // 拿到dom

      let demo = document.getElementById("demo");

      // 把渲染器放到dom中

      demo.appendChild(this.renderer.domElement);

      // 创建一个立方体(长,宽,高)

      let geometry = new THREE.BoxGeometry(10, 10, 10);

      // 创建材料(定义立方体由这个材料组成)

      let material = new THREE.MeshBasicMaterial({

        color: 0xcccccc,

      });

      // 创建网格(合并立方体和材料)

      this.mesh = new THREE.Mesh(geometry, material);

      // 将网格放入场景中

      this.scene.add(this.mesh);

      // 因默认情况相机与场景重合,需要先设定相机位置

      this.camera.position.z = 50;

      this.camera.position.y = 0;

      // 用渲染器渲染场景,相机

      this.renderer.render(this.scene, this.camera);

      this.animate();

    },

    // 定义3D效果

    animate() {

      // 执行动画函数,执行完上一帧在执行下一帧

      requestAnimationFrame(this.animate);

      this.mesh.rotation.x += 0.05;

      // this.mesh.rotation.y += 0.05;

      this.mesh.rotateY(0.01)

      this.renderer.render(this.scene, this.camera);

    },

  },

};

</script>

<style>

body {

  margin: 0;

  overflow: hidden;

  /* 隐藏body窗口区域滚动条 */

}

</style>

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

相关阅读更多精彩内容

友情链接更多精彩内容