1.绘制图形
先在html中定义画布大小:
<canvas id="cav" width="300px" height="300px"></canvas>
然后在script中绘制:
function draw () {
var ctx=document.getElementById("cav").getContext('2d')
// getContext():获取上下文 也就是获取运行环境 反正写canvas这步必不可少
// 先填充颜色再绘制形状
ctx.fillStyle='rgb(200,0,0)' // 填充颜色
ctx.fillRect(10,10,200,100) // 填充矩形 4个参数(x,y,图形宽,图形高)
// ctx.globalAlpha=0.5 // 设置全局透明度 设置后下方代码会受影响
ctx.fillStyle='rgba(0,0,200,0.5)' // 如果只想要当前元素透明度改变 就使用rgba
ctx.fillRect(30,30,100,200)
ctx.strokeStyle='orangered' // 描边颜色
ctx.strokeRect(80,150,100,50) // 描边 把边缘勾勒出来 4个参数(x,y,宽,高)
ctx.clearRect(80,50,100,50) // 透明矩形 显示出来的是画布颜色 而不是body的背景色
}
draw()
实现效果:

2.绘制路径
ctx.beginPath() // 起始路径 新建一条路径,生成之后,图形绘制命令被指向到路径上生成路径。
ctx.moveTo(50,30) // 起点坐标值
ctx.lineTo(200,30) // 终点坐标值
ctx.stroke() // 路径闭合(描边)
ctx.beginPath()
ctx.moveTo(50,50)
ctx.lineTo(200,50)
ctx.closePath() // 有始有终 往复画 画出来的线条更粗些 但宽高不会变
ctx.stroke()
ctx.beginPath()
ctx.moveTo(50,80)
ctx.lineTo(200,80)
ctx.lineWidth=15 //线宽
ctx.lineCap='round' // 让线条的头尾变圆 只能针对于某一条图形使用
ctx.stroke()
ctx.beginPath()
ctx.moveTo(50,120)
ctx.lineTo(200,120)
ctx.lineTo(200,200)
ctx.lineWidth=15 //线宽
ctx.lineJoin='round' // 当使用路径闭合绘制三角形时 要用lineJoin使所有的连接处变圆
ctx.closePath() // 路径闭合 首尾相连
ctx.stroke()
ctx.beginPath()
ctx.moveTo(50,180)
ctx.lineTo(200,250)
ctx.lineTo(50,250)
ctx.fill() // 当我们做路径填充fill的时候 会自动closePath 所以就不用再去写closePath了
实现效果: