Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use canvas to realize online signature in html

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the html how to use canvas to achieve online signature related knowledge, the content is detailed and easy to understand, the operation is simple and fast, with a certain reference value, I believe that after reading this html article on how to use canvas to achieve online signature will have a harvest, let's take a look.

What is Canvas?

Canvas is a new element of HTML5 for drawing graphics on web pages. It was introduced by Apple in Safari 1.3 Web browser. The reason for the expansion of HTML is that the drawing ability of HTML in Safari can be used by the Dashboard component of the Mac OS X desktop, and Apple also hopes that there is a way to support scripted graphics in Dashboard. The two browsers, Firefox 1.5 and Opera 9, followed the lead of Safari and began to support Canvas.

Now, Canvas tag is one of the greatest improvements of HTML5, because it allows us to implement the graphic design of web pages without using pictures. It is like a canvas, it does not have the ability to draw, but it shows the rendering API to the client JavaScript. With the support of JavaScript, we play fully within the canvas to achieve the desired effect.

Technology selection

This function, whether it is Canvas, SVG or Flash, can be implemented, but why did we choose Canvas?

First of all, because we need to support the mobile platform functionally, we can just abandon Flash. It does not get friendly support on the mobile side, but both Canvas and SVG have good cross-platform capabilities. How do we choose? let's compare it below.

Canvas is based on pixels, provides 2D rendering function, and provides more primitive functions. It is suitable for pixel processing, dynamic rendering and large amount of data rendering. It is highly controllable. When the rendering process is basically unrecorded, the drawing performance will be better. The major manufacturers have also implemented the hardware acceleration mechanism of canvas.

SVG for vectors, provides a series of graphic elements, more functional, established a large number of interactive objects, the nature is longer than interaction, but the performance will be weaker, more suitable for static picture display, high-fidelity document viewing and printing application scenarios.

Both of them have their own areas of expertise, based on the above, we chose Canvas to achieve the signature function.

Next, let's take a look at the results.

After understanding the source, technology selection and final rendering effect of Canvas, we will write it from five parts: creation, drawing, monitoring, redrawing and image processing. Let's go into the world of Canvas drawing.

Create a canvas

First, we need to determine whether the browser supports Canvas:

IsCanvasSupported = (): boolean = > {let elem = document.createElement ('canvas'); return! (elem.getContext & & elem.getContext (' 2d'));}

Then choose whether to create the Canvas canvas or display the prompt according to the judgment result.

{isCanvasSupported? (this.canvas = canvas)} height= {canvasHeight} width= {canvasWidth} >: sorry, this feature is not supported by the current browser! }

We know that each Canvas node has a corresponding context object, and we can get it by passing the quantity string "2d" directly to it as the only parameter through the getContext () method of the Canvas object. Next, we get the Canvas element through ref, and then use the getContext () method to get an environment for drawing on the canvas.

Let cxt = this.canvas.getContext ('2d'); this.setState ({cxt: cxt})

The environment is ready, so let's start the drawing work.

Draw

First draw the start path:

Cxt.beginPath ()

Then set the width of the current line:

Cxt.lineWidth = 5

Set the color of the line:

Cxt.strokeStyle ='# 000'

With moveTo and lineTo, let's draw a line

Cxt.moveTo (0Magne0); cxt.lineTo (150dy0); / / 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 cap at the end of the line through lineCap and add a round cap to each end to reduce the stiffness of the line.

Cxt.lineCap = 'round'

At the same time, we can set lineJoin to specify a circular corner when the lines meet.

Cxt.lineJoin = 'round'

But we also find that the lines drawn have obvious aliasing, so we need to blur the aliasing of the edges with the help of the function of drawing element shadows provided by Canvas. Because there are shadows, we can change the lineWidth value appropriately.

Cxt.shadowBlur = 1bot cxt.shadowColor ='# 000'

