three.js学习1(vue3)

月下云生 / 2023-07-31 / 原文

1.引入threejs
npm install --save three

在组件内

import * as THREE from 'three'

2.创建容器

创建canvas标签,为3D渲染建立容器

<template>
  <div>
    <canvas id="three"></canvas>
  </div>
</template>

3.创建场景

 Three.js依赖一些要素,第一是scene,第二是render,第三是carmea

// 创建场景
const initThree = () => {
    // 场景
    const scene = new THREE.Scene()
    scene.background = new THREE.Color('#eee')
    // 容器
    const canvas = document.querySelector('#three')
    // 渲染
    const renderer = new THREE.WebGLRenderer({ canvas, antialias: true })
    // 相机
    const camera = new THREE.PerspectiveCamera(50, window.innerWidth / window.innerHeight, 0.1, 1000)
    camera.position.z = 100
    function animate() {
        renderer.render(scene, camera)
        requestAnimationFrame(animate)
    }
    animate()
}
onMounted(() => {
    initThree()
})

场景的准备好了,现在是一片灰色,没有物体

4.加载物体,这里我们画线就好

 // 画线
    const material = new THREE.LineBasicMaterial({ color: 0x0000ff });
    const points: any = [];
    points.push(new THREE.Vector3(- 10, 0, 0))
    points.push(new THREE.Vector3(0, 10, 0))
    points.push(new THREE.Vector3(10, 0, 0))
    const geometry = new THREE.BufferGeometry().setFromPoints(points)
    const line = new THREE.Line(geometry, material)
    scene.add(line)

5.结果

代码地址:https://gitee.com/yuexiayunsheng/vue3learn/blob/master/src/views/ThreeCase.vue

 参考:https://zhuanlan.zhihu.com/p/333615381