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:
The function is very simple, the principle and drag and drop is similar, mainly three events:
- Bind the MouseDown event to the beginning of the painting (call MoveTo move brush) in the canvas casino Macau
- 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:
View Source print?
05 |
} else if ( typeof arg == ‘string‘ ) { |
06 |
this .canvas = document.getElementById(arg); |
15 |
if (! this .canvas.getContext) { |
18 |
this .context = this .canvas.getContext( ‘2d‘ ); |
19 |
this .canvas.onselectstart = function () { |
20 |
return false ; //修复chrome下光标样式的问题 |
22 |
this .canvas.onmousedown = function (event) { |
23 |
that.drawBegin(event); |
26 |
drawBegin: function (e) { |
28 |
stage_info = this .canvas.getBoundingClientRect(); |
29 |
window.getSelection ? window.getSelection().removeAllRanges() : |
30 |
document.selection.empty(); //清除文本的选中 |
32 |
e.clientX - stage_info.left, |
33 |
e.clientY - stage_info.top |
35 |
document.onmousemove = function (event) { |
38 |
document.onmouseup = this .drawEnd; |
40 |
drawing: function (e) { |
41 |
var stage_info = this .canvas.getBoundingClientRect(); |
43 |
e.clientX - stage_info.left, |
44 |
e.clientY - stage_info.top |
46 |
this .context.stroke(); |
49 |
document.onmousemove = document.onmouseup = null ; |
52 |
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