需求:不断绘制图片、图形、文字等内容,达到实时视频效果。
思路:在使用fabric操作canvas,获取到新数据时先clear()清除画布内容,再add()绘制新的数据内容到画布上达到实时更新效果.
效果:更新内容时会出现闪屏
原因:clear()函数使用位置不对,
解决方法:clear()必须用在img.onload = () => {}函数之内,且add()绘画函数之前,就可以解决闪屏现象,放add()之后代表函数先执行add()绘制画布,再执行clear()清除画布内容,造成页面没有图像。
在mounted中定义画布
mounted() {
this.myCanvas = new fabric.Canvas("myCanvas");//初始化画布
}
绘制画布函数
videoInit(option) {
//动态设置红外画布的宽高
this.myCanvas.setDimensions({
width: this.cWidth,
height: (this.cWidth * 240) / 320,
});
//错误用法,clear()函数用在此处会闪屏
this.myCanvas.clear();//清空画布内容
let img = new Image();
img.src ="http://upload.dczn.com.cn/" + option.devSn +".jpg?"+new
Date().getMilliseconds();
img.onload = () => {
//绘制内容
let imgScale = this.cWidth / img.width;
let imgHScale = (this.cWidth * 240) / 320 / img.height;
let imgInstance = new fabric.Image(img, {
width: this.cWidth,
height: (this.cWidth * 240) / 320,
scaleX: imgScale,
scaleY: imgHScale,
textShadow: "80px #fff",
});
let devName = new fabric.Text(option.devSn, {
fontSize: 24,
fill: "#0276fb",
top: 2,
left: 10,
});
//合并需要绘制的内容
this.group = new fabric.Group(
[imgInstance, devName],
{
objectCaching: false,
}
);
// 正确用法,clear()函数用在此处避免闪屏
// this.myCanvas.clear(); // 清空画布前面绘制的内容
this.myCanvas.add(this.group);//绘制更新的内容至画布
};
},
实现效果:
ps:有点吐血,我网上找了一堆硬是没找到解决办法,估计使用fabric.js库的人少吧!倒是看到很多原生canvas使用双缓存解决闪屏问题,搞得我都想换回去了,结果想想不应该啊,按理说组件库当然比原生的更实用,自己捣鼓捣鼓就解决了,就一行代码位置问题,还是花了我好多时间,哈哈哈哈也算长见识了