1.Canvas绘制步骤
1)向Html5页面添加canvas元素
2)用过JS获取canvas对象,并创建contex对象
3)指定绘路径以及样式
4)开始绘制
2.图形绘制
1)绘制直线
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>canvas2d绘制</title>
</head>
<body>
<canvas id="can" height="500" width="500"></canvas>
<script type="text/javascript">
var canvas = document.getElementById("can");
var ctx = canvas.getContext("2d");
ctx.moveTo(100, 100);
ctx.lineTo(300, 300);
ctx.lineTo(100,00)
ctx.stroke()
</script>
</body>
</html>
2)绘制圆
绘制空心圆
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>canvas绘制圆形</title>
</head>
<body>
<canvas id="can" height="500" width="500"></canvas>
<script>
const canvas = document.getElementById("can");
let ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(200, 200, 100, 0 * Math.PI, 2 * Math.PI, true);
ctx.closePath();
ctx.stroke();
</script>
</body>
</html>
绘制有填充色的圆
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>canvas绘制圆形</title>
</head>
<body>
<canvas id="can" height="500" width="500"></canvas>
<script>
const canvas = document.getElementById("can");
let ctx = canvas.getContext("2d");
ctx.fillStyle="#000"
ctx.beginPath();
ctx.arc(200, 200, 100, 0 * Math.PI, 2 * Math.PI, true);
ctx.closePath();
ctx.stroke();
ctx.fill()
</script>
</body>
</html>
3)绘制渐变色条
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>绘制线条的渐变</title>
</head>
<body>
<canvas id="can" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById("can");
let ctx = canvas.getContext("2d");
let grd = ctx.createLinearGradient(0, 0, 500, 500);
grd.addColorStop(0, "red");
grd.addColorStop(0.5, "blue");
grd.addColorStop(1, "yellow");
ctx.fillStyle = grd;
ctx.fillRect(0,0,500,500)
</script>
</body>
</html>
4)空心字
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>空心字</title>
</head>
<body>
<canvas id="can" width="500" height="500"></canvas>
<script>
const canvas = document.getElementById("can");
let ctx = canvas.getContext("2d");
ctx.font='30px Arial'
ctx.fillText('xiaowu',10,50)
ctx.strokeText('xuxi',10,200)
</script>
</body>
</html>