ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-09-18 16:30:29  阅读:188  来源: 互联网

标签:Canvas dom 画板 代码 ctx canvas height width 签名


这里写目录标题

.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

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有