With the rapid development of computer and network technology, online signature technology is increasingly used in paperless offices. This intuitive and convenient operation can not only greatly improve office efficiency, but also uses digital storage methods to avoid traditional Problems such as difficulty in storing and retrieving paper signatures. In our daily lives, there are already many scenarios where online signature technology is used, such as: POS machine signature, express delivery signature, bank or government agency business signature, etc. Recently, I am working on the company's business processing needs, which also involves online signatures. We use Canvas technology to implement it. Next, let's talk about how to use Canvas to implement online signatures!
What is Canvas?Canvas is a new element in HTML5, used to draw graphics on web pages. It was introduced by Apple in the Safari 1.3 web browser. The reason for extending HTML is that the drawing capabilities of HTML in Safari can be used on the Mac OS X desktop. Dashboard component, and Apple also wanted a way to support scripted graphics in Dashboard. The two browsers, Firefox 1.5 and Opera 9, also followed Safari's lead and began to support Canvas.
Now, the Canvas tag is one of the greatest improvements in HTML5, because it allows us to implement the graphic design of web pages without using images. It is like a canvas. It has no drawing capabilities, but it displays the drawing API to client JavaScript. With the support of JavaScript, we can use it within the scope of the canvas to achieve the desired effect.
Technology selectionThis function can be implemented whether it is Canvas, SVG or Flash, but why did we choose Canvas?
First of all, since we need to support mobile platforms functionally, we can abandon Flash directly. It does not have friendly support on the mobile side, but Canvas and SVG both have good cross-platform capabilities. How do we choose? Let's compare.
Both have their own areas of expertise. Based on the above, we chose Canvas to implement the signature function.
Next, let's take a look at the implementation effect.
After understanding the source of Canvas, technology selection and final rendering effect, we will write from the five parts of creation, drawing, monitoring, redrawing and image processing. Let us enter the world of Canvas drawing together.
Create canvasFirst, we need to determine whether the browser supports Canvas:
isCanvasSupported = (): boolean => { let elem = document.createElement('canvas'); return !!(elem.getContext && elem.getContext('2d'));}
Then choose to create a Canvas or display prompts based on the judgment results.
{isCanvasSupported ? <canvas ref={canvas => (this.canvas = canvas)} height={canvasHeight} width={canvasWidth}> :Sorry, the current browser does not support this feature! }
We know that each Canvas node has a corresponding context object, which we can obtain by directly passing the string 2d as the only parameter to it through the getContext() method of the Canvas object. Next, we obtain the Canvas element through ref, and then obtain a drawing environment on the canvas through the getContext() method.
let cxt = this.canvas.getContext('2d');this.setState({cxt: cxt});
The environment is ready, let's start drawing!
drawFirst draw the starting path:
cxt.beginPath();
Then set the width of the current line:
cxt.lineWidth = 5;
Set the line color:
cxt.strokeStyle = '#000';
Through moveTo and lineTo, we draw a line
cxt.moveTo(0,0);cxt.lineTo(150,0);//Draw the defined path cxt.stroke()
However, we found that the lines drawn were rather stiff
At this time, we can change the style of the line caps at the end of the line through lineCap, and add round line caps to each end to reduce the stiffness of the lines.
cxt.lineCap = 'round';
At the same time, we can also specify the rounded corners when lines intersect by setting lineJoin.
cxt.lineJoin = 'round';
But we also found that the drawn lines have obvious jagged edges. At this time, we need to use the function of drawing element shadows provided by Canvas to blur the jagged edges. Because there are shadows, we can change the lineWidth value appropriately.
cxt.shadowBlur = 1;cxt.shadowColor = '#000';
Has it become much rounder? At this point, our method of drawing lines is ready. Next, let’s take a look at how to monitor canvas events to achieve consistent execution of drawing!
Listen to canvas eventsBecause we need to be compatible with both PC and mobile terminals, we need to determine the corresponding execution events in advance.
this.state = {events: ('ontouchstart' in window) ? ['touchstart', 'touchmove', 'touchend'] : ['mousedown', 'mousemove', 'mouseup']}
After the canvas is initialized, we start listening to events[0] events
this.canvas.addEventListener(this.events[0], startEventHandler, false);
Listen for events[1] and events[2] in the startEventHandler function
this.canvas.addEventListener(events[1], moveEventHandler, false);this.canvas.addEventListener(events[2], endEventHandler, false);
Here comes the point, our core content is to calculate and draw the crossed path
moveEventHandler(event: any): void { event.preventDefault(); const {ctx, isSupportTouch} = this.state; const evt = isSupportTouch ? event.touches[0] : event; const coverPos = this.canvas.getBoundingClientRect() ; const mouseX = evt.clientX - coverPos.left; const mouseY = evt.clientY - coverPos.top; cxt.lineTo( mouseX, mouseY ); cxt.stroke();}
As you know about Canvas, the Canvas canvas provides us with a flat space for drawing. Each point in the space has its own coordinates, x represents the horizontal coordinate, and y represents the vertical coordinate. The origin (0, 0) is located in the upper left corner of the image. The positive direction of the x-axis is to the right of the origin, and the positive direction of the y-axis is downward from the origin.
So we use the getBoundingClientRect() method to obtain the pixel distance to the left and top of the page Canvas element relative to the position of the browser window, and then use the clientX and clientY event properties to return the horizontal and vertical coordinates of the mouse pointer to the browser page when the event is triggered. Finally, the path is drawn using lineTo and stroke.
At the same time, we must remember to remove events[1] and events[2] after the events[2] event is executed, otherwise it will cause continuous drawing.
endEventHandler(event: any): void { event.preventDefault(); const {events, moveEventHandler, endEventHandler} = this.state; this.canvas.removeEventListener(events[1], moveEventHandler, false); this.canvas.removeEventListener( events[2], endEventHandler, false);}
By repeatedly looping the above event operations, our signature function is basically realized.
redrawDuring the signing process, it is inevitable to sign incorrectly or to sign too sloppily, so we need to support the function of clearing the signature. At this time, we use the clearRect() method of Canvas to help us clear the content of the canvas area.
cxt.clearRect(0, 0, canvasWidth, canvasHeight);Image processing
After drawing, we are not finished yet, we still need to upload and save the drawn signature. At this time, we can use the toDataURL() method to convert the Canvas into a general image file form.
Usually we can directly perform the operation to convert it into a data URI, and then use ajax to request the upload and that's it.
dataurl = this.canvas.toDataURL('image/png');//ordataurl = this.canvas.toDataURL('image/jpeg', 0.8);
However, due to various business needs, we sometimes need to carry other content on the page. At this time, we can use html2canvas to achieve this. html2canvas can help us take a screenshot of the entire or part of the page on the browser side and render it into a Canvas, and then we use the toDataURL() method to process it.
Speaking of html2canvas, let me give you a pitfall tip. The pictures it cuts out in some low-version browsers are blank. The reason is that flex layout is used, and html2canvas does not support -webkit-flex or -webkit-box, so it cannot Generate HTML into Canvas, resulting in a white screen capture.
Solution:Through the above steps, we have basically realized the online signature function. It is worth noting that we used the React+TypeScript environment to build this project. The actual use of the above code needs to be appropriately modified based on your own environment.
This article uses relatively shallow drawing knowledge of Canvas. If we want to use Canvas for animation production, physical effect simulation, collision detection, game development, mobile application development, and big data visualization development, we also need to review the mathematical geometry we have learned before. , physics knowledge, and then slowly exploring. Nowadays, many mature chart plug-ins are implemented using Canvas, such as Chart.js, ECharts, etc. There are many beautiful and cool charts in them, covering almost all chart implementations. Canvas also has many open source libraries, such as ZRender, createJS, Pixi.js, etc. The bottom layer of ECharts also relies on the lightweight Canvas class library ZRender for encapsulation.
Okay, let’s stop talking here today. If you have any questions, please leave a message. 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.