Recently, the company is working on a signature function, which mainly uses the canvas line drawing function combined with mobile touch events.
The js part is like this:
window.onload = function() { new lineCanvas({ el: document.getElementById(canvas),//Draw the parent div of canvas clearEl: document.getElementById(clearCanvas),//Clear button saveEl: document.getElementById(saveCanvas) ,//Save button// linewidth:1,//Line thickness, optional// color:black,//Line color, optional// background:#ffffff//Line background, optional});};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; //Start drawing this.canvas.addEventListener(touchstart, function(e) { this.cxt.beginPath(); this.cxt.moveTo(e .changedTouches[0].pageX, e.changedTouches[0].pageY); }.bind(this), false); //Drawing this.canvas.addEventListener(touchmove, function(e) { this.cxt.lineTo(e.changedTouches[0].pageX, e.changedTouches[0].pageY); this.cxt.stroke(); }.bind(this), false); //End drawing this.canvas.addEventListener(touchend, function() { this.cxt.closePath(); }.bind(this), false); //Clear the canvas this.clearEl.addEventListener(click, function() { this.cxt.clearRect(0, 0, this.canvas.width, this.canvas.height); } .bind(this), false); //Save the image and transfer it directly to base64 this.saveEl.addEventListener(click, function() { var imgBase64 = this.canvas.toDataURL(); console.log(imgBase64); }.bind(this), false);};
This is the rendering:
Attach html and css
<div id=canvas> <p id=clearCanvas>Clear</p> <p id=saveCanvas>Save</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;}
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.