• canvas实现电子签名后台保存到服务器


    1、引入js:

    <script type="text/javascript" src="js/libs/esign.js"></script>
    <script type="text/javascript" src="js/libs/html2canvas.min.js"></script>
    

      注:html页面需要的js请自行引入;

    2、html页面:

    <div id="editing_area" style=" 100%;height: 50%;border: 2px dotted silver;border-radius:25px;background:url('images/sign/sign.jpg')" >
      <canvas id="canvasEdit" style=" 100%;height: 100%;"></canvas>
    </div>
    <div class="hw-options text-center">
      <a id="sign_clear" class="hw-btn" >清  除</a>
      <a id="sign_confirm" class="hw-btn" >确  定</a>
    </div>
    

    3、js

    根据书写路径绘制图片并调接口传递到后台:

    function confirmSign() {
            html2canvas(document.querySelector("#canvasEdit"),{useCORS: true}).then(function(canvas) {
              canvas = document.getElementById("canvasEdit");
              //判断用户是否签名
              if(isCanvasBlank(canvas)){
            	alert("请签名!");
            	return;
              }

         $.ajax({
           url: "http://localhost:8080/jiemian/saveImg",
           type:'post',
           data: { pp: b64},
           success:function ()  
                 {  
                   alert('保存成功');  
                 }  
         });  

            //前端下载图片到本地	
    //       downloadCanvasIamge(canvas);
      });
    };
    //验证canvas画布是否为空函数
    function isCanvasBlank(canvas) {
      // canvas = document.getElementById("canvasEdit");
      var blank = document.createElement('canvas');//系统获取一个空canvas对象
      blank.width = canvas.width;
      blank.height = canvas.height;
    
      //比较值相等则为空
      return canvas.toDataURL() == blank.toDataURL();
    
    }
    
    //下载Canvas元素的图片
    function downloadCanvasIamge(canvas, name) {
      // 通过选择器获取canvas元素
      canvas = document.querySelector("#canvasEdit")
      // 使用toDataURL方法将图像转换被base64编码的URL字符串,0.4为图片质量
      var url = canvas.toDataURL('image/png',0.4)
      // 生成一个a元素
      var a = document.createElement('a')
      // 创建一个单击事件
      var event = new MouseEvent('click')
    
      // 将a的download属性设置为我们想要下载的图片名称,若name不存在则使用‘下载图片名称’作为默认名称
      a.download = name || '下载图片名称'
      // 将生成的URL设置为a.href属性
      a.href = url
    
      // 触发a的单击事件
      a.dispatchEvent(event)
    }
    

      

    4、后台代码

    String imageDataUrl = req.getParameter("pp");
    BASE64Decoder decoder = new BASE64Decoder();    
    byte[] b = decoder.decodeBuffer(imageDataUrl);    
    ByteArrayInputStream bais = new ByteArrayInputStream(b);
    BufferedImage bi1 = ImageIO.read(bais);
    File w2 = new File("D://test.png");
    ImageIO.write(bi1, "png", w2);
    

      

  • 相关阅读:
    572.Subtree of Another Tree
    35.Search Insert Position(二分查找)
    198.House Robber(dp)
    724.Find Pivot Index
    705.Design HashSet
    求连通分量(深搜)
    删边(normal)
    叠放箱子问题
    数字游戏
    火车票
  • 原文地址:https://www.cnblogs.com/lychee-wang/p/14554875.html
Copyright © 2020-2023  润新知