Canvas作为前端的画图工具,其实用途还是蛮广泛的,但是很多前端学习课程其实都很少涉及到这块内容。
于是乎,就写下这个了。
当然啦,目前还在学习摸索中。
一些实战代码,仅供参考:
-
- id="ctx"
- width="300px"
- height="300px"
- style="border: 1px solid;margin: 100px 0 0 666px;"
- >
-
-
-
-
- // 通过id去获取canvas,这里不需要#
- const myCtx = document.getElementById('ctx')
-
- // 通过getContext()方法创建2d平面
- const ctx = myCtx.getContext("2d")
-
- // --------------------------------------------
-
- // 要求:画一个矩形
- // ctx.rect(100, 100, 100, 100)
- // 前面两个是起始的坐标位置,后面两个是宽高
-
- // 改变笔头
- // ctx.strokeStyle = "red"
-
- // 设置画笔的像素值
- // ctx.lineWidth = 3
-
- // 使用stroke()是画出形状,不会填充
- // ctx.stroke()
-
- // 使用fill是填充的意思
- // ctx.fill()
-
- // --------------------------------------------
-
- // 使用简单方法画矩形
-
- // 改变笔头
- // ctx.strokeStyle = "red"
-
- // 使用strokeRect()画出
- // ctx.strokeRect(125, 125, 50, 50)
-
- // 使用fillStyle,改变画笔颜色
- // ctx.fillStyle = "red"
-
- // 使用fillRect()填充
- // ctx.fillRect(100, 100, 100, 100)
-
- // 使用clearRect()清空
- // ctx.clearRect(125, 125, 50, 50)
-
- // -------------------------------------
-
- // 画一个三角形
-
- // 移动笔尖
- // ctx.moveTo(30, 40)
-
- // 先画出一条横线
- // ctx.lineTo(270, 40)
-
- // 再画出一条竖线
- // ctx.lineTo(270, 260)
-
- // 回到起点,闭合整个曲线
- // ctx.closePath()
-
- // -------------------------------------
-
- // 画一个圆形
-
- // 最后结束角不能是0,圆形必须是2*Math.PI
- // 还有个参数的——关于画的方向的,但是默认是顺时针,这里使用默认效果。
- // 从X轴开始出发,X轴算是0°
- // ctx.arc(150, 150, 50, 0, 2 * Math.PI)
-
- // 改变颜色
- // ctx.strokeStyle = "blue"
-
- // 完成绘图
- // ctx.stroke()
-
- // 改变填充颜色
- // ctx.fillStyle = "red"
-
- // 完成绘图
- // ctx.fill()
-
- // -------------------------------------
-
- // 画一个椭圆 - 不闭合的
- ctx.arc(150, 150, 88, 0, 1.8*Math.PI)
-
- // 改变画笔颜色
- // ctx.strokeStyle = "orange"
-
- // 完成绘图
- // ctx.stroke()
-
- // 改变填充颜色
- // ctx.fillStyle = "green"
-
- // 完成绘图 - 有bug - 并不是椭圆,而是被切了一小块的圆
- // ctx.fill()
-
- // 完善 - 闭合图案
- // 笔尖回到圆点
- // ctx.lineTo(150, 150)
-
- // 两段闭合
- // ctx.closePath()
-
- // 填充
- // ctx.fill()
-
- // -----------------------------------
-
- // 画一个圆
- ctx.arc(150, 150, 100, 0, 1.6 * Math.PI)
-
- // 要求:渐变色的椭圆形
-
- // 设置线性渐变色
- // const gradient = ctx.createLinearGradient(200, 200, 50, 50)
-
- // 设置放射状渐变色 - 在起始和结尾坐标处添加了半径
- const gradient = ctx.createRadialGradient(180, 180, 100, 75, 75, 100)
-
- // 添加颜色 - 注意前面的数字和后面的颜色
- gradient.addColorStop(0, "black")
- gradient.addColorStop("0.5", "#999")
- gradient.addColorStop("0.8", "red")
- gradient.addColorStop(1, "blue")
-
- // 直接填充
- ctx.fillStyle = gradient
-
- // 笔尖回到圆点
- ctx.lineTo(150, 150)
-
- // 两段闭合
- ctx.closePath()
-
- // 完成绘图
- ctx.fill()
注意最后一个椭圆的闭合的实现:
闭合前:

闭合后:

增加了渐变色的处理。
线性渐变和放射状渐变方法差不多,只不过创建函数有所区别。
其中放射状渐变需要注意的是,半径最好跟圆的半径一致,否则就会出现:

本节完。