我正在尝试使用vanta使用 next.js,遵循此 guide 。它与网络效应完全兼容,但是,当我尝试使用地球效应时,我得到了
[VANTA] Init error TypeError: r.Geometry is not a constructor
at h.onInit (vanta.globe.min.js:1)
at h.init (vanta.globe.min.js:1)
at new r.VantaBase (vanta.globe.min.js:1)
at new h (vanta.globe.min.js:1)
at r.<computed> (vanta.globe.min.js:1)
我已将 Vanta 隔离到后台组件
//Background.js
import { useState, useRef, useEffect } from "react";
import NET from "vanta/dist/vanta.globe.min"
import * as THREE from "three";
export default function Background({ width, height, children }) {
const [vantaEffect, setVantaEffect] = useState(0);
const vantaRef = useRef(null);
useEffect(() => {
if (!vantaEffect) {
setVantaEffect(
NET({
THREE,
el: vantaRef.current,
})
);
}
return () => {
if (vantaEffect) vantaEffect.destroy();
};
}, [vantaEffect]);
return (
<div ref={vantaRef}>{children}</div>
)
}
并将三个脚本添加到我的 _app.js
import '../styles/globals.css'
import Head from "next/head";
import Navbar from "../components/Navbar";
import { useEffect } from "react";
export default function App({ Component, pageProps }) {
useEffect(() => {
const threeScript = document.createElement("script");
threeScript.setAttribute("id", "threeScript");
threeScript.setAttribute(
"src",
"https://cdnjs.cloudflare.com/ajax/libs/three.js/r121/three.min.js"
);
document.getElementsByTagName("head")[0].appendChild(threeScript);
return () => {
if (threeScript) {
threeScript.remove();
}
};
}, []);
return (
<>
<Head>
<title>BrainStorm Tutoring</title>
</Head>
<Navbar />
<Component {...pageProps} />
</>
)
}
并像这样使用它
//index
import Background from "../components/Background";
export default function Home() {
return (
<Background height="400" width="400">
<h1 className="text-white text-8xl text-left p-36">Fish Bowl</h1>
</Background >
)
}
是THREE有问题,还是next.js不支持vanta?
最佳答案
我对 Halo 有这个问题,所以我认为这三个对象不可用或未在 HALO.js 文件中定义。
所以我去了Vanta的官方github仓库并获取了Halo和Net(教程效果)文件的源代码,我发现Halo文件中缺少构造函数。所以我把 Net 的一个放入 Halo 文件中。
constructor(userOptions) {
THREE = userOptions.THREE || THREE;
super(userOptions);
}
然后我导入我的自定义 Halo 文件以获得效果并且它起作用了。
关于javascript - 如何将 vanta 与 nextjs 一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67548895/