首页 > 解决方案 > 如何在不使用多个threejs上下文的情况下渲染多个场景

问题描述

我已经看过这个关于如何只使用一个threejs上下文和渲染器在多个画布上显示对象的教程,有没有办法将结果迁移到react-three-fiber。github上有一个多场景的例子,但这不是我想要的。

我想出了类似的东西:

import React, { useMemo, useEffect, useRef } from 'react';
import * as THREE from 'three';

function useRenderer() {
  const renderer = useMemo(() => {
    const canvas = document.createElement('canvas');
    return new THREE.WebGLRenderer({canvas, alpha: true})
  }, []);

  return renderer;
}

function Scene({ renderer }: any) {
  const ref = useRef<HTMLCanvasElement>(null);

  useEffect(() => {
    if (ref.current) {
      const {left, right, top, bottom, width, height} = ref.current.getBoundingClientRect();
      const isOffscreen = bottom < 0 || top > window.innerHeight || right < 0 || left > window.innerWidth;
      const ctx = ref.current.getContext('2d');

      if (ctx && !isOffscreen) {
        const rendererCanvas = renderer.domElement;

        if (rendererCanvas.width < width || rendererCanvas.height < height) {
          renderer.setSize(width, height, false);
        }

        // make sure the canvas for this area is the same size as the area
        if (ctx.canvas.width !== width || ctx.canvas.height !== height) {
          ctx.canvas.width = width;
          ctx.canvas.height = height;
        }

        renderer.setScissor(0, 0, width, height);
        renderer.setViewport(0, 0, width, height);

        // copy the rendered scene to this element's canvas
        ctx.globalCompositeOperation = 'copy';
        ctx.drawImage(
            rendererCanvas,
            0, rendererCanvas.height - height, width, height,  // src rect
            0, 0, width, height);                              // dst rect
      }
    }
  }, [ref, renderer])

  return <canvas ref={ref} />;
}

function App() {
  const renderer = useRenderer();

  return (
    <div>
      <Scene renderer={renderer} />
    </div>
  );
}

export default App;

但我觉得我已经脱离了 react 和 react-three-fiber,而且我不知道如何渲染我的场景的孩子。

有什么方法可以做到这一点而不会太脏?

标签: reactjstypescriptthree.jsreact-three-fiber

解决方案


推荐阅读