一、效果图
二、代码示例
<!doctype html>
<html lang="zh">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta http-equiv="Cache-Control" content="no-cache" />
<meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no" />
<meta name="apple-mobile-web-app-capable" content="yes">
<style>
* {
touch-action: pan-y; /* 签名的时候滑动会报错,使用全局样式样式去掉 */
}
</style>
</head>
<body>
<div class="htmleaf-container">
<div class="container">
<div class="row">
<div class="col-xs-12">
<p>请签名:</p>
<div class="js-signature"></div>
<p>
<button id="saveBtn" class="btn btn-default" disabled>预览</button>
<button id="clearBtn" class="btn btn-default" >重写</button>
<input type="file" id="imgTest" type="file" onchange="imgChange(event)" accept=".gif,.jpg,.jpeg,.png">
</p>
<div id="signature">
<p>写上签名并点击预览</p>
<div></div>
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.bootcss.com/jquery/1.7.2/jquery.min.js"></script>
<script src="./js/jq-signature.js"></script>
<script type="text/javascript">
$(document).on('ready', function() {
if ($('.js-signature').length) {
var _width = 600;
var _height = 200;
var rate = 0;
if(screen.width<_width){
rate = _width/screen.width;
_width = _width/rate - 15;
_height = _height/rate ;
}
$('.js-signature').jqSignature({autoFit: false,width:_width,height: _height});
}
$('.js-signature').on('jq.signature.changed', function() {
$('#saveBtn').attr('disabled', false);
});
$('#clearBtn').on('click',function(){
$('#signature').html('<p>写上签名并点击预览</p><div></div>');
$('.js-signature').jqSignature('clearCanvas');
$('#saveBtn').attr('disabled', true);
})
$('#saveBtn').on('click',function(){
var dataUrl = $('.js-signature').jqSignature('getDataURL');
console.debug(dataUrl);
var img = $('<img>').attr('src', dataUrl);
$('#signature p').html($('<p>').text("签名预览如下:"));
$('#signature div').html(img);
})
});
function imgChange(e) {
console.info(e.target.files[0]);//图片文件
var dom =$("input[id^='imgTest']")[0];
console.info(dom.value);
console.log(e.target.value);
var reader = new FileReader();
reader.onload = (function (file) {
return function (e) {
var img = $('<img>').attr('src',this.result);
$('#signature div').html(img);
$('.js-signature').jqSignature('setData',this.result);
$('#saveBtn').attr('disabled', false);
};
})(e.target.files[0]);
reader.readAsDataURL(e.target.files[0]);
}
</script>
</body>
</html>
jq-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: 300,
height: 100,
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',
'background-size':'cover'
});
// 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();
},
setData: function(data){
this.clearCanvas();
var ctx = this.canvas.getContext("2d");
var img = new Image();
var _max_width = this.settings.width;
var _max_height = this.settings.height;
img.src=data;
img.onload = function(){
// 图片尺寸
var img_w = img.naturalWidth;
var img_h = img.naturalHeight;
// 缩略后尺寸
var dimg_w ;
var dimg_h ;
// 计算缩略尺寸
dimg_w = _max_width;
dimg_h = Math.ceil(dimg_w*img_h/img_w);
if(dimg_h>_max_height){
dimg_h = _max_height;
dimg_w = Math.ceil(dimg_h*img_w/img_h);
}
console.debug(img_w,img_h,_max_width,_max_height);
ctx.drawImage(img,0,0,dimg_w, dimg_h);
}
},
// Get the position of the mouse/touch
_getPosition: function(event) {
var xPos, yPos, rect;
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 - rect.top;
}
// Mouse event
else {
xPos = event.clientX - rect.left;
yPos = event.clientY - rect.top;
}
return {
x: xPos,
y: 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);
View Code