three.js-设置renderTarget

学习使用levaController

源码

jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
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));