canvas手写签名组件

效果图👇
在这里插入图片描述
代码不多直接粘在这里

<template>
  <div class="border">
    <canvas
      ref="canvas"
      width="800"
      height="500"
      class="border-success"
      tabindex="0"
      @mousedown="onMouseDown"
    />
    <footer slot="footer" class="dialog-footer text-center">
      <button type="danger" @click.native.prevent="clearPanel">清空</button>
      <button type="primary" @click="confirm">确认</button>
    </footer>
    <img class="imgCanvas" :src="imgUrl" />
  </div>
</template>

<script>
import { defineComponent, ref, nextTick } from "vue";
export default defineComponent({
  name: "environAmbitus",
  setup() {
    const canvas = ref(null);
    const imgUrl = ref();

    // 开始签名
    function onMouseDown(e) {
      const el = e.target || e.srcElement; //获取事件源
      const ctx = el.getContext("2d"); //获取canvas的上下文
      ctx.lineWidth = 3; //线条宽度
      ctx.beginPath(); //开始路径绘制
      ctx.moveTo(e.offsetX, e.offsetY); //设置路径起点,坐标为(20,20)
      ctx.lineTo(e.offsetX, e.offsetY); //设置路径终点,坐标为(200,20)
      ctx.stroke(); //图形边框绘制
      el.onmousemove = function(e) {
        //鼠标移动事件
        if (e.which === 0) {
          el.onmousemove = null;
          el.onmouseup = null;
          return;
        }
        ctx.lineTo(e.offsetX, e.offsetY);
        ctx.stroke();
      };
      // el.onmouseup = function () {
      //   //鼠标抬起事件
      //   el.onmousemove = null;
      //   el.onmouseup = null;
      // };
      el.focus();
    }

    // 清空签名
    function clearPanel(e) {
      nextTick(() => {
        // const el = canvas;
        const ctx = canvas.value.getContext("2d");
        ctx.clearRect(0, 0, canvas.value.width, canvas.value.height);
      });
    }

    // 确认签名
    function confirm() {
      nextTick(() => {
        try {
          // const canvas = this.$refs["canvas"];
          const blank = document.createElement("canvas"); // 创建一个空canvas对象
          blank.width = canvas.value.width;
          blank.height = canvas.value.height;
          imgUrl.value = canvas.value.toDataURL();// 将画布上的内容导出为图片
        } catch (e) {
          console.warn(e);
        }
      });
    }
    return { onMouseDown, confirm, clearPanel, canvas, imgUrl };
  }
});
</script>
<style scoped>
.border {
  width: 800px;
  height: 500px;
  border: 1px solid skyblue;
  box-sizing: border-box;
}
</style>

需要注意的是 可绘制区域是canvas的height width控制的,用的话可以给他改成父组件传递的

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值