在vue项目中使用canvas-nest.js,报parameter 1 is not of type 'Element'

时间:2023-03-09 20:02:38
在vue项目中使用canvas-nest.js,报parameter 1 is not of type 'Element'

canvas-nest.js是一款轻量的网页特效,如图:

在vue项目中使用canvas-nest.js,报parameter 1 is not of type 'Element'

github地址:https://github.com/hustcc/canvas-nest.js

在普通的html项目中,只要将<script src="dist/canvas-nest.js"></script>插入到body标签最下边即可。

在vue项目中,使用时配置

 import CanvasNest from 'canvas-nest.js';

 const config = { // 配置
color: '255, 0, 0', // 线条颜色
pointColor: '255, 155, 0', // 节点颜色
opacity: 1, // 线条透明度
count: 222, // 线条数量
zIndex: 99 // 画面层级
}; // Using config rendering effect at 'element'.
// element为html的dom对象,如id为body的dom为:document.getElementById('body');
const cn = new CanvasNest(element, config); // destroy
cn.destroy();

但是在vue项目中,引入canvas-nest.js后,直接在created中 new CanvasNest(element, config);的话,可能会报下图的错误,不显示效果

在vue项目中使用canvas-nest.js,报parameter 1 is not of type 'Element'

原因是dom没有渲染完毕,就开始使用element。

解决办法:在created中

 this.$nextTick(()=> {
const cn = new CanvasNest(element, config);
})

这样写一个延时操作就可以了,当然也可以使用setTimeout。

总结,遇到parameter 1 is not of type 'Element' 这样类型的报错,需要检查dom是否渲染完毕。