简体   繁体   中英

How to make a <canvas> such that user is able to draw in it? Using jQuery/JavaScript

I'm doing a project on CodeCademy and I want to know how can I make a <canvas> that takes user input to draw anything that the user wants to draw.
I have seen people do this but it draws like as if it is creating lines.
To give an example, whenever I tap anywhere in that the user have made it creates a line from the last point where I had left drawing to where I have tapped.
I do not want this.

Also, will I need to enable this by giving each pixel personal attention for precision?
If yes, then how do I make a loop for that?

Sorry for a lot of questions in a question.

EDIT : I also want the user to be able to delete what he/she made by one click at a button. And please explain the way each thing works in the code except for general syntax.

What you need to do is to "record" all of the mouse events as a user interacts with the canvas. When a mouse down event is fired, create an array containing the initial x,y coordinates. When a mouse move event is fired, append the x,y coordinates of that to the array (testing to make sure they're different to the last one). Finally when the mouse up event is fired you can "store" that array into another array of undo's.

Within your requestAnimationFrame function you need to enumerate through all of these arrays and draw them on screen. To improve performance you only need to keep 6 array's worth of plots and can buffer everything prior to that as a static element.

To really improve performance, rather than recording mouse move, you need to fire off a record function every 100ms or so to grab the current position of the mouse cursor.

The link above gives you a decent starting point, but it's not a 5 minute code job :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM