效果如下:
代码如下:
<!--
* @Author: {haoxian1990} 149322439@qq.com
* @Date: 2023-02-18 23:01:38
* @LastEditors: {haoxian1990} 149322439@qq.com
* @LastEditTime: 2023-02-25 11:07:48
* @Description:
-->
<template>
<div></div>
<div id="three-container"></div>
</template>
<script lang="ts" setup>
import { reactive, onMounted } from 'vue';
import * as THREE from 'three';
import initThree from '@/libs/three/initThree';
const state = reactive({});
onMounted(() => {
init();
});
function init() {
const { scene, camera, renderer } = initThree();
// 创建几何体
const positions = [
-5.0, -5.0, 0.0, -5.0, 5.0, 0.0, 5.0, 5.0, 0.0, 5.0, 5.0, 0.0, 5.0, -5.0,
0.0, -5.0, -5.0, 0.0,
];
const geometry = new THREE.BufferGeometry();
geometry.setAttribute(
'position',
new THREE.Float32BufferAttribute(positions, 3)
);
// 设置uv
const uvs = [0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0];
geometry.setAttribute('uv', new THREE.Float32BufferAttribute(uvs, 2));
// 创建材质
// const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const material = new THREE.ShaderMaterial({
side: THREE.DoubleSide,
vertexShader: `
varying vec2 vUv;
void main() {
vUv = uv;
vec4 modelPosition = modelViewMatrix * vec4(position, 1.0);
vec4 projectionPosition = projectionMatrix * modelPosition;
gl_Position = projectionPosition;
}
`,
fragmentShader: `
varying vec2 vUv;
void main() {
gl_FragColor = vec4(1.0,0.3, vUv.x, 1.0);
}
`,
});
// 创建网格
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);
}
</script>
<style scoped>
#three-container {
width: 100%;
height: 100%;
}
</style>