当前位置: 移动技术网 > IT编程>开发语言>JavaScript > jQuery实现移动端笔触canvas电子签名

jQuery实现移动端笔触canvas电子签名

2020年06月23日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了jquery实现移动端笔触canvas电子签名的具体代码,供大家参考,具体内容如下

本文主要是通过jq实现电子签名,其中ios有一个坑,已修复。基于mui+vue框架实现的,如果使用此框架,稍稍改动代码即可。

1.相关代码

1.1引入jq

<script src="jquery-1.11.0.min.js" type="text/javascript"></script>

1.2封装signature.js

(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: 375,
  height: 200,
  autofit: false
  },
  canvasfixture = '<canvas></canvas>';

 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 u = navigator.useragent;
  var isios = !!u.match(/\(i[^;]+;( u;)? cpu.+mac os x/); //ios终端
  var xpos, ypos, rect, getrect;
  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 - 50;
  $('#ypos').html('<p><em>当您点击“保存签名”时,w您的签名将出现在这里'+ypos+','+rect.top+','+rect.bottom+'</em></p>');
  
  }

  // mouse event
  else {
  xpos = event.clientx - rect.left;
  ypos = event.clienty - rect.top;
  $('#ypos').html(ypos);
  }
  return {
  x: xpos,
  y: ypos
//  y: isios?1.7*ypos: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);

1.3dom页面

<div class="signature-wrapper" v-show="issignature" :class="issignature?'issignature':''">
 <header class="mui-bar mui-bar-nav head-color">
 <a class="mui-icon mui-icon-back mui-pull-left" @tap="closesignature"></a>
 <h1 class="mui-title">签名</h1>
 <a id="menu" class="mui-icon mui-pull-right menu-btn" @tap="savesignature">保存</a>
 </header>

 <div class="container">
 <div class="row">
 <div class="col-xs-12">
 <div class="js-signature" data-width="600" data-height="200" data-border="1px solid black" data-line-color="#000000" data-auto-fit="true"></div>
 <p><button id="clearbtn" class="btn btn-default" @tap="clearcanvas();">重置签名</button>&nbsp;<button id="savebtn" class="btn btn-default" @tap="previewsignature();" disabled>保存签名</button></p>
 <div id="signature">
  <p><em>当您点击“保存签名”时,您的签名将出现在这里</em></p>
 </div>
 <span id="ypos"><p><em>ypos</em></p></span>
 </div>
 </div>
 </div>
</div>

1.4js

注:由于此次的$被模型其他框架所替换,因此以jq替代

mounted: function() {
this.$nexttick(function() {
 this.init();
 });
},
methods:{
 init: function() {
 jq('.js-signature').eq(0).on('jq.signature.changed', function() { //canvas签名 初始化 
 jq('#savebtn').attr('disabled', false);
 });
 }
},
clearcanvas:function(){ // 清除重置签名
 jq('#signature').html('<p><em>当您点击“保存签名”时,您的签名将出现在这里</em></p>');
 jq('.js-signature').eq(0).jqsignature('clearcanvas');
 jq('#savebtn').attr('disabled', true);
 vm.signatureimg="";
},
previewsignature:function(){ //保存签名
 jq('#signature').empty();
 var dataurl = jq('.js-signature').eq(0).jqsignature('getdataurl');
 var img = jq('<img>').attr('src', dataurl);
 jq('#signature').append(img);
 console.log(dataurl)
 vm.signatureimg=dataurl;
},
savesignature:function(){ // 保存按钮 逻辑
if(!vm.signatureimg){
 $.toast("请先保存签名");
 return;
 }
 vm.closesignature();
},
closesignature:function(){// 关闭签名弹出层
 vm.issignature = false;
 },
opensignature:function(){ // 打开签名弹出层
 vm.issignature = true;
 this.$nexttick(function() {
 if ($('.js-signature').length) {
 jq('.js-signature').jqsignature();
 }
 });
}

2.页面效果图如下

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网