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.페이지 효과 도 는 다음 과 같다.

이상 이 바로 본 고의 모든 내용 입 니 다.여러분 의 학습 에 도움 이 되 고 저 희 를 많이 응원 해 주 셨 으 면 좋 겠 습 니 다.

좋은 웹페이지 즐겨찾기