html5 利用canvas手寫簽名并保存的實(shí)現(xiàn)方法
發(fā)布時(shí)間:2018-07-12 15:35:15 作者:金大光
我要評(píng)論

這篇文章主要介紹了html5 利用canvas手寫簽名并保存的實(shí)現(xiàn)方法的相關(guān)資料,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
最近公司在做一個(gè)簽名的功能,主要用到了canvas畫線的功能結(jié)合移動(dòng)端touch事件
js部分是這樣的:
window.onload = function() { new lineCanvas({ el: document.getElementById("canvas"),//繪制canvas的父級(jí)div clearEl: document.getElementById("clearCanvas"),//清除按鈕 saveEl: document.getElementById("saveCanvas"),//保存按鈕 // linewidth:1,//線條粗細(xì),選填 // color:"black",//線條顏色,選填 // background:"#ffffff"//線條背景,選填 }); }; function lineCanvas(obj) { this.linewidth = 1; this.color = "#000000"; this.background = "#ffffff"; for (var i in obj) { this[i] = obj[i]; }; this.canvas = document.createElement("canvas"); this.el.appendChild(this.canvas); this.cxt = this.canvas.getContext("2d"); this.canvas.width = this.el.clientWidth; this.canvas.height = this.el.clientHeight; this.cxt.fillStyle = this.background; this.cxt.fillRect(0, 0, this.canvas.width, this.canvas.width); this.cxt.strokeStyle = this.color; this.cxt.lineWidth = this.linewidth; this.cxt.lineCap = "round"; //開始繪制 this.canvas.addEventListener("touchstart", function(e) { this.cxt.beginPath(); this.cxt.moveTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY); }.bind(this), false); //繪制中 this.canvas.addEventListener("touchmove", function(e) { this.cxt.lineTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY); this.cxt.stroke(); }.bind(this), false); //結(jié)束繪制 this.canvas.addEventListener("touchend", function() { this.cxt.closePath(); }.bind(this), false); //清除畫布 this.clearEl.addEventListener("click", function() { this.cxt.clearRect(0, 0, this.canvas.width, this.canvas.height); }.bind(this), false); //保存圖片,直接轉(zhuǎn)base64 this.saveEl.addEventListener("click", function() { var imgBase64 = this.canvas.toDataURL(); console.log(imgBase64); }.bind(this), false); };
這是效果圖:
附上html和css
<div id="canvas"> <p id="clearCanvas">清除</p> <p id="saveCanvas">保存</p> </div> html,body{ width: 100%; height: 100%; } #canvas{ width: 100%; height: 100%; position: relative; } #canvas canvas{ display: block; } #clearCanvas{ width: 50%; height: 40px; line-height: 40px; text-align: center; position: absolute; bottom: 0; left: 0; border: 1px solid #DEDEDE; z-index: 1; } #saveCanvas{ width: 50%; height: 40px; line-height: 40px; text-align: center; position: absolute; bottom: 0; right: 0; border: 1px solid #DEDEDE; z-index: 1; }
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
canvas畫布實(shí)現(xiàn)手寫簽名效果的示例代碼
這篇文章主要介紹了canvas畫布實(shí)現(xiàn)手寫簽名效果的示例代碼的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨2019-04-23- 公司新做了個(gè)功能,一些審核的地方需要加入一些手寫簽名的功能,本文就介紹了html5手寫簽名的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2023-07-17