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

本文实例为大家分享了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>&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.页面效果图如下

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

(0)

相关推荐

  • 微信小程序实现电子签名并导出图片

    本文实例为大家分享了微信小程序做电子签名,并导出图片的具体代码,供大家参考,具体内容如下 wxml: <canvas class="canvas" id="canvas" canvas-id="canvas" disable-scroll="true" bindtouchstart="canvasStart" bindtouchmove="canvasMove" bindtouch

  • 基于canvas实现手写签名(vue)

    最近一直在研究canvas的东西,正好之前对手写签名这块有点兴趣.就自己基于vue写了一个简易的手写签名demo. 其中原理比较简单,先生成一个canvas画布,并对canvas进行touchstart和touchmove事件进行监听.当监听touchstart事件被触发时,我们开始触发canvas里的beginPath事件并且设置moveTo原始点.当监听touchmove事件则去不断去触发lineTo事件,最后stroke(). demo里还有清除签名和保存签名的功能,分别对应了clearR

  • vue 使用 canvas 实现手写电子签名

    功能 兼容 PC 和 Mobile: 画布自适应屏幕大小变化(窗口缩放.屏幕旋转时画布无需重置,自动校正坐标偏移): 自定义画布尺寸(导出图尺寸),画笔粗细.颜色,画布背景色: 支持裁剪 (针对需求:有的签字需要裁剪掉四周空白). 导出图片格式为 base64 : 示例demo 安装 npm install vue-esign --save 使用 main.js 中引入 import vueEsign from 'vue-esign' Vue.use(vueEsign) 页面中使用 必须设置 r

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

    本文实例为大家分享了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 (functi

  • jQuery实现移动端图片上传预览组件的方法分析

    本文实例讲述了jQuery实现移动端图片上传预览组件的方法.分享给大家供大家参考,具体如下: 之前的一篇博客:移动端H5图片预览和压缩,实现了基本的功能.这次则计划做成一个组件,可供前台.后台使用. 首先,我们先来捋一捋想要实现的功能: 预览 删除 压缩 上传到服务器 基本机构 这样,我们的组件结构就有了: ;!function(window, $, undefined){ function Upload() { }; Upload.prototype.change = function() {

  • jQuery实现移动端滑块拖动选择数字效果

    本文为大家分享了基于jquery ui实现的一个精美实用的效果,可以通过鼠标拖拽滑动效果来选择数字,供大家参考,具体内容如下 运行效果图: 实现代码: <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="gb2312"> <title>demo</title> <link rel="stylesheet"

  • jQuery实现移动端手机商城购物车功能

    购物车数量加减 右加号 $(".jiahao").click(function() { var t = $(this).siblings().find("input");//取到数量 t.val(parseInt(t.val()) + 1);//parseInt()解析input一个字符串,返回一个整数 heji();//调用后面计算的函数 }) 左减号 $(".jianhao").click(function() { var t = $(thi

  • jQuery仿移动端支付宝键盘的实现代码

    最近做项目时碰到一个需求,就是在移动端支付页面点击支付按钮弹出一个支付键盘,类似于支付宝的那种.由于项目只是单纯的手机网站,而并非app,所以这个功能得由前端来实现.话不多说,先上图看看效果. 尼玛,这不就是支付宝app那个支付键盘吗? 没错,咱们UI就是参照支付宝做的这个键盘.你可能会问,为什么不直接调用支付宝提供的支付接口呢.额,因为项目需要,这里就不多解释了. 我们先看一下实现后的效果图 HTML部分 <!-- 支付键盘 --> <divclass="pay-contai

  • jQuery实现移动端扭蛋机抽奖

    本文实例为大家分享了jQuery实现移动端扭蛋机抽奖的具体代码,供大家参考,具体内容如下 <!doctype html> <html> <head> <meta charset="utf-8"> <meta name="apple-touch-fullscreen" content="YES" /> <meta name="format-detection" c

  • jquery实现移动端按钮组左右滑动

    本文实例为大家分享了jquery实现移动端按钮组左右滑动的具体代码,供大家参考,具体内容如下 学习移动端触摸相关功能时写了一个例子,共享一下,其中最不好理解的是screen.page.client相对坐标的问题,我画了一个简图帮助记忆: jquery插件源码: //按钮滑动插件     +(function ($, w, d, undefined) {           jQuery.fn.slideLeftRight = function () {             var start

  • Jquery实现移动端控制DIV拖拽

    本文实例为大家分享了Jquery实现移动端控制DIV拖拽的具体代码,供大家参考,具体内容如下 需求:车型配置表,移动端需要滑动,并且多项配置的表需要联动对应头部分类名称 要求:左侧 title 固定 / 顶部需要吸顶效果 处理方案:一开始打算使用table表格,但是发现不太好控制,后来就使用了div进行模拟了table表格.左侧title 和 右侧的表格属于两部分结构. 然后移动端的时候进行相对定位,控制右侧的盒子进行联动并且实现滑动效果 /*     touchstart 事件     tou

  • jquery datatable服务端分页

    OK,上次完成了客户端的分页,这次我们就在上一次的Demo上进行修改,来实现服务端的分页~ js代码: <script type="text/javascript"> $(document).ready(function() { $('#table_id_example').DataTable({ "bProcessing" : false, //是否显示加载 "sAjaxSource" : '/datatableDemo/user/

  • jQuery实现移动端Tab选项卡效果

    效果图: 代码如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalab

随机推荐