- 頁面中加入組件
<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組件庫裏面有相應的組件可以更好的實現這個要求。