- canvas的定义:
canvas标签用来定义图形,是一个容器,常常用来进行绘画操作,要与js进行搭配使用 - 创建一个画布容器
width、height定义画布容器的大小
<canvas id="myCanvas" width="200" height="200" style="border:1px solid #000000;"></canvas>
- canvas本身没有绘画能力,绘画操作要在js里进行
1.通过js获取canvas对象
let c=document.getElementById("myCanvas");
- 创建context对象,context对象拥有多种绘制方法,一般通过调用获取的canvas元素对象下的getContext来创建
let ctx=c.getContext("2d");
示例
1.绘制三角形
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="200"
style="border:1px solid #000000;"></canvas>
</body>
<script>
let c=document.getElementById("myCanvas");
let ctx=c.getContext("2d");
//开始一条路径
ctx.beginPath();
ctx.moveTo(50,100);
ctx.lineTo(100,100);
ctx.lineTo(100,200);
ctx.closePath();
ctx.stroke();
</script>
</html>
2.绘制矩形
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="200"
style="border:1px solid #000000;"></canvas>
</body>
<script>
let c=document.getElementById("myCanvas");
let ctx=c.getContext("2d");
ctx.rect(50,50,100,100);
ctx.fillStyle="red";
ctx.fill();
ctx.stroke();
</script>
</html>
3.绘制圆形
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<canvas id="myCanvas" width="200" height="200"
style="border:1px solid #000000;"></canvas>
</body>
<script>
let c=document.getElementById("myCanvas");
let ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(50,50,30,0,2*Math.PI);
ctx.stroke();
</script>
</html>