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


Posted in jQuery onMay 21, 2020

本文实例为大家分享了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页面index.html

<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> <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.页面效果图如下

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

jQuery 相关文章推荐
jquery.validate表单验证插件使用详解
Jun 21 jQuery
jQuery+C#实现参数RSA加密传输功能【附jsencrypt.js下载】
Jun 26 jQuery
使用 jQuery 实现表单验证功能
Jul 05 jQuery
自定义类似于jQuery UI Selectable 的Vue指令v-selectable
Aug 23 jQuery
jQuery实现滚动效果
Nov 17 jQuery
Vue.js 通过jQuery ajax获取数据实现更新后重新渲染页面的方法
Aug 09 jQuery
学习jQuery中的noConflict()用法
Sep 28 jQuery
jQuery实现的中英文切换功能示例
Jan 11 jQuery
jquery 验证用户名是否重复代码实例
May 14 jQuery
jQuery实现手风琴效果(蒙版)
Jan 11 jQuery
jQuery实现鼠标移入显示蒙版效果
Jan 11 jQuery
jQuery实现雪花飘落效果
Aug 02 jQuery
jQuery HTML获取内容和属性操作实例分析
May 20 #jQuery
jQuery HTML设置内容和属性操作实例分析
May 20 #jQuery
jquery html添加元素/删除元素操作实例详解
May 20 #jQuery
jQuery HTML css()方法与css类实例详解
May 20 #jQuery
jQuery 隐藏/显示效果函数用法实例分析
May 20 #jQuery
jQuery 淡入/淡出效果函数用法分析
May 19 #jQuery
jQuery 动画与停止动画效果实例详解
May 19 #jQuery
You might like
php-perl哈希算法实现(times33哈希算法)
2013/12/30 PHP
php生成随机字符串可指定纯数字、纯字母或者混合的
2014/04/18 PHP
PHP file_get_contents函数读取远程数据超时的解决方法
2015/05/13 PHP
PHP网页安全认证的实例详解
2017/09/28 PHP
List all the Databases on a SQL Server
2007/06/21 Javascript
JQuery中判断一个元素下面是否有内容或者有某个标签的判断代码
2012/02/02 Javascript
JavaScript 处理Iframe自适应高度(同或不同域名下)
2013/03/29 Javascript
JS图片放大效果简单实现代码
2016/09/08 Javascript
vue实现导航栏效果(选中状态刷新不消失)
2017/12/13 Javascript
用node开发并发布一个cli工具的方法步骤
2019/01/03 Javascript
JavaScript代码调试方法实例小结
2019/01/05 Javascript
VueJs里利用CryptoJs实现加密及解密的方法示例
2019/04/29 Javascript
Vue监听页面刷新和关闭功能
2019/06/20 Javascript
vue使用高德地图根据坐标定位点的实现代码
2019/08/22 Javascript
VUE 自定义组件模板的方法详解
2019/08/30 Javascript
微信小程序 flexbox layout快速实现基本布局的解决方案
2020/03/24 Javascript
Vue 样式切换及三元判断样式关联操作
2020/08/09 Javascript
[01:16:01]VGJ.S vs Mski Supermajor小组赛C组 BO3 第一场 6.3
2018/06/04 DOTA
python数组过滤实现方法
2015/07/27 Python
VTK与Python实现机械臂三维模型可视化详解
2017/12/13 Python
详解python校验SQL脚本命名规则
2019/03/22 Python
Python 使用指定的网卡发送HTTP请求的实例
2019/08/21 Python
在pytorch 中计算精度、回归率、F1 score等指标的实例
2020/01/18 Python
以实惠的价格提供高品质的时尚:Newchic
2018/01/18 全球购物
澳大利亚网上买书:Angus & Robertson
2019/07/21 全球购物
社团文化节邀请函
2014/01/10 职场文书
保密普查工作实施方案
2014/02/25 职场文书
爽歪歪广告词
2014/03/20 职场文书
竞赛口号大全
2014/06/16 职场文书
瘦西湖导游词
2015/02/03 职场文书
钱塘江大潮导游词
2015/02/03 职场文书
学术研讨会主持词
2015/07/04 职场文书
公司人力资源管理制度
2015/08/05 职场文书
《将心比心》教学反思
2016/02/23 职场文书
Java实战之用Swing实现通讯录管理系统
2021/06/13 Java/Android
ubuntu如何搭建vsftpd服务器
2022/12/24 Servers