- 通过const cvs = document.querySelector(‘canvas’)拿到DOM元素
- 通过const ctx = cvs.getcontext(“2d”)拿到CanvasRenderingContext2D的类型对象
- 开启一条路径ctx.beginPath()
- 开始位置ctx.moveTo(x,y)
- 结束位置ctx.lineTo(x,y)
- 进行上色ctx.stroke()
- 关闭路径ctx.closePath()
- 设置绘线的粗细ctx.lineWidth,默认值为1.0
- 设置线段端点显示的样子,butt,round 和 square
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<style>
canvas{
margin: 0 auto;
border: 1px solid #000;
display: block;
}
</style>
</head>
<body>
<canvas width="500" height="500"></canvas>
<script>
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
// 画虚线
for (let i = 0; i < 20; i++) {
drawLine(100+10\*i,100,105+10\*i,100,'green',2)
}
function drawLine(x1,y1,x2,y2,color,width){
ctx.beginPath();
ctx.moveTo(x1,y1);
ctx.lineTo(x2,y2);
ctx.strokeStyle=color;
ctx.lineWidth=width;
ctx.stroke();
ctx.closePath();
}
</script>
</body>
</html>
画矩形
- rect(x,y,width,height)
- strokeRect(x,y,width,height)
- fillRect(x,y,width,height)
- clearRect(x,y,width,height)
画圆
- arc(x,y,radius,startAngle,endAngle,counterclockwise