<!--[if lt IE 9]> <script type="text/javascript" src="libs/flashcanvas.js"></script> <![endif]-->
在<body>中加入:
<div id="signature"></div> <!-- you load jquery somewhere before jSignature ... --> <script src="libs/jquery.js"></script> <script src="libs/jSignature.min.js"></script> <script> $(document).ready(function () { $("#signature").jSignature() }) </script>
調整顏色或粗細(更多可用參數請參考:http://www.unbolt.net/jSignature/)
$("#signature").jSignature({color:"#00f",lineWidth:5});
加上相關按鈕
<button type='button' id="clear">清除</button> <button type='button' id="save">儲存</button>
加上清除功能
$('#clear').click(function(){ $("#signature").jSignature('clear'); });
建立資料表
CREATE TABLE `canvas` ( `sn` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `type` varchar(255) NOT NULL, `content` text NOT NULL, PRIMARY KEY (`sn`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8;
加上儲存功能:
$('#save').click(function(){ $.post('save.php', { sig: $("#signature").jSignature('getData', 'image')}, function(sn) { location.href='show.php?sn=' + sn; }); });
建立儲存用的save.php,其中sig為陣列,第一個元素紀錄圖片類型,第二個才是圖片編碼內容
<?php $db = new mysqli('localhost', 'root', '密碼', '資料庫'); if ($db->connect_error) { die('無法連上資料庫:' . $db->connect_error); } $db->set_charset("utf8"); $type = $db->real_escape_string($_POST['sig'][0]); $content = $db->real_escape_string($_POST['sig'][1]); $sql = "INSERT INTO `canvas` ( `type`, `content`) VALUES ('{$type}', '{$content}')"; $db->query($sql) or die($db->error); $sn = $db->insert_id; echo $sn;
建立顯示用的show.php
<?php $db = new mysqli('localhost', 'root', '密碼', '資料庫'); $db->set_charset("utf8"); $sn = $db->real_escape_string($_GET['sn']); $sql = "SELECT `type`,`content` FROM `canvas` where `sn`='{$sn}'"; $result = $db->query($sql) or die($db->error); list($type, $content) = $result->fetch_row(); echo "<img src='data:" . $type . "," . $content . "'>"; echo '<a href="index.html">回首頁</a>';
若要顯示所有圖片列表,可加入:
$sql = "SELECT * FROM `canvas` order by `sn` desc"; $result = $db->query($sql) or die($db->error); while (list($sn, $type, $content) = $result->fetch_row()) { echo " <div> <a href='show.php?sn=$sn'> <img src='data:" . $type . "," . $content . "' style='width: 200px; border:1px solid gray; margin: 4px;'> </a> </div>"; }
產生實體檔案,編輯 save.php
if (strpos($type, 'svg') !== false) { file_put_contents("{$sn}.svg", $_POST['sig'][1]); } else { $data = base64_decode($_POST['sig'][1]); file_put_contents("{$sn}.png", $data); }