效果:
代码:
<template><div><el-container><el-main><div class="box-card-left"><div id="threejs"></div> <div>{{ res1 }}</div> <div>{{ res2 }}</div></div></el-main></el-container></div>
</template>s
<script>
// 引入轨道控制器扩展库OrbitControls.js
import { OrbitControls } from "three/examples/jsm/controls/OrbitControls.js";
export default {data() {return {scene: null,camera: null,renderer: null,res1: null,res2: null,};},created() {},mounted() {this.name = this.$route.query.name;this.init();},methods: {goBack() {this.$router.go(-1);},init() {this.scene = new this.$three.Scene();const axesHelper = new this.$three.AxesHelper(100);this.scene.add(axesHelper);this.createLine();this.createLine2();this.camera = new this.$three.PerspectiveCamera(60,1,0.01,2000);this.camera.position.set(30,30,30);this.camera.lookAt(0,0,0);this.renderer = new this.$three.WebGLRenderer();this.renderer.setSize(1000,800);this.renderer.render(this.scene, this.camera);window.document.getElementById("threejs").appendChild(this.renderer.domElement);const controls = new OrbitControls(this.camera, this.renderer.domElement)controls.addEventListener("change", () => {this.renderer.render(this.scene, this.camera);})},createLine() {let a = new this.$three.Vector3(10,0,0);let b = new this.$three.Vector3(0,10,0);let c = new this.$three.Vector3(0,0,10);let geometry = new this.$three.BufferGeometry().setFromPoints([a,b,c]);let material = new this.$three.LineBasicMaterial({color:0xffccdd, side: this.$three.DoubleSide});// let line = new this.$three.LineLoop(geometry, material);// let line = new this.$three.Line(geometry, material);let line = new this.$three.Mesh(geometry, material);this.scene.add(line);this.res1 = this.createRay(a,b,c);},createLine2() {let arr = new Float32Array([20,0,0,0,20,0,0,0,20,]);let position = new this.$three.BufferAttribute(arr, 3)let geometry = new this.$three.BufferGeometry();geometry.setAttribute("position", position);let material = new this.$three.LineBasicMaterial({color:0xb5a6dd});let line = new this.$three.LineLoop(geometry, material);// let line = new this.$three.Line(geometry, material);this.scene.add(line);let a = new this.$three.Vector3(20,0,0);let b = new this.$three.Vector3(0,20,0);let c = new this.$three.Vector3(0,0,20);this.res2 = this.createRay(a,b,c);},createRay(a,b,c) {// 使用箭头辅助对象显示射线的起点和方向let ray = new this.$three.Ray();ray.origin = new this.$three.Vector3(0,0,0); // 设置射线起点ray.direction = new this.$three.Vector3(1,1,1).normalize(); // 设置射线方向,保证方向为单位向量this.createArrowHelper(ray.direction, ray.origin);const point = new this.$three.Vector3();const result = ray.intersectTriangle(a,b,c, false, point);return result;},createArrowHelper(dir, origin) {let arrow = new this.$three.ArrowHelper(dir, origin, 20);this.scene.add(arrow);}},
};
</script>
<style lang="less" scoped>
.box-card-left {display: flex;align-items: flex-start;flex-direction: row;width: 100%;.box-right {img {width: 500px;user-select: none;}}
}
</style>