“This is the 19th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021”
🚧 Draw some common basic graphics ~
- You know, no matter how complex a graph is, it’s made up of a combination of basic shapes.
- So, let’s start by looking at how to draw various common basic shapes.
- This will be handy when designing projects that need to use Canvas!
🚓 (1) Draw a straight line
- Specify the starting (x,y) coordinates;
- Specified thickness;
- Specify the color.
Note: Use CSS to locate the Canvas element and give it a prominent border style for viewing below!
1️ discount code:
<! DOCTYPEhtml>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
/* Set canvas canvas style -- canvas border width 1px; Solid lines; Red * /
#myCanvas{
border: 1px solid red;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="300" height="250"></canvas>
</body>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
// 1. First, position the brush at the starting point;
ctx.moveTo(50.50);
// 2. Then, connect a line from the current position to the destination coordinate (note: no real line is drawn at this point!).
ctx.lineTo(100.50);
ctx.strokeStyle = "blue"; // Line color
ctx.lineWidth = "5"; // The thickness of the line
// 3. Finally, draw a line, the function is to stroke ———— this sentence is the real draw a line!
ctx.stroke(); // You can comment this line and see the effect.
</script>
</html>
Copy the code
2️ realisation effect:
🚑 (2) Draw a broken line
- Specifies the shape at the fold point.
- Specifies the shape of the end of the line.
1️ discount code:
<! DOCTYPEhtml>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#myCanvas{
border: 1px solid red;
}
</style>
</head>
<body>
<canvas id="myCanvas" width="300" height="250"></canvas>
</body>
<script type="text/javascript">
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
// 1. First, position the brush at the starting point
ctx.moveTo(50.50);
// 2. Then, connect a line from the current position to the key coordinate.
ctx.lineTo(100.50);
ctx.lineTo(60.80);
// 3. Specify a line segment endpoint shape ———— round: round; A square B. Butt: the default
ctx.lineCap = "round";
// 4. Specify the shape of the intersection point (polyline point) ———— round: Miter: default; Bevel: Cut a part of it;
ctx.lineJoin = "round";
ctx.strokeStyle = "blue"; // Line color
ctx.lineWidth = "5"; // The thickness of the line
// 5. Finally, draw a line, the function is to stroke ———— this line is the real draw line!
ctx.stroke();
</script>
</html>
Copy the code
Try changing lineCap and lineJoin multiple times to see what happens.
2️ realisation effect:
🚔 (3) Draw rectangles and circles
Try drawing solid and hollow!
Draw multiple graphs on the same drawing:
|