H5手写签名,适用于手机网页、电脑网页(IE9+)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/moniteryao/article/details/82263653

先看看效果吧:

图片保存到服务器为png格式,一般10k左右。

这个功能适用于H5app,或者H5,或者pc网页端(IE9以上,支持canvas),

低端安卓机依然不支持,具体低端到什么程度,没有经过测试。

下边上代码,前端HTML:

<!DOCTYPE html>
<html lang="en">

	<head>
		<meta charset="utf-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<!--<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">-->
		<!--<meta name="viewport" content="initial-scale=1.0, target-densitydpi=device-dpi" />-->
		<!-- this is for mobile (Android) Chrome -->
		<!--<meta name="viewport" content="initial-scale=1.0, width=device-height">-->
		<!--  mobile Safari, FireFox, Opera Mobile  -->
		<script src="js/libs/modernizr.js"></script>
		<!--[if lt IE 9]>
		<script type="text/javascript" src="libs/flashcanvas.js"></script>
		<![endif]-->
		<style type="text/css">
			/*div {
				margin-top: 1em;
				margin-bottom: 1em;
			}*/
			
			input {
				padding: .5em;
				margin: .5em;
			}
			
			select {
				padding: .5em;
				margin: .5em;
			}
			
			#signatureparent {
				color: #000;
				background-color: #fff;
				/*max-width:600px;*/
				padding: 10px;
				width: 100%;
			}
			/*This is the div within which the signature canvas is fitted*/
			
			#signature {
				border: 1px dotted #3eaed2;
				background-color: #ececec;
				height: 200px;
				width: 100%;
			}
			/* Drawing the 'gripper' for touch-enabled devices */
			
			html.touch #content {
				float: left;
				width: 92%;
			}
			
			/*html.touch #scrollgrabber {
				float: right;
				width: 4%;
				margin-right: 2%;
				background-image: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAFCAAAAACh79lDAAAAAXNSR0IArs4c6QAAABJJREFUCB1jmMmQxjCT4T/DfwAPLgOXlrt3IwAAAABJRU5ErkJggg==)
			}*/
			
			html.borderradius #scrollgrabber {
				border-radius: 1em;
			}
			.signature .jSignature{height: 100%;}
		</style>
	</head>
	<body style="background-color: #fff;">
			<div id="content" style="width: 100%;">
				<p>说明:
					服务器端用的thinkphp,这里只是个控制器,单独使用无效的,
					如果不知道控制器该放在什么位置,请自行百度。自行拼接请求服务器的完整的网址。
				</p>
				<p style="padding-left: 10px;margin-top:10px;margin-bottom: 5px;">请在虚线框内签名,完毕后点击“保存”。</p>
				<div id="signatureparent">
					<div id="signature"></div>
				</div>
				<div style="text-align: center;">
					<input type="button" name="btnReset" id="btnReset" value="重写" />
					<input type="submit" class="" name="btnSave" id="btnSave"  value="保存签名" />
				</div>
			</div>
		<script src="libs/jquery1.10.2.min.js"></script>
		<script type="text/javascript">
			jQuery.noConflict();
		</script>
		<script>
			/*  @preserve
			jQuery pub/sub plugin by Peter Higgins ([email protected])
			Loosely based on Dojo publish/subscribe API, limited in scope. Rewritten blindly.
			Original is (c) Dojo Foundation 2004-2010. Released under either AFL or new BSD, see:
			http://dojofoundation.org/license for more information.
			*/
			(function($) {
				var topics = {};
				$.publish = function(topic, args) {
					if(topics[topic]) {
						var currentTopic = topics[topic],
							args = args || {};

						for(var i = 0, j = currentTopic.length; i < j; i++) {
							currentTopic[i].call($, args);
						}
					}
				};
				$.subscribe = function(topic, callback) {
					if(!topics[topic]) {
						topics[topic] = [];
					}
					topics[topic].push(callback);
					return {
						"topic": topic,
						"callback": callback
					};
				};
				$.unsubscribe = function(handle) {
					var topic = handle.topic;
					if(topics[topic]) {
						var currentTopic = topics[topic];

						for(var i = 0, j = currentTopic.length; i < j; i++) {
							if(currentTopic[i] === handle.callback) {
								currentTopic.splice(i, 1);
							}
						}
					}
				};
			})(jQuery);
		</script>
		<script src="libs/jSignature.min.noconflict.js"></script>
		<script>
			(function($) {

				$(document).ready(function() {

					// This is the part where jSignature is initialized.
					var $sigdiv = $("#signature").jSignature({
							'UndoButton': false
						}),
						// All the code below is just code driving the demo. 
						$tools = $('#tools'),
						$extraarea = $('#displayarea'),
						pubsubprefix = 'jSignature.demo.'

					var export_plugins = $sigdiv.jSignature('listPlugins', 'export');
					
					$("#btnSave").on("click",function(){
						//可选格式:native,image,base30,image/jsignature;base30,svg,image/svg+xml,svgbase64,image/svg+xml;base64
						var basedata = "data:"+$sigdiv.jSignature('getData', "image");
//						console.log("basedata:"+basedata);
//						$(".signResult").html(data);
						//server是我自定义的,值为http://www.abc.com/index.php?g=user&m=jk
						//这样就能拼接完整的请求路径了。
						var weburl=server+"&a=make_sign";
						var jsdata={imgbase:basedata};
						$.ajax({
							type:"post",
							url:weburl,
							async:true,
							data:jsdata,
							dataType:"json",
							success:function(data){
								console.log(JSON.stringify(data));
								if(data.success){
									console.log(data.msg);
								}
								else{
									console.log(data.msg);
								}
							}
						}); 
//						if(data.length<100){
	                        //本来这里想判断是否为空的,发现什么都不写时,竟然也有数据,应该是底板的编码了
//							mui.toast("请重新签名");
//						}
					});
					$("#btnReset").on("click",function(){
						$sigdiv.jSignature('reset');
					});
				})
			})(jQuery)
		</script>
	</body>

