HTML5 allows you to easily implement painting applications on the canvas. You can draw images in the following area using a browser that supports html5. To see the demonstration effect, make sure that your browser supports HTML5:
Effect demonstration 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:
- Bind the mousedown event on the canvas to mark the start of the painting (call moveTo to move the paint brush)
- Bind the mousemove event on the document to process the painting behavior (call lineTo and stroke for painting)
- 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.
The following is the implementation code:
// <! [CDATA [function Draw (arg) {if (arg. nodeType) {this. canvas = arg;} else if (typeof arg = 'string') {this. canvas = document. getElementById (arg);} else {return;} this. init ();} Draw. prototype = {init: function () {var that = this; if (! This. canvas. getContext) {return;} this. context = this. canvas. getContext ('2d '); this. canvas. onselectstart = function () {return false; // fixed the cursor style issue in chrome}; this. canvas. onmousedown = function (event) {that. drawBegin (event) ;}}, drawBegin: function (e) {var that = this, stage_info = this. canvas. getBoundingClientRect (); window. getSelection? Window. getSelection (). removeAllRanges (): document. selection. empty (); // clear the selected text this. context. moveTo (e. clientX-stage_info.left, e. clientY-stage_info.top); document. onmousemove = function (event) {that. drawing (event) ;}; document. onmouseup = this. drawEnd;}, drawing: function (e) {var stage_info = this. canvas. getBoundingClientRect (); this. context. lineTo (e. clientX-stage_info.left, e. clientY-stage_info.top); this. context. stroke () ;}, drawEnd: function () {document. onmousemove = document. onmouseup = null ;}}; var draw = new Draw (the _ stage); //]>
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.