问题描述
我目前正在使用Nuxt.js(使用TypeScript)创建一个个人投资组合网站。 我决定要在目标网页上使用Vanta.js Halo effect.,但似乎找不到找到使之正常工作的方法。
我尝试使用three.js和vanta npm软件包,但是会产生错误。 “无法读取未定义的属性”纹理”
import * as THREE from 'three'
import HALO from 'vanta/dist/vanta.halo.min.js'
...
*inside Vue.extend block*
mounted(){
this.vantaEffect = HALO({
el: '#landing',*rest of the settings*
THREE: THREE
})
}
有什么办法可以使它工作?
更新:
我设法使用静态文件摆脱了错误-this vanta repo issue中的方法,但是用于初始化的静态脚本找不到#landing元素。
/*nuxt.config.js*/
...
head: {
title: process.env.npm_package_name || '',meta: [
{ charset: 'utf-8' },{ name: 'viewport',content: 'width=device-width,initial-scale=1' },{
hid: 'description',name: 'description',content: process.env.npm_package_description || '',},],link: [{ rel: 'icon',type: 'image/x-icon',href: '/favicon.ico' }],script: [
{ src: 'vanta.halo.min.js' },{ src: 'three.min.js' },{ src: 'effect.js' },...
/*effect.js - file that initializes the effect*/
VANTA.HALO({
el: '#landing',mouseControls: true,touchControls: true,gyroControls: false,minHeight: 200.0,minWidth: 200.0,baseColor: 0xffffff,backgroundColor: 0x2d2d2d,THREE,})
更新2:
通过导出一个初始化效果并从mount()运行它并传递元素引用的函数,我设法解决了找不到#landing元素的问题。
/*effect.js*/
const vantaEffect = (elementRef) => {
return window.VANTA.HALO({
el: elementRef,THREE: THREE,})
}
export default vantaEffect
现在出现此错误:
[VANTA] Init error TypeError: Cannot read property 'LinearFilter' of undefined
解决方法
因此,我对劳伦斯提供的沙箱进行了一些修改,并使其能够像这样工作:https://codesandbox.io/s/winter-thunder-pffsq
基本上,发生的事情是Vanta假设在window
上设置了3个,当我们从npm导入它时不会发生。因此,在导入三个并将其设置为窗口变量之后,必须导入Vanta。
import * as THREE from "three";
// import HALO from "vanta/dist/vanta.halo.min";
export default {
async mounted() {
// window is only avaiable on browser
if (process.browser) {
window.THREE = THREE;
const { default: HALO } = await import("vanta/dist/vanta.halo.min");
HALO({
el: "#abc",mouseControls: true,touchControls: true,minHeight: 200.0,minWidth: 200.0,xOffset: -0.17,size: 2.1,THREE: window.THREE
});
}
}
};