</html>

服务端使用thinkphp:

<?php
namespace User\Controller;
use Common\Controller\HomebaseController;
class JkController extends HomebaseController {
	function make_sign(){
		$host=$_SERVER['HTTP_HOST'];//系统域名
		$base64=I("imgbase");
		$result=$this->base64_upload($base64);
		if($result!==false){
			$signUrl=$host.$result;
			$rtn='{"success":true,"msg":"保存成功","signurl":"http://'.$signUrl.'"}';
		}
		else{
			$rtn='{"success":false,"msg":"签名保存失败"}';
		}
		echo $rtn;
	}
	//保存base64为图片
	function base64_upload($base64) {
	    $base64_image = str_replace(' ', '+', $base64);
	    //post的数据里面,加号会被替换为空格,需要重新替换回来,如果不是post的数据,则注释掉这一行
	    //上一行是注释好像没有意义,测试后发现,post来的数据,并没有把+替换为空格
	    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image, $result)){
	        //匹配成功
	        if($result[2] == 'jpeg'){
	            $image_name = uniqid().'.jpg';
	            //纯粹是看jpeg不爽才替换的
	        }else{
	            $image_name = uniqid().'.'.$result[2];
	        }
			$img_url="/Uploads/".date("Ymd")."/";
			//目录要有可写权限,一般给user全部权限就行了。
			if(!is_dir("./".$img_url)){
				mkdir("./".$img_url);
			}
	        $image_file = $img_url.$image_name;
	        //服务器文件存储路径
	        //  ./这才是指向根目录的
	        if (file_put_contents(".".$image_file, base64_decode(str_replace($result[1], '', $base64_image)))){
	            return $image_file;
	        }else{
	            return false;
	        }
	    }else{
	        return false;
	    }
	}
}

这是控制器,具体位置不用细说了吧。

注意:demo里,有个地方需要修改,就是控制器的33和34行,路径前面要加上./,这样才能指向根目录。

修改后如下:

if(!is_dir("./".$img_url)){
	mkdir("./".$img_url);
}

完整的demo下载路径:https://download.csdn.net/download/moniteryao/10639108

js插件来源:http://www.jq22.com/jquery-info13488

服务器接收base64另存为图片借鉴:https://www.cnblogs.com/hopelooking/p/6277419.html

猜你喜欢

转载自blog.csdn.net/moniteryao/article/details/82263653