业务场景

  • 用户在页面使用电子签名进行文件的签收与信息的确认

分析

  • 考虑用户会通过手机或者PC端进行操作,因此需要在事件中考虑手机端部分

思路

  • 通过一个对话框的形式利用Canvas生成图片并通过toDataURL()转换成Base64的形式保存下来提交给后端进行保存

最终效果

实际效果展示
组件效果
组件效果
电子签名

实现

export default {
  name: 'ESignature',
  data() {
    return {
      points: [],
      canvasTxt: null,
      stage_info: [],
      startX: 0,
      startY: 0,
      moveY: 0,
      moveX: 0,
      isDown: false,
      strokeStyle: '#000',
      lineWidth: 2
    }
  },
  mounted() {
    this.initCanvas()
  },
  methods: {
    // 初始化Canvas
    initCanvas() {
      let canvas = this.$refs.canvasF
      // 获取画布的高度
      canvas.height = this.$refs.canvasHW.offsetHeight - 20
      // 获取画布的宽度
      canvas.width = this.$refs.canvasHW.offsetWidth - 20
      // 创建 context 对象
      this.canvasTxt = canvas.getContext('2d')
      this.stage_info = canvas.getBoundingClientRect()
    },
    // 鼠标按下事件 - 准备绘画
    mouseDown(ev) {
      ev = ev || event
      ev.preventDefault()
      if (ev) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY
        }
        this.startX = obj.x
        this.startY = obj.y
        this.canvasTxt.beginPath()
        this.canvasTxt.moveTo(this.startX, this.startY)
        this.canvasTxt.lineTo(obj.x, obj.y)
        this.canvasTxt.stroke()
        this.canvasTxt.closePath()
        this.points.push(obj)
        this.isDown = true
      }
    },
    // 鼠标移动事件 - 开始绘画
    mouseMove(ev) {
      ev = ev || event
      ev.preventDefault()
      if (this.isDown) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY
        }
        this.moveY = obj.y
        this.moveX = obj.x
        this.canvasTxt.strokeStyle = this.strokeStyle
        this.canvasTxt.lineWidth = this.lineWidth
        this.canvasTxt.beginPath()
        this.canvasTxt.moveTo(this.startX, this.startY)
        this.canvasTxt.lineTo(obj.x, obj.y)
        this.canvasTxt.stroke()
        this.canvasTxt.closePath()
        this.startY = obj.y
        this.startX = obj.x
        this.points.push(obj)
      }
    },
    // 松开鼠标事件 - 停止绘画
    mouseUp(ev) {
      ev = ev || event
      ev.preventDefault()
      if (ev) {
        let obj = {
          x: ev.offsetX,
          y: ev.offsetY
        }
        this.canvasTxt.beginPath()
        this.canvasTxt.moveTo(this.startX, this.startY)
        this.canvasTxt.lineTo(obj.x, obj.y)
        this.canvasTxt.stroke()
        this.canvasTxt.closePath()
        this.points.push(obj)
        this.points.push({ x: -1, y: -1 })
        this.isDown = false
      }
    },
    // 返回
    handleGoBack() {
      this.handleOverwrite()
      this.$emit('on-back')
    },
    // 重写
    handleOverwrite() {
      this.canvasTxt.clearRect(0, 0, this.$refs.canvasF.width, this.$refs.canvasF.height)
      this.points = []
    },
  }
}
详情请看:Vue-电子签名(E-Signature)
Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