- 页面中加入组件
<canvas canvas-id="canvas" class="canvas" @touchstart="cas_start" @touchmove="cas_move" @touchend="cas_end"></canvas>
- onReady获取页面宽度,加入条件编译
onReady() { //#ifdef APP-PLUS this.canvasWidth = uni.getSystemInfoSync().windowWidth; this.cas_Drawer(this.canvasWidth,384,1); //#endif }
- methods对象中方法
cas_start(e){ console.log('触摸开始'); console.log(e) if(e.touches.length>1){//大于一的时候,可以判断是两个手指 this.startArr=e.touches; } }, cas_move(e){ console.log('触摸移动'); console.log(e) if(e.touches.length>1){ console.log(2); this.nowArr=e.touches; var scale=this.getDistance(this.nowArr[0],this.nowArr[1])/this.getDistance(this.startArr[0],this.startArr[1]); //得到缩放比例, if(scale!=1){ this.cas_Drawer(this.canvasWidth,384,scale); } var rotation=this.getAngle(this.nowArr[0],this.nowArr[1])-this.getAngle(this.startArr[0],this.startArr[1]); //得到旋转角度, } }, cas_end(e){ console.log('触摸结束'); console.log(e) }, getDistance(p1, p2) { var x = p2.x - p1.x, y = p2.y - p1.y; return Math.sqrt((x * x) + (y * y));//getDistance是勾股定理的一个方法,用于计算放大倍数 }, getAngle(p1, p2) { var x = p1.x - p2.x, y = p1.y - p2.y; return Math.atan2(y, x) * 180 / Math.PI;//getAngle是得到夹角的一个方法用于计算放大倍数 }, cas_Drawer(width,height,scale){ console.log(scale); let ctx = uni.createCanvasContext('canvas'); ctx.clearRect(0,0,width,height);//清除画布 ctx.drawImage('../../static/img/bg.jpg',0,0,width*scale,height*scale);//绘制图片 ctx.draw();//绘制图片 }
当前canvas方法主要是用于两个手指缩放图片大小,还有很多地方要改,uniapp组件库里面有相应的组件可以更好的实现这个要求。