代码
<template>
<div class="circle" ref="circle"></div>
</template>
<script setup>
import {onMounted, ref} from "vue";
import * as THREE from 'three';
import {OrbitControls} from 'three/examples/jsm/controls/OrbitControls'
let scene, camera, renderer, controls, circle = ref(null);
let timeValue = {value: 0.0}
function init() {
let width = circle.value.clientWidth;
let height = circle.value.clientHeight
scene = new THREE.Scene();
renderer = new THREE.WebGLRenderer({
antialias: true, //开启锯齿
});
renderer.setSize(width, height)
renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
renderer.setClearColor(new THREE.Color('#32373E'), 1);
camera = new THREE.PerspectiveCamera(45, width / height, 1, 10000)
camera.position.set(500, 500, 500)
controls = new OrbitControls(camera, renderer.domElement);
let light = new THREE.AmbientLight(0xadadad, 0.8); // soft white light
scene.add(light)
let light_2 = new THREE.HemisphereLight(0x00AAFF, 0xFFAA00, 0.8)
scene.add(light_2)
scene.add(new THREE.AxesHelper(500))
const geometry = new THREE.PlaneGeometry(500, 500);
geometry.translate(250, 250, 0)
geometry.rotateX(Math.PI/2)
const material = new THREE.MeshBasicMaterial({color: 0xffff00, side: THREE.DoubleSide});
let vertexShader = `
// uniform mat4 modelMatrix;//不需要声明
varying vec3 v_position;
void main(){
// 模型矩阵modelMatrix对顶点位置坐标进行模型变换
gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
v_position = position;
}`
let fragmentShader = `
varying vec3 v_position;
uniform float v_time;
void main() {
// 定义速度
float v = 2.0;
// 定义宽度
float w = v * v_time;
if (v_position.x <= w + 20.0 && v_position.x >= w-20.0) {
// 颜色插值计算
vec3 color = mix(vec3(1.0, 1.0, 0.0), vec3(1.0, 0.0, 0.0), abs(w-v_position.x)/20.0);
gl_FragColor = vec4(color, 1.0);
} else {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
}
`
let material2 = new THREE.ShaderMaterial({
vertexShader,
fragmentShader,
side: THREE.DoubleSide,
transparent: true,
uniforms: {
v_time: timeValue
}
})
const plane = new THREE.Mesh(geometry, material2);
scene.add(plane);
// plane.rotateX(Math.PI/2)
}
function animal() {
renderer.render(scene, camera);
timeValue.value += 0.5
if (timeValue.value >= 250) {
timeValue.value = 0.0;
}
requestAnimationFrame(animal)
}
onMounted(() => {
init();
circle.value.appendChild(renderer.domElement)
animal();
})
</script>
<style scoped lang="less">
.circle {
height: 100%;
}
</style>