_loadImg() {
if (this.imgLoading || this.loadImgQueue.length === 0) {
return;
}
let img = this.loadImgQueue.shift();
if (!img) {
return;
}
let $img = new Image(),
onLoad = e => {
$img.removeEventListener('load', onLoad, false);
this.$img = $img;
this.imgLoaded = true;
this.imgLoading = false;
this._initImg($img.width, $img.height);
this.$emit('loadSuccess', e);
this.$emit('loadComplete', e);
this._loadImg();
},
onError = e => {
$img.removeEventListener('error', onError, false);
this.$img = $img = null;
this.imgLoading = false;
this.$emit('loadError', e);
this.$emit('loadComplete', e);
this._loadImg();
};
this.$emit('beforeLoad');
this.imgLoading = true;
this.imgLoaded = false;
$img.src = this.img;
$img.crossOrigin = 'Anonymous'; //因为canvas toDataUrl不能操作未经允许的跨域图片,这需要服务器设置Access-Control-Allow-Origin头
$img.addEventListener('load', onLoad, false);
$img.addEventListener('error', onError, false);
}
_initImg(w, h) {
let eW = null,
eH = null,
maxW = this.cWidth,
maxH = this.cHeight - this.actionBarHeight;
//如果图片的宽高都少于容器的宽高,则不做处理
if (w <= maxW && h <= maxH) {
eW = w;
eH = h;
} else if (w > maxW && h <= maxH) {
eW = maxW;
eH = parseInt(h / w * maxW);
} else if (w <= maxW && h > maxH) {
eW = parseInt(w / h * maxH);
eH = maxH;
} else {
//判断是横图还是竖图
if (h > w) {
eW = parseInt(w / h * maxH);
eH = maxH;
} else {
eW = maxW;
eH = parseInt(h / w * maxW);
}
}
if (eW <= maxW && eH <= maxH) {
//记录其初始化的宽高,日后的缩放功能以此值为基础
this.imgStartWidth = eW;
this.imgStartHeight = eH;
this._drawImage((maxW - eW) / 2, (maxH - eH) / 2, eW, eH);
} else {
this._initImg(eW, eH);
}
}五、绘制图片
下面的_drawImage有四个参数,分别是图片对应cCanvas的x,y坐标以及图片目前的宽高w,h。函数首先会清空两个canvas的内容,方法是重新设置canvas的宽高。然后更新组件实例中对应的值,最后再调用两个canvas的drawImage去绘制图片。对于pCanvas来说,其绘制的图片坐标值为x,y减去对应的originXDiff与originYDiff(其实相当于切换坐标系显示而已,因此只需要减去两个坐标系原点的x,y差值即可)。看看代码
_drawImage(x, y, w, h) {










