uniapp使用canvas电子签名

<template>
  <view class="draw-page">
    <view class="draw-content">
      <canvas
        style="width: 100%; height: 100%"
        ref="sign"
        canvas-id="sign"
        id="sign"
        disable-scroll
        @touchstart="touchstart"
        @touchmove="touchmove"
      ></canvas>
    </view>
    <view class="actions">
      <button @click="background()" type="warn">清空</button>
      <button @click="save" type="primary">保存</button>
    </view>
  </view>
</template>

<script>
export default {
  data() {
    return {
      lineColor: "#000", //线条颜色
      lineWidth: 2, //线条宽度
    };
  },
  onReady() {
    const ctx = uni.createCanvasContext("sign");
    this.ctx = ctx;
    this.ctx.setStrokeStyle(this.lineColor);
    this.ctx.setLineWidth(this.lineWidth);

    // 获取canvas的宽高
    const query = uni.createSelectorQuery().in(this);
    query.select("#sign").boundingClientRect();
    query.exec((res) => {
      if (res && res.length) {
        this.width = res[0].width;
        this.height = res[0].height;
        this.background();
      }
    });
  },
  methods: {
    save() {
      uni.canvasToTempFilePath({
        canvasId: "sign",
        success(res) {
          // h5 tempFilePath是base64
          const url = res.tempFilePath;
          console.log(url);
        },
        fail(err) {
          console.error(err);
        },
      });
    },
    /**设置背景色 */
    background(color = "#f8f8f8") {
      this.ctx.fillStyle = color;
      this.ctx.fillRect(0, 0, this.width, this.height);
      this.ctx.draw();
    },
    touchstart(e) {
      if (e.touches && e.touches.length) {
        const t = e.touches[0];
        this.mouseX = t.x;
        this.mouseY = t.y;
        this.pmouseX = this.mouseX;
        this.pmouseY = this.mouseY;
      }
    },
    /**触摸移动 */
    touchmove(e) {
      if (e.touches && e.touches.length) {
        const t = e.touches[0];
        this.pmouseX = this.mouseX;
        this.pmouseY = this.mouseY;
        this.mouseX = t.x;
        this.mouseY = t.y;
        this.draw();
      }
    },
    draw() {
      this.ctx.moveTo(this.pmouseX, this.pmouseY);
      this.ctx.lineTo(this.mouseX, this.mouseY);
      this.ctx.stroke();
      this.ctx.draw(true);
    },
  },
};
</script>

<style lang="scss">
.draw-page {
  height: 100vh;
  display: flex;
  flex-direction: column;
}

.draw-content {
  flex: 1;
}

.actions {
  display: flex;

  button {
    flex: 1;
  }
}
// #sign {
//   box-sizing: border-box;
//   border: 1px solid red;
// }
</style>

posted @ 2023-08-26 15:57  Ajanuw  阅读(33)  评论(0编辑  收藏  举报