如何在 Gatsby 中实现 Three.js?

Posted

技术标签:

【中文标题】如何在 Gatsby 中实现 Three.js?【英文标题】:How to implement Three.js inside Gatsby? 【发布时间】:2020-06-04 09:08:12 【问题描述】:

我已经安装了 react-three-fiber三个 软件包。我正在关注this tutorial,但我怀疑这条线应该放在哪里:

const rootElement = document.getElementById("root");

另外,我开始收到此错误:

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object.

我的index.js

import React,  Children, useRef, useState  from "react"

import   Link  from "gatsby"

import  Canvas from 'react-three-fiber'

import Layout from "../components/layout"

const IndexPage = () => 

  return(

    <Layout>

      <div>

        <h1>Hi</h1>

      </div>

      <canvas>

        <Children></Children>

      </canvas>

    </Layout>

    )



const rootElement = document.getElementById("root");

export default IndexPage

有什么想法吗?

【问题讨论】:

【参考方案1】:

确保您已安装 threereact-three-fiber

npm install three react-three-fiber 

然后在您的 gatsby 页面组件中,只需从 react-three-fiber 导入 Canvas,然后在您的 JSX 中使用它。

import React from "react"
import  Canvas from 'react-three-fiber'

import Layout from "../components/layout"

const IndexPage = () => (
  <Layout>
    <Canvas />
  </Layout>
)

export default IndexPage

关于const rootElement = document.getElementById("root");

虽然Gatsby 是使用React 构建的,但它并不要求您选择根元素来呈现您的应用程序。如果这听起来令人困惑,您应该花一点时间来take a read of the Gatsby docs。


如果您要从 Gatsby 中的 react-three-fiber docs 构建示例,它看起来像这样。

import React,  useRef, useState  from "react"
import  Canvas, useFrame  from "react-three-fiber"

const Box = props => 
  // This reference will give us direct access to the mesh so we can animate it
  const mesh = useRef()

  // Set up state for the hovered and active state
  const [hovered, setHover] = useState(false)
  const [active, setActive] = useState(false)

  // Rotate mesh every frame, this is outside of React without overhead
  useFrame(() => (mesh.current.rotation.x = mesh.current.rotation.y += 0.01))

  return (
    <mesh
      ...props
      ref=mesh
      scale=active ? [1.5, 1.5, 1.5] : [1, 1, 1]
      onClick=e => setActive(!active)
      onPointerOver=e => setHover(true)
      onPointerOut=e => setHover(false)
    >
      <boxBufferGeometry attach="geometry" args=[1, 1, 1] />
      <meshStandardMaterial
        attach="material"
        color=hovered ? "hotpink" : "orange"
      />
    </mesh>
  )


const IndexPage = () => (
  <Canvas>
    <ambientLight />
    <pointLight position=[10, 10, 10] />
    <Box position=[-1.2, 0, 0] />
    <Box position=[1.2, 0, 0] />
  </Canvas>
)

export default IndexPage

【讨论】:

谢谢。我还发现这个视频没有使用那个“rootElement”。 youtube.com/watch?v=1rP3nNY2hTo 不幸的是,您所遵循的教程假设了很多现有的 react 和 threejs 知识。最重要的是,它根本没有提到盖茨比。

以上是关于如何在 Gatsby 中实现 Three.js?的主要内容,如果未能解决你的问题,请参考以下文章

Three.js铅笔手绘效果实现

three.js 入门详解

three.js 入门详解

三.js中的全局复合操作

Three.js杂记—— VR全景效果制作·中

在 Gatsby 中使用 Tailwind (SCSS)