其他分享
首页 > 其他分享> > Canvas实现画板功能(可做签名板)

Canvas实现画板功能(可做签名板)

作者:互联网

这里写目录标题

.vue文件中的代码

html代码

<template>
  <div class="sign" id="sign">
    <div class="signButton">
      <el-button @click="clearSign">清除</el-button>
      <el-button type="primary" @click="click">完成</el-button>
    </div>
  </div>
</template>

methods代码

	init(){
      const dom = document.getElementById("sign")
      this.width = dom.clientWidth
      this.height = dom.clientHeight
      this.canvas = document.createElement("canvas")
      this.canvas.id = "canvas"
      this.canvas.addEventListener("mousedown",this.mousedown)
      this.canvas.addEventListener("mouseup",this.mouseup)
      this.canvas.addEventListener("mousemove",this.mousemove)
      this.canvas.width = this.width
      this.canvas.height = this.height
      dom.appendChild(this.canvas)
      this.ctx = canvas.getContext("2d")
      this.ctx.fillStyle = "#fff";
      this.ctx.fillRect(0, 0, this.width, this.height)
    },
    mousedown(e){
      this.ctx.beginPath()
      this.ctx.moveTo(e.offsetX,e.offsetY)
      this.flag = true
    },
    mouseup(e){
      this.ctx.lineTo(e.offsetX,e.offsetY);
      this.ctx.stroke();
      this.flag = false
    },
    mousemove(e){
      if(this.flag){
        this.ctx.lineTo(e.offsetX,e.offsetY);
        this.ctx.stroke();
      }
    },
    click(){
      this.canvas.toBlob(function(blob){
        console.log(blob)
      })
      const dataBase64 = this.canvas.toDataURL('image/png')
      console.log(dataBase64)
    },
    clearSign(){
      this.ctx.clearRect(0,0,this.width,this.height)
    }

mounted()代码

this.init()

style中的代码

<style lang="scss" scoped>
.sign{
  width: 100%;
  height: 100%;
  .signButton{
    position: absolute;
    bottom: 10px;
    right: 10px;
  }
}
</style>

最后

点击提交后可以生成Blob形式的文件,也可以生成base64内容的图片格式。

标签:Canvas,dom,画板,代码,ctx,canvas,height,width,签名
来源: https://blog.csdn.net/yue_xingfu/article/details/120369759