利用HTML5d的Canvas绘制签名区域,保存为图片



简要教程

jq-signature是一款基于HTML5 canvas的支持移动触摸设备的在线签名和涂鸦jQuery插件。可以使用该jQuery插件来制作在线签名或涂鸦板,用户绘制的东西可以用图片的形式保存下来,非常方便实用。

关于使用HTML5 canvas制作涂鸦板的方法,可以参考《使用html5 canvas制作涂鸦画板》,如何将绘制号的涂鸦图片上传到服务器可以参考《HTML5 canvas画图及图片上传服务器》。

使用方法

使用该签名插件要引入jQuery和jq-signature.js文件。

< script src = "jquery/1.11.0/jquery.min.js" > script >
< script src = "jq-signature.js" > script

HTML结构

然后可以像下面这样创建一个签名区域。你可以使用HTML5的data-option来传递一些参数。

< div class = "js-signature"
      data-width = "600"
      data-height = "200"
      data-border = "1px solid #1ABC9C"
      data-background = "#16A085"
      data-line-color = "#fff"
      data-auto-fit = "true" >
div >  
此div表示的区域 即为 签名的  绘制区域。


你可以创建两个操作按钮,分别用于清空画板和保存签名。

< button id = "clearBtn" onclick = "clearCanvas();" >Clear Canvas button >
< button id = "saveBtn" onclick = "saveSignature();" disabled>Save Signature button >               

你可以使用一个空的

来显示保存的签名图片。

< div id = "signature" > div

初始化插件

在页面加载完毕之后使用下面的方法来初始化该签名插件。

$(document).on( 'ready' , function () {
   $( '.js-signature' ).jqSignature();
});
 
function clearCanvas() {
   $( '#signature' ).html( '

Your signature will appear here when you click "Save Signature"

'
);
   $( '.js-signature' ).jqSignature( 'clearCanvas' );
   $( '#saveBtn' ).attr( 'disabled' , true );
}
 