Has it become much more rounded? at this point, our method of drawing the circuit is ready. Next, let's take a look at how to monitor canvas events to achieve consistent rendering.

Monitor canvas events

Because we need to be compatible with both the PC side and the mobile side, we need to determine the corresponding events in advance

This.state = {events: ('ontouchstart' in window)? ['touchstart',' touchmove', 'touchend']: [' mousedown', 'mousemove',' mouseup']}

After the canvas is initialized, we start listening for the events [0] event

This.canvas.addEventListener (this.events [0], startEventHandler, false)

Listen for events [1] and events [2] events in the startEventHandler function

This.canvas.addEventListener (events [1], moveEventHandler, false); this.canvas.addEventListener (events [2], endEventHandler, false)

The point is, our core content is to calculate and depict the 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 ();}

For those of you who know Canvas, the Canvas canvas provides us with a flat space for drawing. Each point in this space has its own coordinates, x for Abscissa and y for vertical coordinates. The origin (0,0) is located in the upper-left corner of the image, the positive direction of the x-axis is the origin to the right, and the positive direction of the y-axis is the origin downward.

So we get the pixel distance of the Canvas element of the page relative to the left and top of the browser window through the getBoundingClientRect () method, and then use the clientX,clientY event property to return the horizontal and vertical coordinates of the mouse pointer to the browser page when the event is triggered, and finally draw the path through lineTo and stroke.

At the same time, we should remember to remove the events [1] and events [2] events after the events [2] event is executed, otherwise it will result in 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 repeating the above event operations over and over again, our signature function is basically realized.

Redraw

During the signing process, it is inevitable to sign wrong or scribbled too much, so we need to support the function of emptying the signature. At this time, we can use Canvas's clearRect () method to help us clear the canvas area.

Cxt.clearRect (0,0, canvasWidth, canvasHeight)

Picture processing

After drawing, we are not finished yet, we still need to upload and save the drawn signature. At this point, we can use the toDataURL () method to convert Canvas into a general image file form.

Usually we execute it directly to convert it to data URI, and then use ajax to request upload.

Dataurl = this.canvas.toDataURL ('image/png'); / / ordataurl = this.canvas.toDataURL (' image/jpeg', 0.8)

However, due to a variety of business needs, we sometimes need to carry other content of the page, at this time, we can use html2canvas to achieve. Html2canvas can help us take a screenshot of all or part of the page on the browser side and render it into a Canvas, and then we are using the toDataURL () method to deal with it.

Speaking of html2canvas, by the way, I will give you a hint to go around the hole. The image it captured in some low-version browsers is blank because it uses flex layout, but html2canvas does not support-webkit-flex or-webkit-box, so it is impossible to generate Canvas from HTML, resulting in a blank screen.

Solution:

Do not use flex layout

Modify the html2canvas source code to add-webkit-flex and-webkit-box to the html2canvasdist pmparsingdisplay.js file and also return DISPLAY.FLEX; summary

Through the above steps, we have basically realized the function of online signature. It is worth noting that the React+TypeScript environment we used to build this project, the actual use of the above code needs to be modified according to our own environment.

This paper uses Canvas relatively shallow rendering knowledge, if you want to use Canvas into animation production, physical effects simulation, collision detection, game development, mobile application development, big data visual development, we also need to review the previous knowledge of mathematical geometry, physics, and then slowly explore. Now many mature chart plug-ins are implemented in Canvas, such as Chart.js, ECharts, etc., there are many good-looking and cool charts, covering almost all the chart implementation. Canvas also has many open source class libraries, such as ZRender, createJS, Pixi.js and so on. The bottom layer of ECharts also relies on the lightweight Canvas class library ZRender for encapsulation.

This is the end of the article on "how to use canvas to achieve online signature in html". Thank you for reading! I believe that everyone has a certain understanding of the knowledge of "how to use canvas to achieve online signature in html". If you want to learn more, you are welcome to follow the industry information channel.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report