关于canvas:支付宝小程序-横屏电子版签字-canvas实现

3次阅读

共计 2037 个字符,预计需要花费 6 分钟才能阅读完成。

背景形容:业务须要在支付宝小程序横屏签字,然而目前支付宝不反对横屏,所以只能用款式疏导用户
实现成果:

思路:
应用 transform 和 translate 去旋转页面,这样就能满足款式的需要,看着是没啥问题,然而当在 canvas 上绘画的时候,就会看到,我写的是一横,展现确实是一竖
起因:页面是旋转了,然而坐标零碎没有扭转

解决方案:调整坐标零碎
可借由 rotate 逆向旋转 90°,而后由 translate 平移坐标系。

context.rotate((degree * Math.PI) / 180);
switch (degree) {
  // 页面顺时针旋转 90°后,画布左上角的原点地位落到了屏幕的右上角(此时宽高调换),围绕原点逆时针旋转 90°后,画布与原地位垂直,居于屏幕右侧,须要向左平移画布以后高度雷同的间隔。case -90:
    context.translate(-height, 0);
    break;
  // 页面逆时针旋转 90°后,画布左上角的原点地位落到了屏幕的左下角(此时宽高调换),围绕原点顺时针旋转 90°后,画布与原地位垂直,居于屏幕下侧,须要向上平移画布以后宽度雷同的间隔。case 90:
    context.translate(0, -width);
    break;
  // 页面顺逆时针旋转 180°回到了同一个地位(即页面倒立),画布左上角的原点地位落到了屏幕的右下角(此时宽高不变),围绕原点反方向旋转 180°后,画布与原地位平行,居于屏幕右侧的下侧,须要向左平移画布宽度雷同的间隔,向右平移画布高度的间隔。case -180:
  case 180:
    context.translate(-width, -height);
}

上面是我的代码:

<canvas ref="cxt" id="xfCanvas" class="xfcanvas" :style="{height: canvasw -52+'px', width:'100%'}"
      @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd" :disable-scroll="true">
    </canvas>
    <view class="btn">
      <view @click="resetImg"> 重签 </view>
      <view @click="goSignDate"> 下一步签日期 </view>
    </view>
    mounted() {
      let that = this;
      uni.getSystemInfo({success: function(res) {
          that.canvasw = res.windowWidth;
          that.canvash = res.windowHeight;
          console.log(that.canvasw, that.canvash, '画布尺寸');
          that.$nextTick(() => {that.ctx = uni.createCanvasContext('xfCanvas');
//======== 重点在这里  扭转坐标零碎,52 的高度是我操作按钮的高度 =============
            that.ctx.rotate((-90 * Math.PI) / 180); 
            that.ctx.translate(-that.canvash + that.canvasw + 52, 0)
            that.ctx.setStrokeStyle('#000'); // 色彩
            that.ctx.setLineWidth(8); // 粗细
            that.ctx.setLineCap('round'); // 线头形态
            that.ctx.setLineJoin('round'); // 交叉处形态
          });
        },
      });
    },

methods:{touchStart(e) {console.log('+++++++++++ 刚开始触摸');
        this.startX = e.changedTouches[0].x;
        this.startY = e.changedTouches[0].y;
        this.ctx.beginPath();
        this.ctx.moveTo(this.startX, this.startY); // 找到终点
      },
      touchMove(e) {console.log('+++++++++++ 触摸进行中');
        this.isSign = true
        let moveX = e.changedTouches[0].x;
        let moveY = e.changedTouches[0].y;
        this.ctx.lineTo(moveX, moveY); // 找到起点
        this.ctx.stroke(); // 描述门路
        this.ctx.draw(true, function(ret) {});
      },
      touchEnd() {
        this.isSign = true
        console.log('+++++ 完结啦', this.ctx);
      },}

最初实现成果


折腾了好一会,参考了大佬的文档,受益匪浅,原文链接:https://segmentfault.com/a/11…

正文完
 0