function is simple, the principle and drag-and-drop is similar, mainly three events:
Bind the MouseDown event at Canvas to flag the start of painting (Invoke MoveTo move brush)
Behavior when the document is bound MouseMove events to handle painting (call LineTo and stroke for painting)
Bind the MouseUp event in document to mark the end of painting (two events on the binding document)
A special note to realize is how to pass the correct coordinate value when invoking MoveTo and LineTo methods, which should be the offset of the cursor relative to the upper-left corner of the canvas, taking into account the position of the canvas phase to the current viewport. The Getboundingclientrect method comes in handy (the browser that supports HTML5 should all implement this method), and ends with the clientx of the event object, ClientY minus the Getboundingclientrect method returns the left and top values.
The implementation code is as follows:
<! [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; Fix the 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 ():
Document.selection.empty (); Clear text for selection
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 (' draw_stage ');
]]>
So a simple mouse painting function is done, the deficiencies are also, such as not able to draw points ... I personally think that the use of canvas to do drawing or relatively weak, the complexity of some of the function is not very good to achieve, but you can also try oh, such as to add a way to save the picture, define Draw.prototype.save = function () {...}, Where you can invoke the Todataurl method implementation.