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动态追加页面数据以及事件委托详解
May 06 jQuery
jQuery遍历节点方法汇总(推荐)
May 13 jQuery
jquery实现一个全局计时器(商城可用)
Jun 30 jQuery
Jquery中.bind()、.live()、.delegate()和.on()之间的区别详解
Aug 01 jQuery
jQuery+HTML5实现WebGL高性能烟花绽放动画效果【附demo源码下载】
Aug 18 jQuery
解决html-jquery/js引用外部图片时遇到看不了或出现403的问题
Sep 22 jQuery
浅谈ajax在jquery中的请求和servlet中的响应
Jan 22 jQuery
用jquery获取select标签中选中的option值及文本的示例
Jan 25 jQuery
jQuery实现的电子时钟效果完整示例
Apr 28 jQuery
JQuery特殊效果和链式调用操作示例
May 13 jQuery
jQuery操作cookie的示例代码
Jun 05 jQuery
jquery插件实现代码雨特效
Apr 24 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 强制下载文件代码
2010/10/24 PHP
PHP修改session_id示例代码
2014/01/08 PHP
php数组去除空值函数分享
2015/02/02 PHP
php输入数据统一类实例
2015/02/23 PHP
jquery使用ColorBox弹出图片组浏览层实例演示
2013/03/14 Javascript
jquery批量控制form禁用的代码
2013/08/06 Javascript
获取非最后一列td值并将title设为该值的方法
2013/10/30 Javascript
js实现大转盘抽奖游戏实例
2015/06/24 Javascript
js获取对象、数组的实际长度,元素实际个数的实现代码
2016/06/08 Javascript
jQuery实现输入框邮箱内容自动补全与上下翻动显示效果【附demo源码下载】
2016/09/20 Javascript
html、css和jquery相结合实现简单的进度条效果实例代码
2016/10/24 Javascript
js实现控制textarea输入字符串的个数,鼠标按下抬起判断输入字符数
2016/10/25 Javascript
webgl实现物体描边效果的方法介绍
2019/11/27 Javascript
[02:08]什么藏在DOTA2 TI9“小紫本”里?斧王历险记告诉你!
2019/05/17 DOTA
python 接口_从协议到抽象基类详解
2017/08/24 Python
pandas 小数位数 精度的处理方法
2018/06/09 Python
pandas进行数据的交集与并集方式的数据合并方法
2018/06/27 Python
Pytorch: 自定义网络层实例
2020/01/07 Python
Python如何通过百度翻译API实现翻译功能
2020/04/02 Python
VScode连接远程服务器上的jupyter notebook的实现
2020/04/23 Python
Python程序慢的重要原因
2020/09/04 Python
英国马莎百货官网:Marks & Spencer
2016/07/29 全球购物
英国时尚优质的女装:Hope Fashion
2018/08/14 全球购物
英国家居用品和床上用品零售商:P&B Home
2020/01/16 全球购物
装饰资料员岗位职责
2013/12/30 职场文书
生物科学专业职业规划书范文
2014/02/11 职场文书
情人节活动策划方案
2014/02/27 职场文书
科技之星事迹材料
2014/06/02 职场文书
博士生专家推荐信
2014/09/26 职场文书
不尊敬老师的检讨书
2014/12/21 职场文书
先进典型发言材料
2014/12/30 职场文书
安全教育第一课观后感
2015/06/17 职场文书
2016年元旦寄语
2015/08/17 职场文书
Python包管理工具pip的15 个使用小技巧
2021/05/17 Python
JS实现九宫格拼图游戏
2022/06/28 Javascript
td 内容自动换行 table表格td设置宽度后文字太多自动换行
2022/12/24 HTML / CSS