demand
Users need to sign or sign in the APP or applet by hand
Effect of picture
implementation
- Encapsulated as a component call
(recommended)
If you want to know how to use it, you can click to go to — [Encapsulated component edition】 - The current tutorial is used directly, not encapsulated as a component
use
Step 1: Use pages such asindex.vue
<! -- canvas --> <canvas class="mycanvas" canvas-id="mycanvas" @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend"></canvas> <! <view class="footer"> <view class="left" @click="finish"> save </view> <view class="right" @ click = "clear" > remove < / view > < the view class = "close" @ click = "close" > close < / view > < / view > < the view @click='createCanvas()'> </view>Copy the code
The canvas above is bound to a total of three methods
The method name | Reading, |
---|---|
@touchstart | Hand touch starts, gets to the starting point |
@touchmove | Hand touch moves to get to the waypoint |
@touchend | End of hand touch |
Step 2: Define the required data
Export default {data() {return {points: [], // SignatureImg: "}}}Copy the code
Step 3: Bind the method and write the logic
- CreateCanvas () –
This method is basically creating the canvas
- Touchstart () –
Touch start to get the starting point
- Touchmove () –
Touch to move to get to the waypoint
- Touchend – ()
At the end of the touch, the undrawn points are cleared to prevent interference with subsequent paths
- The draw () –
Draw the handwriting
- The clear () –
Empty canvas
- Finish () –
Complete the painting and save it locally
Methods: {createCanvas() {this.ctx = uni.createcanvasContext (' myCanvas ', this); This.ctx. lineWidth = 4; this.ctx.lineCap = 'round'; this.ctx.lineJoin = 'round'; }, touchstart(e) { let startX = e.changedTouches[0].x; let startY = e.changedTouches[0].y; let startPoint = { X: startX, Y: startY }; this.points.push(startPoint); // Each touch starts to open a new path this.ctx.beginPath(); }, touchmove(e) { let moveX = e.changedTouches[0].x; let moveY = e.changedTouches[0].y; let movePoint = { X: moveX, Y: moveY }; this.points.push(movePoint); Let len = this.points.length; if (len >= 2) { this.draw(); }}, touchend() {this.points = []; }, draw() { let point1 = this.points[0]; let point2 = this.points[1]; this.points.shift(); this.ctx.moveTo(point1.X, point1.Y); this.ctx.lineTo(point2.X, point2.Y); this.ctx.stroke(); this.ctx.draw(true); }, clear() { let that = this; uni.getSystemInfo({ success: function(res) { let canvasw = res.windowWidth; let canvash = res.windowHeight; that.ctx.clearRect(0, 0, canvasw, canvash); that.ctx.draw(true); }}); }, finish() { let that = this; uni.canvasToTempFilePath({ canvasId: 'mycanvas', success: Function (res) {// where res.tempFilepath is the signature image generated console.log(res.tempFilepath); }}); }}Copy the code
The res.tempFilepath obtained from the finish() method above is the generated signature that can be used for the rest of the business operations