0
点赞
收藏
分享

微信扫一扫

【NAS 折腾】个人音乐库解决方案-Music-Tag-Web

电子版签名效果

在这里插入图片描述

定义画布

    <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) //上传成功

    })
  })
},
举报

相关推荐

0 条评论