Handwritten signature plug-in - using experience of jSignature

Recently, we need to do a function of handwritten signature on the mobile terminal. After searching the Internet, it's basically the jSignature plug-in. There's almost no second choice. So we can follow the copy test of various versions on the Internet. It's easy to test on the PC terminal.

However, after the mobile terminal changed the size of the canvas's parent box, there was a problem. The handwritten and displayed ones were not together, and the jSignature brush was offset. After reviewing the elements, it was found that the size of the canvas changed to 100%. The solution was to manually set the size of the canvas. If the relative units of 100% and rem were used, there would be a problem If it needs to be responsive, it should be written in the media query. If it needs to be controlled by js, it needs to set canvas.attr("width","200") and take care not to bring units!!

The following is the signature display and upload to Alibaba cloud OSS code. If you need to see the parameters of jSignature, baidu simple version can.
<script type="text/javascript">     
        $(function () {
            $.ajaxSetup({
                async:false
            });
            window.canvasIsEmpty = "Y"//It is used to determine whether there is a handwritten signature. It is empty by default. When the brush is turned on in unsigned.jSignature.js, this value will be changed.
            var sigdiv = $("#signature");
            sigdiv.jSignature('init',{height:'100%',width:'100%',color:"#000",lineWidth:10});

            $("#closeSign").on("click",function(){
                reset();                
                $("#signWrap").removeClass("flex disable-touch");
            });

            //Click the picture and prompt text of the signature to pop up the picture board of the signature
            $("#imageViewBox").on("click","#user_sign_img,#user_sign_tips",function(){
                 getOSSAuth();
                 $("#loadingStatus").css({"width":"0"});//Zero progress bar
                 $("#loadingStatus span").text("");//Clear progress display text
                 $("#signWrap").addClass("flex disable-touch");                 
            });

            //Clear history signature, delete from OSS
            $("#imageViewBox").on("click","#user_sign_delete",function(){
                $.post("OSSAuth/yjsigndel.shtml",{basename:basename},function(res){
                    layer.msg("Electronic signature deleted");
                    $("#user_sign_img").attr("src","image/sign_img_default.jpg");
                    $("#user_sign_delete").hide();
                    $("#user_sign_tips").show();
                })
            })

            $("#myShare,#myPatient,#mySst,.store,.sign-in-day").on("click",function(){layer.msg("Coming soon")})

        });

        function reset() {
            var $sigdiv = $("#signature");
            $sigdiv.jSignature("reset");
            if(window.canvasIsEmpty === "Y"){$("#signWrap").removeClass("flex");}
            window.canvasIsEmpty = "Y";
        }

        //Monitor signature action and show preview
        function jSignature_img() {
            if(window.canvasIsEmpty === "Y"){
                layer.msg("Please sign your name.");
                return false;
            } 
            var $sigdiv = $("#signature");
            var datapair = $sigdiv.jSignature("getData", "image"); //Set the format of the output. Please refer to the official documents for details
            var i = new Image();
            i.src = "data:" + datapair[0] + "," + datapair[1];
            i.crossOrigin="anonymous";
            $("#user_sign_img").attr("src",i.src);
            $("#user_sign_tips").hide();

            //Encapsulate blob objects  
            var blob = convertBase64UrlToBlob(i.src); 
            upload(blob)
        }

        function convertBase64UrlToBlob(urlData){
            var bytes=window.atob(urlData.split(',')[1]);        //Remove the header from the url and convert to byte
            //Handle exception, convert ascii code less than 0 to greater than 0
            var ab = new ArrayBuffer(bytes.length);
            var ia = new Uint8Array(ab);
            for (var i = 0; i < bytes.length; i++) {
                ia[i] = bytes.charCodeAt(i);
            }
            return new Blob( [ab] , {type : 'image/png'});
        }

       /* Picture upload */ 
       var hostUrl=window.location.protocol+"//"+window.location.host+"/yunjingservice/"; 
       var basename=Base64.encodeURI("${user_name}");       
       var accessid='',policy='', Signature='', key='signature/${user_id.substring(0, 4)}_'+basename+'.png' ,host='',expire = 0,now = 0;

       // You can judge whether the current expire exceeds the current time. If it exceeds the current time, you can retrieve it again and use 3s as the buffer
       function getOSSAuth(){
          now = Date.parse(new Date()) / 1000; 
          if (expire < now + 3){
               $.post(hostUrl + "OSSAuth/yjsign.shtml",{dir:"signature"},function(data){
                console.dir(data);
                accessid=data.accessid;
                policy=data.policy;
                signature=data.signature;
                expire=data.expire;
                host=data.host;
              });
           }
       }

      function get_suffix(filename) {
        pos = filename.lastIndexOf('.')
        suffix = ''
        if (pos != -1) {
            suffix = filename.substring(pos)
        }
        return suffix;
      }

       function upload(blob){
         getOSSAuth();//Get authorization
         var request = new FormData(); 
           request.append('OSSAccessKeyId', accessid);
           request.append('policy', policy);
           request.append('Signature',signature);
           request.append('key',key);//+filename
           request.append('success_action_status','200');//The status header, if not set, returns 204
           request.append('Access-Control-Allow-Origin','*');
           request.append('Access-Control-Allow-Methods','GET, POST');
           //request.append('file', $(".upload_input")[0].files[0]);
           request.append("fileData", blob);//fileData is custom 
           request.append('file', blob);
           request.append("imageName",blob);
           $.ajax({
               url: host,
               data: request,
               processData: false,
               cache: false,
               async: false,
               contentType: false,
               //The key is to set the contentType to false, otherwise the issued request header has no boundary
               type: "POST",
               beforeSend:function(){
                 var width = 1;
                  timer = setInterval(function(){
                    $("#loadingStatus").css({"width":width + "%"});
                    $("#loadingStatus span").text("Uploading"+width+"%")
                    width++;
                    if(width == 98){
                        clearInterval(timer)
                    }
                 },34)
               },
               success: function (data,textStatus, request) {
                 console.log(data)
                 if (request.status == '200') {
                     reset();
                     clearInterval(timer)
                     $("#loadingStatus").css({"width":"100%"});
                     //$("#imageViewBox").css({"height":"auto"})
                     $("#signWrap").removeClass("flex");
                     $("#user_sign_delete").show();
                     layer.msg('Signature saved successfully!');
                 }
               },
               error: function (data,textStatus, request) {
                   layer.msg('Upload failed, please try again!');
               },
               complete:function(){
               }
           });
       }

        var signImgSrc = "https://biangene.oss-cn-shenzhen.aliyuncs.com/signature/${user_id.substring(0, 4)}_"+basename+".png";

        $(function(){
            var time = Date.parse(new Date());
           $("#user_sign_img").attr("src","https://biangene.oss-cn-shenzhen.aliyuncs.com/signature/${user_id.substring(0, 4)}_"+basename+".png?"+time);
        });

        $(window).load(function(){
           $("img.user_sign").each(function() {
               if (!this.complete || typeof this.naturalWidth == "undefined" || this.naturalWidth == 0) { 
                  $("#user_sign_img").attr("src","image/sign_img_default.jpg").show();
                  $("#user_sign_tips").show();
                  $("#user_sign_delete").hide();
               }else{
                  $("#user_sign_img").show()
                  $("#user_sign_tips").hide();
                  $("#user_sign_delete").show();
               }
           });

    });  

   </script>

Tags: Mobile Javascript ascii less

Posted on Sat, 02 May 2020 18:00:51 -0700 by Poomerio