1.什么是canvas
HTML5 <canvas> 元素用于图形的绘制,通过脚本 (通常是JavaScript)来完成.
<canvas> 标签只是图形容器,您必须使用脚本来绘制图形。
你可以通过多种方法使用 canvas 绘制路径,盒、圆、字符以及添加图像。
2.语法
1.直线
在Canvas上画线,我们将使用以下两种方法:
- moveTo(x,y) 定义线条开始坐标
- lineTo(x,y) 定义线条结束坐标
绘制线条我们必须使用到 "ink" 的方法,就像stroke().
var canvas=document.querySelector("#box")
var pen=canvas.getContext("2d")
pen.moveTo(100,200)
pen.lineTo(400,400)
pen.stroke()
2.圆
let deg=Math.PI/180
ctx.arc(300,300,200,0*deg,270*deg,true)
ctx.stroke()
ctx.arc(x,y,r,start,end,true/false)
x与y分别为圆心的横坐标与竖坐标
start指开始的地方 单位为弧度 end指结束的地方 单位为弧度
最后的布尔值 true为顺时针 false为逆时针 默认为true
3.矩形
ctx.moveTo(200,300)
ctx.lineTo(200,500)
ctx.lineTo(400,500)
ctx.lineTo(400,300)
ctx.lineTo(200,300)
ctx.strokeStyle="red"
ctx.lineWidth=3
ctx.stroke()
ctx.closePath()//闭合轨迹 会把线连接到某一点形成闭合轨迹
ctx.fillRect(x,y,width,height)
x,y左上角点的坐标
width宽单位是像素 height长单位是像素