threej初体验

在这里插入图片描述

<template>
  <div>
    <div id="canvas-container" :ref="canvasContainer" v-resize="resize" v-show="isWebGL"></div>
    <div v-if="!isWebGL" class="incompatible-hint">
      您的显卡似乎不支持
      <a :href="href" style="color: #000" previewlistener="true">WebGL</a>
    </div>
  </div>
</template>

<script>
import * as THREE from "three";
import WebGL from "three/addons/capabilities/WebGL.js";

export default {
  name: "",
  data() {
    return {
      renderer: null, //渲染器
      camera: null, //相机
      scene: null, //场景
      isWebGL: true, //是否支持WebGL
      canvasContainer: "canvasContainer", //canvas容器
      href: "http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation", //WebGL链接
    };
  },
  mounted() {
    this.initScene();
  },
  methods: {
    resize() {
      this.renderer.setSize(window.innerWidth, window.innerHeight);
      this.$refs.canvasContainer.appendChild(this.renderer.domElement); // 将渲染器的dom元素添加到页面
    },
    initScene() {
      // 初始化场景
      this.scene = new THREE.Scene();
      // 初始化相机
      this.camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
      this.camera.position.z = 500;
      // 初始化渲染器
      this.renderer = new THREE.WebGLRenderer();
      this.renderer.setSize(window.innerWidth, window.innerHeight);
      this.$refs.canvasContainer.appendChild(this.renderer.domElement); // 将渲染器的dom元素添加到页面
      // 创建几何体和材质
      const geometry = new THREE.BoxGeometry(500, 100, 100);
      const material = new THREE.MeshBasicMaterial({ color: 0xff0015 }); //0xff0015:#ff0015
      const cube = new THREE.Mesh(geometry, material);
      // 添加立方体到场景
      this.scene.add(cube);
      // 添加环境光(可选,用于基本光照效果)
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
      this.scene.add(ambientLight);
      // 渲染循环
      const that = this;
      function animate() {
        requestAnimationFrame(animate);
        // 使立方体动起来
        cube.rotation.x += 0.01;
        cube.rotation.y += 0.01;
        that.renderer.render(that.scene, that.camera);
      }
      // WebGL兼容性检查
      if (WebGL.isWebGLAvailable()) {
        // Initiate function or other initializations here
        this.isWebGL = true;
        animate();
      } else {
        this.isWebGL = false;
      }
    },
  },
  beforeDestroy() {
    // 清理工作,比如移除事件监听器等(如果有)
  },
};
</script>

<style scoped>
#canvas-container {
  width: 100%;
  height: 100vh;
}
.incompatible-hint {
  font-family: monospace;
  font-size: 13px;
  font-weight: normal;
  text-align: center;
  background: rgb(255, 255, 255);
  color: rgb(0, 0, 0);
  padding: 1.5em;
  width: 400px;
  margin: 5em auto 0px;
}
</style>

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值