Code
Note: The code in this article was introduced with JQuery.
code is as follows |
copy code |
Mycanvas.linewidth = 5 Mycanvas.strokestyle =" Blue "; Mycanvas.linecap = "Round"; var paint = 0; $ ("#myCanvas"). MouseDown (function (e) { var mousex = E.pagex-this.offset Left; var mousey = e.pagey-this.offsettop; paint = 1; mycanvas.moveto (MouseX, Mousey); }); $ ("#myCanvas"). MouseUp (function (e) { paint = 0; }); $ ("#myCanvas"). MouseMove (function (e) { var mousex = e.pagex-this.offsetleft; var mousey = E.PA Gey-this.offsettop; if (paint) { mycanvas.lineto (mousex, mousey); mycanvas.stroke (); &NBSP} }); |
Analytical
The above code, first and before the same line as three attributes, before the LineCap, said that the end of the line is what kind of, round for rounded corners, in order to make the picture of the painting useless so blunt.
Then a variable paint specifies whether to allow drawing when the pointer moves, which means that the effect we want is to have the mouse pressed and the pointer in the effective area of the canvas to draw, which is to prevent the mouse from not being pressed or released and still drawn.
MouseDown () event, when the mouse is pressed, first get the mouse for the canvas relative coordinates, and then the paint changed to true, that is, allow drawing, and establish a starting point.
MouseUp () event, the mouse loosened, the paint changed to false, not allowed to continue to draw.
The MouseMove () event, mouse movement, gets the mouse relative coordinates to the canvas, and then if the paint is true, allowing the drawing to create a point line and end.
Because it's so much more, it's like a messy line.
This is just a simple example, you can certainly set aside a few buttons and input boxes to allow the user to control the line width, style to empty the canvas, save the drawn graphics and so on.