先看看效果吧:
圖片保存到服務器爲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