在AR尝试(1)中实现了以摄像头为底,但是采用的方法是通过marginLeft来"裁"去左边,通过设置html左右不能滑动来"裁"去右边,但是video的实际宽度还是比window.innerWidth大的。
现在要实现对当前屏幕进行截图,第一想法就是通过canvas的drawImage方法来对屏幕进行裁剪,但是尝试了很多次,试过3、5、9个参数的,呈现效果均是让人匪夷所思。最后在一篇博文中看到,drawImage对于裁剪Image类型和Video类型,参数代表的含义是不一样的。QwQ
找到了病症之后又开始无尽的试试试…真没想到这个截图能卡住我1天半的时间,啊我好菜55555
最后实在受不了了,换了种方法,既然裁剪Video匪夷所思,既然裁剪Image可控。
那。。。
干脆就直接裁剪image吧。
先用一个canvas来把整个video给截下来,然后用另一个canvas来裁刚刚canvas转过来的image。
于是就
initCanvas() {
// this.canvasElement = document.createElement('canvas');
this.canvasElement = document.getElementById('canvas');
this.canvasElement.setAttribute('width', window.innerWidth.toString() + 'px');
this.canvasElement.setAttribute('height', window.innerHeight.toString() + 'px');
this.canvasContext = this.canvasElement.getContext('2d');
this.canvasElement2 = document.getElementById('canvas2');
this.canvasElement2.setAttribute('width', window.innerWidth + 'px');
this.canvasElement2.setAttribute('height', window.innerHeight+ 'px');
this.canvasContext2 = this.canvasElement2.getContext('2d');
// document.body.appendChild(this.canvasElement);
}
/**
* 截取摄像头图片
* @returns {HTMLImageElement}
*/
captureVideo() {
this.canvasContext.drawImage(this.videoElement,0,0,window.innerWidth,window.innerHeight); //把整个video截下来
let image_64 = this.canvasElement.toDataURL('image/jpeg');
let image = new Image();
image.src = image_64; //将canvas转成image类型
this.canvasElement.style.display = "none";
let newImagePromise = this.cutImage(image);
return newImagePromise;
}
这里发现,在cutImage()函数(下面给出)中因为图片加载的速度要慢于代码执行的速度,所以返回的裁剪完的image均是空的。试了网上常用的onload、设置延迟器的方法,结果均不太好用,因为我们需要return一张image回来,但是在onload里面return不是为该函数的返回,固我在外面套了一层promise,将整个promise返回,来获取里面的图片
cutImage(image){
let videoOffWidth = this.videoOffWidth;
let videoOffHeight = this.videoOffHeight;
let videoWidth = this.videoElement.offsetWidth;
let videoHeight = this.videoElement.offsetHeight;
let canvasElement2 = this.canvasElement2;
let canvasContext2 = this.canvasContext2;
return new Promise(function(resolve,reject){
image.onload = function(){
//this.canvasContext2.drawImage(image,0,0);
canvasContext2.drawImage(
image,
videoOffWidth / 2 / videoWidth * window.innerWidth,videoOffHeight / 2 / videoHeight * window.innerWidth,
window.innerWidth * window.innerWidth / videoWidth,window.innerHeight *window.innerHeight / videoHeight,
0, 0,
window.innerWidth,window.innerHeight);
let image_64_cut = canvasElement2.toDataURL('image/jpeg', 0.5);
let image_cut = new Image();
image_cut.src = image_64_cut;
resolve(image_cut);
};
});
}