Using HTML5, you can easily implement a paint application on a canvas, use a browser that supports HTML5 to paint in the area below, and to see how it works, make sure your browser supports HTML5:
function is very simple, the principle and drag and drop is similar, mainly three events: Royal Casino
- Bind the MouseDown event to the beginning of the painting (call MoveTo move brush) on the canvas
- Behavior when binding a MouseMove event on document to handle painting (call LineTo and stroke for painting)
- Binding the MouseUp event in document to the end of the mark painting (two events on document)
One of the special considerations to implement is how to pass the correct coordinate values when calling MoveTo and the LineTo method, which should be the offset of the cursor relative to the upper-left corner of the canvas, and take into account the position of the canvas in relation to the current viewport. The Getboundingclientrect method comes in handy (the browser that supports HTML5 should implement this method), and finally uses the event object's Clientx, ClientY minus Getboundingclientrect method returns the left, top value.
Here 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 a problem with the cursor style under 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 ():d ocument.selection.empty (); Clears the text from the selected This.context.moveTo (e.clientx-stage_info.left,e.clienty-stage_info.top);d ocument.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 ');//]]>
Just such a simple mouse painting function is completed, the shortcomings are also, for example, can not draw a point ... I personally think that using canvas to do drawing or relatively weak, some of the complex features are not very good to achieve, but you can also try to, for example, to add a method to save the picture, define Draw.prototype.save = function () {...}, Where the Todataurl method implementation can be called.
Make a drawing board with HTML5 Canvas