<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>
threej初体验
最新推荐文章于 2024-07-23 14:06:40 发布