【问题标题】:How to add a jsx component inside a react-three-fiber canvas?如何在反应三纤维画布内添加 jsx 组件?
【发布时间】:2021-12-15 12:14:38
【问题描述】:

我想在 react-three-fiber 画布中插入一个 jsx 组件。有办法吗?

我已经创建了一个官方示例,它具有无限滚动。每个元素都是来自@react-three/drei 的图像。假设我有一个组件数组。如何定位它们以达到相同的效果?

代码是:

import { Suspense, useRef } from 'react'
import { Canvas, useThree } from '@react-three/fiber'
import { ScrollControls, Scroll, Preload, Image as ImageImpl } from '@react-three/drei'

function Image(props) {
  const ref = useRef()
  const group = useRef()

  return (
    <group ref={group}>
      <ImageImpl ref={ref} {...props} />
    </group>
  )
}
function Card() {
  return (
    <div style={{ background: '#red', width: 200, height: '100%', borderRadius: 8 }}>
      <h3>hello world</h3>
      <p>great text here!</p>
    </div>
  )
}

function Page({ m = 0.4, urls, ...props }) {
  const { width } = useThree((state) => state.viewport)
  const w = width < 10 ? 1.5 / 3 : 1 / 3
  return (
    <group {...props}>
      <Image position={[-width * w, 0, -1]} scale={[width * w - m * 2, 5, 1]} url={urls[0]} />
      <Image position={[0, 0, 0]} scale={[width * w - m * 2, 5, 1]} url={urls[1]} />
      <Image position={[width * w, 0, 1]} scale={[width * w - m * 2, 5, 1]} url={urls[2]} />
    </group>
  )
}

function Pages() {
  const { width } = useThree((state) => state.viewport)
  return (
    <>
      <Page position={[-width * 1, 0, 0]} urls={['/trip1.jpg', '/trip2.jpg', '/trip3.jpg']} />
      <Page position={[width * 0, 0, 0]} urls={['/img1.jpg', '/img2.jpg', '/img3.jpg']} />
      <Page position={[width * 1, 0, 0]} urls={['/img4.jpg', '/img5.jpg', '/img6.jpg']} />
      {/* INSERT JSX COMPONENT HERE */}
      {/* <Card />*/}
      <Page position={[width * 2, 0, 0]} urls={['/trip1.jpg', '/trip2.jpg', '/trip3.jpg']} />
      <Page position={[width * 3, 0, 0]} urls={['/img1.jpg', '/img2.jpg', '/img3.jpg']} />
      <Page position={[width * 4, 0, 0]} urls={['/img4.jpg', '/img5.jpg', '/img6.jpg']} />
    </>
  )
}

export default function App() {
  return (
    <Canvas gl={{ antialias: false }} dpr={[1, 1.5]}>
      <Suspense fallback={null}>
        <ScrollControls infinite horizontal damping={4} pages={4} distance={1}>
          <Scroll>
            <Pages />
          </Scroll>
        </ScrollControls>
        <Preload />
      </Suspense>
    </Canvas>
  )
}

这里也是codesandbox。谢谢!

【问题讨论】:

    标签: reactjs canvas three.js react-three-fiber


    【解决方案1】:

    r3f 是一个渲染器,canvas 里面的所有东西都渲染成threejs。画布内的“div”与“new THREE.Div()”相同,并且不存在。就像你试图写一个内部的 react-dom 一样。您可以在 canvas 元素之前或之后添加 html。您也可以将其包含在其中,但只能通过使用诸如 drei/Html 之类的帮助程序将 html 与网格或组的下落联系起来。查看示例,该用例有很多:https://docs.pmnd.rs/react-three-fiber/getting-started/examples

    【讨论】:

      猜你喜欢
      • 2021-07-10
      • 2021-08-18
      • 2021-10-18
      • 2021-08-01
      • 2022-12-23
      • 2021-08-09
      • 1970-01-01
      • 2021-04-18
      • 2021-07-11
      相关资源
      最近更新 更多