2

我一直在尝试使用 react-three-fiber 将 GLTF 模型加载到我的 gatsby 站点中,但似乎无法加载它。这看起来应该很简单,但我是 Gatsby 和 Threejs 的新手,想知道是否可以得到一些指导。

我的模型存储为 static/models/crerar.glb,我使用 gltfjsx 生成了一个模型组件。我试过只引用'models/crerar.glb',但也没有运气。

在 index.js 中,我有:

import Layout from "../components/layout"
import SEO from "../components/seo"
import React, { Suspense, useRef, useState } from "react"
import { Canvas, useFrame, useLoader } from "react-three-fiber"
import Model from "../components/Crerar"

const IndexPage = () => (
<Layout>
  <Canvas>
    <ambientLight intensity={0.2} />
    <Model />
  </Canvas>
</Layout>
)

export default IndexPage

在 Crerar.js 中(存储在组件中)

/*
auto-generated by: https://github.com/react-spring/gltfjsx
*/

import * as THREE from 'three'
import React, { useRef } from 'react'
import { useLoader } from 'react-three-fiber'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader'

export default function Model(props) {
  const group = useRef()
  const { nodes, materials } = useLoader(GLTFLoader, '../static/models/crerar.glb')
  return (
    <group ref={group} {...props} dispose={null}>
      <mesh material={nodes.mesh_0.material} geometry={nodes.mesh_0.geometry} />
    </group>
  )
}

4

2 回答 2

2

路径是错误的。您得到的 json.parse 错误是因为加载程序尝试将 HTML 404 提取错误解析为 GLTF。您可以通过打开开发工具和网络选项卡来确保。您应该看到它正在尝试访问您的文件,但不能。

如果模型在您的 src 文件夹中,您必须先导入它,然后使用您获得的散列 URL。这是我的建议,不要乱用公共文件,总是导入你的东西。它更安全,如果文件不存在,编译器会抱怨,并且更好地用于缓存控制。

否则,如果文件在 /public 中,或者我猜它是 gatsby 中的 /static(?),那么 url 必须类似于“/file.glb”。有时它是 /public/file.glb 或 /static/file.glb,这取决于您的捆绑环境(您可以尝试通过浏览器的 url 栏获取文件,如果 url 有效,那是您应该传递给加载器的那个)。

如果您的文件是 draco 压缩的,那么 draco 也必须在公共或静态内部。见:https ://codesandbox.io/s/r3f-ibl-envmap-simple-y541h

您可以安全地使用 useLoader(GLTFLoader, url),它只是new GLTFLoader().load(url, data => ...)+ suspense 的包装。它不再是实验性的,即使它可能在 Github 上有警告。

于 2020-07-20T08:29:57.873 回答
0

gatsby 将所有内容从静态复制到公用文件夹中,因此将您的 url 更改为:

const { nodes, materials } = useLoader(GLTFLoader, '/models/crerar.glb')

于 2021-04-05T20:12:05.690 回答