canvas 电子签名

canvas 电子签名

重绘,保存,移出,移入,点击

<template>
  <div style="width: 100%;height: 100%;display: flex;flex-direction: column">
    <div >
      <el-button @click="clearCanvas" size="mini">重绘</el-button>
      <el-button @click="saveSignature" size="mini">保存</el-button>
    </div>
    <canvas
      ref="canvas"
      :width="canvasWidth"
      :height="canvasHeight"
      @mousedown="startDrawing"
      @mousemove="draw"
      @mouseenter="inits"
      @mouseup="finishDrawing"
    ></canvas>
  </div>
</template>

<script>
export default {
  data() {
    return {
      canvasWidth: 480,
      canvasHeight: 300,
      drawing: false,
      signatureData: null
    };
  },
  mounted() {
    const canvas = this.$refs.canvas;
    this.ctx = canvas.getContext('2d');
    this.resetInit()
  },
  methods: {
    // 开始绘制签名
    startDrawing(event) {
      this.drawing = true;

      this.ctx.beginPath()
      const x = event.offsetX;
      const y = event.offsetY;
      this.ctx.moveTo(x, y);
    },
    // 绘制签名
    draw(event) {
      if (this.drawing) {
        const x = event.offsetX;
        const y = event.offsetY;
        this.ctx.lineTo(x, y);
        this.ctx.lineCap = "round";
        this.ctx.stroke();
      }
    },
    // 移出内容
    inits(){
      this.drawing = false
    },
    // 完成绘制签名
    finishDrawing() {
      this.drawing = false;
    },
    // 清除Canvas上的内容 清除上下文
    clearCanvas() {
      const canvas = this.$refs.canvas;
      // 重置上下文
      this.ctx = canvas.getContext('2d')
      this.ctx.clearRect(0, 0, this.canvasWidth, this.canvasHeight);
      this.resetInit()
      this.ctx.beginPath()
      this.signatureData = null
    },
    // 保存签名数据
    saveSignature() {
      this.signatureData = this.$refs.canvas.toDataURL();
      this.$emit("returnAutograph",this.signatureData)
    },
  //   设置默认底图
    resetInit(){
      this.ctx.beginPath()
      this.ctx.fillStyle = '#ccc'
      // 设置底图上下文
      this.ctx.fillRect(0,0,this.canvasWidth,this.canvasHeight)
      this.ctx.font = "48px serif";
      this.ctx.fillStyle =  '#000'
      this.ctx.strokeText("Hello world", 0, 0);
    }
  }
};
</script>

<style>

canvas{
  border: 1px solid #4C4C4C ;
}

</style>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值