<canvas id = mycanvas width = 400 height = 200>
The default <CANVAS> canvas display a blank, borderless rectangle on the page. In order to make it display the contour, add a dotted bezel to it by defining the rules of the style:
Canvas {border: 1px dashed black;}2. Get the context of Canvas
To complete the drawing task, first of all, we have to get the <CANVAS> object, and then obtain its two -dimensional drawing context.
The following sample demonstration is obtained by the drawing of the drawing when the page is loaded:
<script> Window.Onload = Function () {var canvas = document.GetelementByid (mycanvas); var contentXt = Canvas.GetContext (2D); // Write drawing code} </script>3, draw straight line
(1) The starting point is (50,50) below (50,50), and the ending point is (150,150) straight line lines
context.moveto (50, 50); context.lineto (150, 150); context.stroke ();
(2) Set the width and color of the lines with LINEWIDTH and Strokestyle attributes
// line width context.lineWidth = 10; // Line color (supports color coding and RGB () function) context.strokestyle = #cd2828; context.Strokestyle = RGB (205,40,40); Context.Moveto ( 50, 50); context.lineto (150, 150); context.stroke ();
(3) Set the shape of both ends of the line (line head type) with the linecap property:
var canvas = document.GetelementByid (mycanvas); Var Context = Canvas.getContext (2D); // line width context.lineWidth = 10; // line color context.Stroketyle = # CD2828; // The first straight line, the default side Tore Context.moveto (50, 50); context.lineto (250, 50); context.stroke (); // The second straight line, use round head context.beginpath (); context.moveto (50, 100); Context.lineto (250, 100); context.linecap = Round; context.stroke (); // The third line of straight line, context.moveto (50, 150); context.Lineto O (250, 150); context.linecap = square; context.stroke ();Note: The beginpath () method of drawing context
The above example can see that every time the new line segment is drawn, the Beginpath () method is called.
Without this step, every time you call Stroke (), you will re -draw the original line segment on the canvas. Especially like the example above, the context attributes must be modified when drawing a new line. If the Beginpath () method is not called, the original straight line will also be drawn with new styles.