This article will guide you through using canvas and JavaScript to create a simple drawing program.
Prepare the container canvas element first, and everything will be in JavaScript.
1 < ID= "Canvasinaperfectworld" width= "490" height= "220" ></canvas>
Gets the drawing environment in which the context object provides methods and properties for drawing on the canvas
1 context = document.getElementById (' Canvasinaperfectworld '). GetContext ("2d");
Start the drawing process
First we need to store the plot path point coordinates, the AddClick function adds coordinate point values to the array
var New Array (); var New Array (); var New Array ();//storage path Point var paint; // whether to draw, MouseDown to True function AddClick (x, y, dragging) { clickx.push (x); Clicky.push (y); Clickdrag.push (dragging);}
The redraw function is redrawn every time the entire canvas is called. First we empty the canvas and set the lines to draw the line color and weight line connection. And then
Draw a path between two points and draw the coordinate points in the array sequentially
1 functionRedraw () {2Context.clearrect (0, 0, context.canvas.width, context.canvas.height);//Clear Canvas Content3 4Context.strokestyle = "#df4b26";//Set Line Color5Context.linejoin = "Round";//creates a rounded corner when two lines intersect6Context.linewidth = 5;//Line Thickness7 8 for(vari=0; i < clickx.length; i++) { 9Context.beginpath ();//start a path, or reset the current pathTen if(Clickdrag[i] &&i) { OneContext.moveto (Clickx[i-1], clicky[i-1]); A}Else{ -Context.moveto (clickx[i]-1, Clicky[i]); - } the Context.lineto (Clickx[i], clicky[i]); - Context.closepath (); -Context.stroke ();//Draw Path - } +}
Events required by the drawing process
1 MouseDown Events
This event execution is triggered when the drawing is clicked onto the canvas. The AddClick function is called and the paint is set to true.
1$ (' #canvas '). MouseDown (function(e) {2 varMouseX = E.pagex- This. offsetleft;3 varMousey = E.pagey- This. OffsetTop;5Paint =true;6AddClick (E.pagex- This. offsetleft, E.pagey- This. OffsetTop);7 redraw ();8});
2 MouseMove Events
When the paint set in MouseDown is true, the mouse movement triggers the MouseMove event execution, records all points of the mouse movement, and constantly calls redraw to redraw the canvas.
1 $ (' #canvas '). MouseMove (function(e) {2 if(paint) { 3This is true); 4 Redraw (); 5 }6 });
3 MouseUp Events
MouseUp after the mouse click Release or drag and release, indicating that the drawing completed the path, the paint is set to false.
1 $ (' #canvas '). MouseUp (function(e) {2 false; 3 });
4 MouseLeave Events
MouseLeave the mouse away from the canvas element and set the paint to false.
1 $ (' #canvas '). MouseLeave (function(e) {2 false; 3 });
Create a drawing program with HTML5 canvas and JavaScript