HTML5-Canvas Drawing (1)
Draw lines and polygons
Step 1: define canvas. Step 2: Get cancas and context. Step 3: Draw a line
Step 1: Define canvas
<canvas id="canvas" width="500" height="500"
style="border:1px solid #aaa; display:block; margin: 50px auto">
</canvas>
Copy the code
Get the Canvas from window.onload = function() via doucument.getelementById (” canvas “)
window.onload = function() {
var mCanvas = document.getElementById("canvas");
var mContext = canvas.getContext("2d");
}
Copy the code
McOntext.moveto (x, y) starting point McOntext.lineto (x0, y0) defines the end of the execution or the passing point of the polygon
Note:
Using both methods is state, which does not draw, but must call Stroke () to draw
Set the style of the line: property lineWidth strokeStyle
mContext.lineWidth = 10; McOntext. strokeStyle = "#005588"; // Line style, can use CSS style, generally use string styleCopy the code
Use McOntext.fill () to fill the interior of the polygon with the triangle below
mContext.fillStyle = "green";
mContext.fill();
Copy the code
- –
Note that the end and start calls to two methods for each edge
** mContext.beginPath(); mContext.closePath(); 支那
mContext.beginPath(); mContext.moveTo(200, 200); // start McOntext. lineTo(400, 400); // end McOntext. lineTo(200, 400); mContext.lineTo(200, 200); mContext.closePath();Copy the code
<! PUBLIC DOCTYPE HTML "- / / / / W3C DTD HTML 4.01 Transitional / / EN" "http://www.w3.org/TR/html4/loose.dtd" > < HTML > < head > < meta http-equiv="Content-Type" content="text/html; Charset =UTF-8"> <title>Insert title here</title> </head> <body> <p>Canvas Canvas </p> < Canvas ID =" Canvas "width="1024" height="768" style="border:1px solid #aaa; display:block; margin: 50px auto"> </canvas> <! <script type="text/javascript"> window.onload = function() {var mCanvas = document.getElementById("canvas"); var mContext = canvas.getContext("2d"); If (mContext == null){document.write(" Current browser cannot use Canvas "); } // Use context to draw // start and end state McOntext.beginpath (); mContext.moveTo(200, 200); // start McOntext. lineTo(500, 500); // end McOntext. lineTo(200, 500); mContext.lineTo(200, 200); mContext.closePath(); mContext.fillStyle = "green"; mContext.fill(); mContext.lineWidth = 10; McOntext. strokeStyle = "#005588"; // Call McOntext.stroke (); // Call McOntext.stroke (); mContext.beginPath(); mContext.moveTo(400, 400); mContext.lineTo(400, 500); mContext.closePath(); mContext.strokeStyle = "red"; mContext.stroke(); }; </script> </body> </html>Copy the code