1、引入js:
<script type="text/javascript" src="js/libs/esign.js"></script> <script type="text/javascript" src="js/libs/html2canvas.min.js"></script>
注:html页面需要的js请自行引入;
2、html页面:
<div id="editing_area" style=" 100%;height: 50%;border: 2px dotted silver;border-radius:25px;background:url('images/sign/sign.jpg')" > <canvas id="canvasEdit" style=" 100%;height: 100%;"></canvas> </div> <div class="hw-options text-center"> <a id="sign_clear" class="hw-btn" >清 除</a> <a id="sign_confirm" class="hw-btn" >确 定</a> </div>
3、js
根据书写路径绘制图片并调接口传递到后台:
function confirmSign() { html2canvas(document.querySelector("#canvasEdit"),{useCORS: true}).then(function(canvas) { canvas = document.getElementById("canvasEdit"); //判断用户是否签名 if(isCanvasBlank(canvas)){ alert("请签名!"); return; }
$.ajax({
url: "http://localhost:8080/jiemian/saveImg",
type:'post',
data: { pp: b64},
success:function ()
{
alert('保存成功');
}
});
//前端下载图片到本地 // downloadCanvasIamge(canvas);
});
};
//验证canvas画布是否为空函数 function isCanvasBlank(canvas) { // canvas = document.getElementById("canvasEdit"); var blank = document.createElement('canvas');//系统获取一个空canvas对象 blank.width = canvas.width; blank.height = canvas.height; //比较值相等则为空 return canvas.toDataURL() == blank.toDataURL(); } //下载Canvas元素的图片 function downloadCanvasIamge(canvas, name) { // 通过选择器获取canvas元素 canvas = document.querySelector("#canvasEdit") // 使用toDataURL方法将图像转换被base64编码的URL字符串,0.4为图片质量 var url = canvas.toDataURL('image/png',0.4) // 生成一个a元素 var a = document.createElement('a') // 创建一个单击事件 var event = new MouseEvent('click') // 将a的download属性设置为我们想要下载的图片名称,若name不存在则使用‘下载图片名称’作为默认名称 a.download = name || '下载图片名称' // 将生成的URL设置为a.href属性 a.href = url // 触发a的单击事件 a.dispatchEvent(event) }
4、后台代码
String imageDataUrl = req.getParameter("pp"); BASE64Decoder decoder = new BASE64Decoder(); byte[] b = decoder.decodeBuffer(imageDataUrl); ByteArrayInputStream bais = new ByteArrayInputStream(b); BufferedImage bi1 = ImageIO.read(bais); File w2 = new File("D://test.png"); ImageIO.write(bi1, "png", w2);