HTML5 Canvas Sketchpad Example detailed

Source: Internet
Author: User
Tags linecap

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.