4

three.js-设置renderTarget

 1 year ago
source link: https://www.msy.plus/2022/01/03/three-render-target-double-cube/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

three.js-设置renderTarget

发表于2022-01-02更新于2023-05-04字数统计381阅读次数67阅读次数4
threejs-logo.png

学习使用levaController

import {OrbitControls, GizmoHelper, GizmoViewport, Box} from '@react-three/drei';
import {Canvas, useFrame, createPortal} from '@react-three/fiber';
import React, {VFC, useMemo, useRef} from 'react';
import {createDOM} from '../lib/utils';
import * as THREE from 'three';
import ReactDOM from 'react-dom';

export const App: VFC = () => {
return (
<div style={{width: '100vw', height: '100vh'}}>
<Canvas
camera={{
position: [-2, 2, 3],
fov: 50,
aspect: window.innerWidth / window.innerHeight,
near: 0.1,
far: 2000,
}}
dpr={window.devicePixelRatio}
shadows>
<color attach="background" args={['#000']} />
<OrbitControls attach="orbitControls" />
<ambientLight intensity={0.1} />
<directionalLight intensity={1} position={[5, 5, 5]} />
<Cube />
<GizmoHelper alignment="bottom-left" margin={[100, 100]} onUpdate={() => {}}>
<GizmoViewport axisColors={['#f00', '#398400', '#00f']} labelColor="#fff" />
</GizmoHelper>
</Canvas>
</div>
);
};
const Cube: VFC = () => {
const {camera, scene, target} = useMemo(() => {
const camera = new THREE.PerspectiveCamera();
camera.position.set(0, 0, 3);
const scene = new THREE.Scene();
scene.background = new THREE.Color('orange');
const target = new THREE.WebGLRenderTarget(1024, 1024);
return {camera, scene, target};
}, []);

useFrame(({gl}) => {
gl.setRenderTarget(target);
gl.render(scene, camera);
gl.setRenderTarget(null);
});

return (
<>
{createPortal(<InnerCube />, scene)}
<Box args={[1, 1, 1]}>
<meshStandardMaterial map={target.texture} />
</Box>
</>
);
};
const InnerCube: VFC = () => {
const meshRef = useRef<THREE.Mesh>(null);

useFrame(() => {
meshRef.current!.rotation.x += 0.01;
meshRef.current!.rotation.y += 0.01;
meshRef.current!.rotation.z += 0.01;
});

return (
<Box ref={meshRef} args={[1, 1, 1]}>
<meshNormalMaterial />
</Box>
);
};

const div = createDOM();
ReactDOM.render(<App/>, document.body.appendChild(div));

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK