基于Vue的移动端图片裁剪组件功能(3)
五、绘制图片
下面的_drawImage有四个参数,分别是图片对应cCanvas的x,y坐标以及图片目前的宽高w,h。函数首先会清空两个canvas的内容,方法是重新设置canvas的宽高。然后更新组件实例中对应的值,最后再调用两个canvas的drawImage去绘制图片。对于pCanvas来说,其绘制的图片坐标值为x,y减去对应的originXDiff与originYDiff(其实相当于切换坐标系显示而已,因此只需要减去两个坐标系原点的x,y差值即可)。看看代码
_drawImage(x, y, w, h) {
this._clearCanvas();
this.imgX = parseInt(x);
this.imgY = parseInt(y);
this.imgCurrentWidth = parseInt(w);
this.imgCurrentHeight = parseInt(h);
//更新canvas
this.ctx.drawImage(this.$img, this._ratio(x), this._ratio(y), this._ratio(w), this._ratio(h));
//更新pCanvas,只需要减去两个canvas坐标原点对应的差值即可
this.pCtx.drawImage(this.$img, this._ratio(x - this.originXDiff), this._ratio(y - this.originYDiff), this._ratio(w), this._ratio(h));
},
_clearCanvas() {
let $canvas = this.$refs.canvas,
$pCanvas = this.$refs.pCanvas;
$canvas.width = $canvas.width;
$canvas.height = $canvas.height;
$pCanvas.width = $pCanvas.width;
$pCanvas.height = $pCanvas.height;
}
六、移动图片
移动图片实现非常简单,首先给gesture-mask绑定touchstart,touchmove,touchend事件,下面分别介绍这三个事件的内容
首先定义四个变量scx, scy(手指的起始坐标),iX,iY(图片目前的坐标,相对于cCanvas)。
1、touchstart
方法很简单,就是获取touches[0]的pageX,pageY来更新scx与scy以及更新iX与iY
2、touchmove
获取touches[0]的pageX,声明变量f1x存放,移动后的x坐标等于iX + f1x - scx,y坐标同理,最后调用_drawImage来更新图片。
看看代码吧
_initEvent() {
let $gesture = this.$refs.gesture,
scx = 0,
scy = 0;
let iX = this.imgX,
iY = this.imgY;
$gesture.addEventListener('touchstart', e => {
if (!this.imgLoaded) {
return;
}
let finger = e.touches[0];
scx = finger.pageX;
scy = finger.pageY;
iX = this.imgX;
iY = this.imgY;
}, false);
$gesture.addEventListener('touchmove', e => {
e.preventDefault();
if (!this.imgLoaded) {
return;
}
let f1x = e.touches[0].pageX,
f1y = e.touches[0].pageY;
this._drawImage(iX + f1x - scx, iY + f1y - scy, this.imgCurrentWidth, this.imgCurrentHeight);
}, false);
}
七、缩放图片(这里不作特别说明的坐标都是相对于cCanvas坐标系)
绘制缩放后的图片无非需要4个参数,缩放后图片左上角的坐标以及宽高。求宽高相对好办,宽高等于imgStartWidth * 缩放比率与imgstartHeight * 缩放倍率(imgStartWidth ,imgstartHeight 上文第四节有提到)。接下来就是求缩放倍率的问题了,首先在touchstart事件上求取两手指间的距离d1;然后在touchmove事件上继续求取两手指间的距离d2,当前缩放倍率= 初始缩放倍率 + (d2-d1) / 步长(例如每60px算0.1),touchend事件上让初始缩放倍率=当前缩放倍率。
