<template>
<div class="container">
<canvas id="webgl"></canvas>
</div>
</template>
<script>
import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import img from '../../assets/image/1.jpg'
export default {
mounted(){
// 创建场景
let scene = new THREE.Scene();
// 创建环境灯光
const light = new THREE.AmbientLight('#fff'); // soft white light
scene.add( light );
// 创建地面材质
let plane = new THREE.Mesh(
new THREE.PlaneGeometry(7,7),
new THREE.MeshStandardMaterial({color:'#00ff00'})
)
// 创建房屋主体
let home = new THREE.Mesh(
new THREE.BoxGeometry(3,2.5,2),
new THREE.MeshStandardMaterial({color:'#338161'})
)
// 调节位置
home.position.z = 1;
// 创建屋顶结构
let roof = new THREE.Mesh(
new THREE.ConeGeometry(2.5,1,4),
new THREE.MeshStandardMaterial({color: '#15db89'})
)
roof.position.z = 1 / 2 + 2
roof.rotation.y = Math.PI / 4;
roof.rotation.x = Math.PI / 2;
// 创建门的贴图
const texture = new THREE.TextureLoader().load(img);
// 创建门结构
let door = new THREE.Mesh(
new THREE.PlaneGeometry(1.25,1),
new THREE.MeshStandardMaterial({map:texture})
)
door.rotation.y = Math.PI / 2;
door.position.x = 1.5 + 0.01;
door.position.z = 1 / 2
// 创建一个group
let group = new THREE.Group();
group.add(plane)
group.add(home)
group.add(roof);
group.add(door);
scene.add(group);
// 选取canvas节点
let canvas = document.querySelector("#webgl");
// 定义屏幕尺寸大小
let size = {
width: window.innerWidth,
height: window.innerHeight
}
// 定义相机
let camera = new THREE.PerspectiveCamera(75, size.width / size.height);
camera.position.z = 3;
scene.add(camera);
// 定义渲染者
let renderer = new THREE.WebGL1Renderer({
canvas:canvas
})
renderer.setSize(size.width, size.height);
// 定义控制器
let controls = new OrbitControls(camera, canvas);
controls.enableDamping = true;
// 添加监听函数
document.addEventListener("resize", ()=>{
size = {
width:window.innerWidth,
height:window.innerHeight
}
renderer.setSize(size.width, size.height);
camera.aspect = size.width / size.height;
camera.updateProjectMatrix();
renderer.setPixelRatio(Math.min(window.devicePixelRatio), 2);
})
const tick = ()=>{
requestAnimationFrame(tick);
renderer.render(scene, camera);
}
tick();
}
}
</script>
<style scoped lang="scss">
</style>
效果图
比较有意思的一个3d库