This is a simple drawing application implemented on canvas using javascript. You can draw images in the following area using a html5-supported Browser:
Your browser does not support canvas!
The function is very simple. The principle is similar to that of drag-and-drop. There are mainly three events:
1. Bind The mousedown event to the canvas to mark the start of the painting (call moveTo to move the paint brush)
2. Bind The mousemove event to the document to process the painting behavior (call lineTo and stroke for painting)
3. Bind The mouseup event on the document to mark the end of the painting (unbind two events on the document)
Note how to pass the correct coordinate value when calling the moveTo and lineTo methods. The coordinate value should be the offset of the cursor relative to the upper left corner of the canvas, when obtaining the image, you need to consider the position of the canvas relative to the current view. The getBoundingClientRect method is useful (this method should be implemented by browsers that support HTML5). Finally, the clientX of the event object is used, clientY minus left and top returned by the getBoundingClientRect method.
In this way, a simple mouse painting function is completed, and there are also shortcomings, such as the inability to draw points... I personally think it is still relatively weak to use canvas for drawing, and complicated functions are not very easy to implement. However, you can try to add a method to save the image, for example, define Draw. prototype. save = function (){...}, you can call the toDataURL method.
Here is a good HTML5 canvas tutorial for beginners to learn ~
<! DOCTYPE html>
Tip: valid only for IE9, Chrome, and Firefox!