Vue 使用Canvas画布手写电子版签名 保存 上传服务端

电子版签名效果

在这里插入图片描述

定义画布

    <canvas 
    width="500"
    height="250"
    ref="cn"
    @mousedown="cnMouseDown"
    @mousemove="cnMouseMove"
    @mouseup="cnMouseUp"
    style="width:500px;height: 250px;background-color:snow;padding: 10px">
    </canvas>

canvas 的width height两个属性表示画布的大小,style的width height为实际的内容大小

是否可绘制

data() {
    return {
      pen:false //是否可以绘画
    };
  },

获取鼠标按下事件

 cnMouseDown(e){
      this.pen=true //鼠标按下可绘画
      const canvas= this.$refs.cn //获取对象
      
      const p =canvas.getContext('2d') //绘画2D图 画笔
      
      //this.p.fillStyle = '#d3d3d3'; 画布的颜色 不设置保存时为透明
      //this.p.fillRect(0, 0, this.canvas.width, this.canvas.height) //填充整个画布

      let x =e.pageX-canvas.offsetLeft //鼠标在画布的X
      let y =e.pageY-canvas.offsetTop  //鼠标在画布的Y
      
      p.moveTo(x,y)//移动画笔到 鼠标位置 断开线段
      p.lineTo(x,y) //画线
      p.stroke() //绘制轮廓 (线)

      this.p=p //全局挂载 其他事件需要使用到 画笔
      this.canvas=canvas //全局挂载 其他事件需要使用到 画布
    },

鼠标移动事件

cnMouseMove(e){
if(this.pen)
{
  let x=e.pageX-this.canvas.offsetLeft //移动的距离X
  let y =e.pageY-this.canvas.offsetTop //移动的距离Y

  let w =this.canvas.width //画布高度
  let h =this.canvas.height //画布宽度

  if(x+10>w||x<10||y+10>h||y<10){
    this.pen=false
    return
    //鼠标移出画布 停止绘制
  }

  this.p.lineTo(x,y) //鼠标移动持续绘制
  this.p.stroke() //绘制轮廓 (线)
}

鼠标松开事件

 cnMouseUp(){
      this.pen=false
      //鼠标双开 停止绘画
    },

保存签名

 save(){
      const url =this.canvas.toDataURL() //转换成链接
      const a =document.createElement('a') //创建A标签
      a.download='手写签名' //文件名字
      a.href=url //赋值
      a.click() //点击事件 打开下载对话框
    }

在这里插入图片描述

清空画布

 clear(){
      this.p.clearRect(0,0,this.canvas.width,this.canvas.height)
    },

上传服务端

接口封装

import request from '@/utils/request'
export function  fileUp(data){
  return request({
    method:'POST',
    url:'/fileUpload',
    data
  })
}

上传

up(){
  this.canvas.toBlob(b=>{ //转成二进制 成功的回调
  
    const formData = new FormData();//表单
   
    formData.append('file', b, 'filename.png'); //file为上传时的参数名

    fileUp(formData).then(r=>{
      console.log(r) //上传成功

    })
  })
},

相关推荐

  1. 微信小程序canvas签字

    2024-04-27 07:56:06       30 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-04-27 07:56:06       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-04-27 07:56:06       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-04-27 07:56:06       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-04-27 07:56:06       18 阅读

热门阅读

  1. vue 实现 下拉触底事件

    2024-04-27 07:56:06       14 阅读
  2. Ubuntu: 自留小技巧

    2024-04-27 07:56:06       13 阅读
  3. npm镜像切换

    2024-04-27 07:56:06       11 阅读
  4. 基于协同过滤算法的旅游推荐系统设计与实现

    2024-04-27 07:56:06       13 阅读
  5. 如何使用逆滤波算法deconvwnr恢复图像

    2024-04-27 07:56:06       15 阅读
  6. 优化SQL的方法

    2024-04-27 07:56:06       12 阅读