【问题标题】:How to set up ThreeJS Scrollable plane in a React project?如何在 React 项目中设置 ThreeJS 可滚动平面?
【发布时间】:2022-01-02 06:40:19
【问题描述】:

我想使用 ThreeJS 创建一个具有左、右、上、下边缘的 2D 平面。相机不应该能够滚动超过这些界限。为什么 ThreeJS 用于只有 2D 平面的场景?因为我想使用着色器来绘制平面,并且最终可能会添加 3D 内容。

如何设置这样的场景?相机是否在飞机周围移动?飞机是否围绕相机移动?如何强制执行相机无法滚动过去的“有界边缘”?

最后,我是否需要使用 React-Three-Fiber,因为它将存在于 React 应用程序中?我试过只用 ThreeJS 设置场景,但我无法让我的控件按我想要的方式工作,我想知道我是否需要 React-Three-Fiber 来弥补差距。

【问题讨论】:

    标签: reactjs graphics three.js 2d react-three-fiber


    【解决方案1】:

    终于搞定了。使用 R3F 可能更容易,但我采用了 ThreeJS 方法,因为许多人似乎认为它提供了更大的灵活性。希望这对将来的某人有所帮助:

    import React, { useEffect, useRef } from "react";
    import * as THREE from "three";
    import {OrbitControls} from "three/examples/jsm/controls/OrbitControls";
    
    const Window = () => {
        const windowRef = useRef(null);
    
        const setupScene = () => {
            // renderer
            const renderer = new THREE.WebGLRenderer();
            renderer.setSize( window.innerWidth, window.innerHeight );
            windowRef.current.appendChild( renderer.domElement );
    
            // scene
            const scene = new THREE.Scene();
    
            // camera
            const camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
            camera.position.set(0,0,10);
        
            // controls
            const controls = new OrbitControls(camera, renderer.domElement);
            controls.target.set( 0, 0, 0 ); // view direction perpendicular to XY-plane
            controls.enableRotate = false;
            controls.enablePan = true;
            controls.mouseButtons = { LEFT: THREE.MOUSE.PAN };
            controls.minDistance = 1;
            controls.maxDistance = 100;
    
            const geometry = new THREE.PlaneBufferGeometry(100, 100, 10, 10);
            const material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
            const plane = new THREE.Mesh( geometry, material );
        
            scene.add( plane );
        
            const animate = function () {
                controls.update();
                requestAnimationFrame( animate );
                renderer.render( scene, camera );
            };
        
            animate();
    
            return () => windowRef.current.removeChild( renderer.domElement);
        };
    
        useEffect(setupScene);
    
        return (
            <div ref={windowRef} />
        );
    }
    
    export default Window;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-10-08
      • 2021-09-28
      • 2016-11-01
      • 2017-01-19
      • 2019-05-02
      • 2016-04-13
      相关资源
      最近更新 更多