欢迎来到cool的博客
7

Music box

Click to Start

点击头像播放音乐
新博客链接

如何使用signature_pad (签名,画板)

demo:

http://szimek.github.io/signature_pad/

参考地址:https://github.com/szimek/signature_pad

效果如下:


 

1.页面的代码如下:(我的是rails项目, signature.html.erb) 

<!doctype html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>签名页</title>
        <meta name="description" content="Signature Pad - HTML5 canvas based smooth signature drawing using variable width spline interpolation.">

        <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no">

        <meta name="apple-mobile-web-app-capable" content="yes">
        <meta name="apple-mobile-web-app-status-bar-style" content="black">

        <link rel="stylesheet" href="http://szimek.github.io/signature_pad/css/signature-pad.css">
    <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
        <script src="http://szimek.github.io/signature_pad/js/signature_pad.js"></script>

        <script type="text/javascript">
            var _gaq = _gaq || [];
            _gaq.push(['_setAccount', 'UA-39365077-1']);
            _gaq.push(['_trackPageview']);

            (function() {
                var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
                ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
                var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
            })();
        </script>
    </head>

    <body onselectstart="return false">
        <div id="signature-pad" class="m-signature-pad">
            <div class="m-signature-pad--body">
                <canvas></canvas>
            </div>
            <div class="m-signature-pad--footer">
                <div class="description">请在上面签字</div>
                <button id="clear" type="button" class="button clear" data-action="clear">清除</button>
                <button id="save" type="button" class="button save" data-action="save">保存</button>
            </div>
        </div>

    <script>
      var wrapper = document.getElementById("signature-pad"),
          clearButton = wrapper.querySelector("[data-action=clear]"),
          saveButton = wrapper.querySelector("[data-action=save]"),
          canvas = wrapper.querySelector("canvas"),
          signaturePad;

      function resizeCanvas() {
        var ratio =  Math.max(window.devicePixelRatio || 1, 1);
        canvas.width = canvas.offsetWidth * ratio;
        canvas.height = canvas.offsetHeight * ratio;
        canvas.getContext("2d").scale(ratio, ratio);
      }

      window.onresize = resizeCanvas;
      resizeCanvas();

      signaturePad = new SignaturePad(canvas);

      clearButton.addEventListener("click", function (event) {
        signaturePad.clear();
      });

      saveButton.addEventListener("click", function (event) {
        if (signaturePad.isEmpty()) {
          alert("Please provide signature first.");
        } else {
          window.open(signaturePad.toDataURL());
          var data = signaturePad.toDataURL('image/png');
          //window.open(signaturePad.toDataURL());
          window.open(data)
          console.info(data)

          // 注意返回的 data 在新窗口打开,是一大串  data_uri 代码。我们需要把 data_uri 上传到 upyun ,然后再返回签名的图片链接。下面是一个ajax的方法。 上传签名到upyun.

          $.post('/interface/staffs/upload_signature_data_uri_to_upyun', {data_uri: data}, function(result) {
            if (result.is_upload_success) {
              window.location.href = "<%= root_path %>?signature_img=" + result.img_url
            } else {
              console.info(data)
            }
          });

        }
      });

    </script>
    </body>
</html>

2.ajax请求接口的方法。

  def upload_signature_data_uri_to_upyun
    Tool.upload_signature_image(params[:data_uri], 20)
    signature_image = SignatureImage.find_by_staff_id(20)

    render :json => {
      is_upload_success: true,
      img_url: signature_image.img_url
    }
  end

3.上传图片到upyun的方法,在 model/tool.rb中:(保存签名的表是 signture_images     staff_id是字段)

 def self.upload_signature_image(image, staff_id)
    require 'upyun'
    bucket = Settings.carrierwave.bucket
    operator = Settings.carrierwave.operator
    password = Settings.carrierwave.password             #settings 是又拍云账号的配置

    require 'data_uri'
      upload_file = image
      upyun = Upyun::Rest.new(bucket, operator, password)
      Rails.logger.info "image ====== #{image}"

      new_file_name = Time.now.strftime('%Y-%m-%d') + rand(10000).to_s + ".jpg"
      remote_file = "/image/queentown/#{new_file_name}"       #远程保存图片的位置
      uri = URI::Data.new(image)
      picture_url = "#{Settings.carrierwave.bucket_host}#{remote_file}"

      Rails.logger.info "picture_url  ===== #{picture_url} ===="

      file_on_local_path = "#{Rails.root}/public/uploads/#{new_file_name}"
      File.write(file_on_local_path, uri.data.force_encoding('UTF-8'))
      response = upyun.put remote_file, File.new(file_on_local_path)

      SignatureImage.create(
          img_url: picture_url,
          staff_id: staff_id
        )
  end

点击save,就能保存签名了。

返回列表