Many product requirements now require electronic signatures
The first solution that comes to mind is canvas artboard. By clicking and moving events, we can obtain the coordinates of sliding, and then use canvas tracing line to achieve the effect of writing on the artboard.
1. The simplest way to do this is with the following interface
this.ctx.moveTo();
this.ctx.lineTo()
Copy the code
Take a look at the effect on PC: The lines look a little rough… It’s still not obvious on the computer
Mobile terminal: you can see the obvious diamond Angle, the line is not smooth;
The reason for this is simple: moveTo and lineTo are drawn by joining two points together. Note that they are straight lines, so we can see that the drawn lines are joined one by one
2. Solutions: Quadratic Bessel curve
Quadratic Bessel curve formula:According to the formula, three points need to be known to draw a Bezier curve: starting point, ending point and control point. B(t) is any point on the curve, and t is constant. We can easily get the starting and ending points, but we can control how we get the points. So one idea I had was to take three points along the path and draw a Bezier curve, P0,P1,P2, where P0 is the starting point and P2 is the ending point, and P1 is the point through the curve, which is B (t) in the formula;
P0 (x1,y1), P2(x2,y2), Pc(cx,cy), starting point, ending point, control pointCopy the code
By substituting the formula, the control points are obtained after the calculation is simplified
cx = (x - (Math.pow(1 - t, 2) * x1) - Math.pow(t, 2) * x2) / (2 * t * (1 - t))
cy = (y - (Math.pow(1 - t, 2) * y1) - Math.pow(t, 2) * y2) / (2 * t * (1 - t))
t[0-1]
Copy the code
Through the above formula, the control points can be obtained by directly substituting coordinates; That’s how I inversely compute a quadratic Bezier curve;
Lines drawn with quadratic Bezier curves, renderings
The author uses the above method to write a uniApp component
Git address: git address
Goal, to achieve the signature board with a pen edge, there are still some problems, is to write too fast not smooth, the code is not uploaded temporarily