function saveSignature() {
   $( '#signature' ).empty();
   var dataUrl = $( '.js-signature' ).jqSignature( 'getDataURL' );
   var img = $( '' ).attr( 'src' , dataUrl);
   $( '#signature' ).append($( '

' ).text( "Here's your signature:" ));

   $(' #signature').append(img);
}
 
$('.js-signature ').on(' jq.signature.changed ', function() {
   $(' #saveBtn').attr('disabled', false);
});               

配置参数

下面是该签名插件的一些可用参数,这些参数同时也可以在data-attributes上使用:

参数 描述 Data Attribute 示例
Width 签名canvas的宽度,单位像素,默认值300 data-width="600" $().jqSignature({width: 600});
Height 签名canvas的高度,单位像素,默认值100 data-height="200" $().jqSignature({height: 200});
Border 签名canvas的边框CSS样式。默认为'1px solid #AAAAAA' data-border="1px solid red" $().jqSignature({border: '1px solid red'});
Background 签名canvas的背景颜色,默认值为'#FFFFFF' data-background="#EEEEEE" $().jqSignature({background: '#EEEEEE'});
Line Color 签名的颜色。默认值为#222222' data-line-color="#ABCDEF" $().jqSignature({lineColor: '#ABCDEF'});
Line Width 签名的线宽,单位像素,默认值为1 data-line-width="2" $().jqSignature({lineWidth: 2});
Auto Fit 使canvas占满父元素的宽度,默认值false

插件的内容

(function(window, document, $) {
	'use strict';

  // Get a regular interval for drawing to the screen
  window.requestAnimFrame = (function (callback) {
    return window.requestAnimationFrame || 
      window.webkitRequestAnimationFrame ||
      window.mozRequestAnimationFrame ||
      window.oRequestAnimationFrame ||
      window.msRequestAnimaitonFrame ||
      function (callback) {
        window.setTimeout(callback, 1000/60);
      };
  })();

  /*
  * Plugin Constructor
  */

  var pluginName = 'jqSignature',
      defaults = {
        lineColor: '#222222',
        lineWidth: 1,
        border: '1px dashed #AAAAAA',
        background: '#FFFFFF',
        width: 300,
        height: 100,
        autoFit: false
      },
      canvasFixture = '';

  function Signature(element, options) {
    // DOM elements/objects
    this.element = element;
    this.$element = $(this.element);
    this.canvas = false;
    this.$canvas = false;
    this.ctx = false;
    // Drawing state
    this.drawing = false;
    this.currentPos = {
      x: 0,
      y: 0
    };
    this.lastPos = this.currentPos;
    // Determine plugin settings
    this._data = this.$element.data();
    this.settings = $.extend({}, defaults, options, this._data);
    // Initialize the plugin
    this.init();
  }

  Signature.prototype = {
    // Initialize the signature canvas
    init: function() {
      // Set up the canvas
      this.$canvas = $(canvasFixture).appendTo(this.$element);
      this.$canvas.attr({
        width: this.settings.width,
        height: this.settings.height
      });
      this.$canvas.css({
        boxSizing: 'border-box',
        width: this.settings.width + 'px',
        height: this.settings.height + 'px',
        border: this.settings.border,
        background: this.settings.background,
        cursor: 'crosshair'
      });
      // Fit canvas to width of parent
      if (this.settings.autoFit === true) {
        this._resizeCanvas();
        // TO-DO - allow for dynamic canvas resizing 
        // (need to save canvas state before changing width to avoid getting cleared)
        // var timeout = false;
        // $(window).on('resize', $.proxy(function(e) {
        //   clearTimeout(timeout);
        //   timeout = setTimeout($.proxy(this._resizeCanvas, this), 250);
        // }, this));
      }
      this.canvas = this.$canvas[0];
      this._resetCanvas();
      // Set up mouse events
      this.$canvas.on('mousedown touchstart', $.proxy(function(e) {
        this.drawing = true;
        this.lastPos = this.currentPos = this._getPosition(e);
      }, this));
      this.$canvas.on('mousemove touchmove', $.proxy(function(e) {
        this.currentPos = this._getPosition(e);
      }, this));
      this.$canvas.on('mouseup touchend', $.proxy(function(e) {
        this.drawing = false;
        // Trigger a change event
        var changedEvent = $.Event('jq.signature.changed');
        this.$element.trigger(changedEvent);
      }, this));
      // Prevent document scrolling when touching canvas
      $(document).on('touchstart touchmove touchend', $.proxy(function(e) {
        if (e.target === this.canvas) {
          e.preventDefault();
        }
      }, this));
      // Start drawing
      var that = this;
      (function drawLoop() {
        window.requestAnimFrame(drawLoop);
        that._renderCanvas();
      })();
    },
    // Clear the canvas
    clearCanvas: function() {
      this.canvas.width = this.canvas.width;
      this._resetCanvas();
    },
    // Get the content of the canvas as a base64 data URL
    getDataURL: function() {
      return this.canvas.toDataURL();
    },
    // Get the position of the mouse/touch
    _getPosition: function(event) {
      var xPos, yPos, rect;
      rect = this.canvas.getBoundingClientRect();
      event = event.originalEvent;
      // Touch event
      if (event.type.indexOf('touch') !== -1) { // event.constructor === TouchEvent
        xPos = event.touches[0].clientX - rect.left;
        yPos = event.touches[0].clientY - rect.top;
      }
      // Mouse event
      else {
        xPos = event.clientX - rect.left;
        yPos = event.clientY - rect.top;
      }
      return {
        x: xPos,
        y: yPos
      };
    },
    // Render the signature to the canvas
    _renderCanvas: function() {
      if (this.drawing) {
        this.ctx.moveTo(this.lastPos.x, this.lastPos.y);
        this.ctx.lineTo(this.currentPos.x, this.currentPos.y);
        this.ctx.stroke();
        this.lastPos = this.currentPos;
      }
    },
    // Reset the canvas context
    _resetCanvas: function() {
      this.ctx = this.canvas.getContext("2d");
      this.ctx.strokeStyle = this.settings.lineColor;
      this.ctx.lineWidth = this.settings.lineWidth;
    },
    // Resize the canvas element
    _resizeCanvas: function() {
      var width = this.$element.outerWidth();
      this.$canvas.attr('width', width);
      this.$canvas.css('width', width + 'px');
    }
  };

  /*
  * Plugin wrapper and initialization
  */

  $.fn[pluginName] = function ( options ) {
    var args = arguments;
    if (options === undefined || typeof options === 'object') {
      return this.each(function () {
        if (!$.data(this, 'plugin_' + pluginName)) {
          $.data(this, 'plugin_' + pluginName, new Signature( this, options ));
        }
      });
    } 
    else if (typeof options === 'string' && options[0] !== '_' && options !== 'init') {
      var returns;
      this.each(function () {
        var instance = $.data(this, 'plugin_' + pluginName);
        if (instance instanceof Signature && typeof instance[options] === 'function') {
          returns = instance[options].apply( instance, Array.prototype.slice.call( args, 1 ) );
        }
        if (options === 'destroy') {
          $.data(this, 'plugin_' + pluginName, null);
        }
      });
      return returns !== undefined ? returns : this;
    }
  };

})(window, document, jQuery);


你可能感兴趣的:(开发笔记)