three.js vue3封装贴图循环偏移案例

发布于:2024-04-30 ⋅ 阅读:(40) ⋅ 点赞:(0)

以上是代码实现效果。本篇文章主要讲述vue3对代码的封装,以及如何让图片循环播放。

封装主要分三步:

1、封装实例化模块;2、封装渲染;3、偏移量操作。

具体的代码如下:

<script setup>
import * as THREE from 'three'

import {  onMounted, ref } from 'vue';
const containerRef = ref()
let camera, scene, renderer, mesh, texture = null, geometry, material, loader, para = { repeat: 1, wrap: 1, offsetX: 0, offsetY: 0 }, gui, parameter;
let width = 500,height = 500
const initData = () => {
    scene = new THREE.Scene();

    camera = new THREE.PerspectiveCamera(70, width / height, 1, 1000);
    camera.position.z = 400;

    renderer = new THREE.WebGLRenderer({alpha:true});
    renderer.setSize(width, height);
    containerRef.value.appendChild(renderer.domElement);

    geometry = new THREE.PlaneGeometry(500, 300, 1, 1);
    //贴图
    loader = new THREE.TextureLoader()
    loader.load(
        'src/assets/img/girl/7.png',
        function (text) {
            texture = text;
            material = new THREE.MeshBasicMaterial({
                map: texture
            });
            mesh = new THREE.Mesh(geometry, material);
            scene.add(mesh);
        },
        function (xhr) {
            console.log((xhr.loaded / xhr.total * 100) + '% loaded');
        },
        function (xhr) {
            console.log('An error happened');
        }
    );
}

//玄幻渲染
const animate =  ()=> {
    change();
    requestAnimationFrame(animate);
    renderer.render(scene, camera);
}

function change() {
    if (texture != null) {
        //贴图在滚动
        texture.repeat.x = texture.repeat.y = para.repeat;
        //x轴偏移
        texture.offset.x += 0.01;
        //y轴偏移
        // texture.offset.y += 0.01;

        if (para.wrap == 1) {
            texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
        } else if (para.wrap == 2) {
            texture.wrapS = texture.wrapT = THREE.ClampToEdgeWrapping;
        } else if (para.wrap == 3) {
            texture.wrapS = texture.wrapT = THREE.MirroredRepeatWrapping;
        }
        texture.needsUpdate = true;
    }
}

onMounted(() => {
    initData()
    animate();
})


</script>

<template>
    <main class="containBox">
        <div ref="containerRef" class="threeBox"></div>
    </main>
</template>
<style  lang="less" scoped>
.containBox {
    background-color: #95e4e8;
    min-width: 100vw;

    .threeBox {
        width: 500px;
        height: 500px;
        margin: 0 auto;
        margin-top: 200px;
    }
}
</style>

爬坑是一场没有终点的旅程,只有不断前行,才能看到更广阔的风景


网站公告

今日签到

点亮在社区的每一天
去签到