前期准备
要封装canvas,首先需要对其的方法api有一个全局的认识
canvas的主要方法主要有以下几类
- 线条样式 lineStyle
- 笔触颜色 color
- 阴影 shadow
- 矩形 rect
- 路径 path
- 转换 transform
- 文本 font
- 图像 img
- 像素操作 imgData
- 合成 compose
- 存储 store
为了方便去封装类,我们可以将以上几类分成两大类
基础类
- lineStyle
- color
- shadow
- rect
- path
- font
- img
扩展类
- transform
- imgData
- compose
- store
整体思路
目录结构
- src目录(存放源代码)
- main.js(存放封装canvas api的代码)
- index.js(用于展示封装canvas api的示例)
- README.md(说明文档)
链式操作
为了可以更加方便的使用,在大部分操作方法的最后的返回当前的this来支持他可以进行链式操作
function option(){
return this
}
构建实例化函数
实例化函数
class EasyCanvas {
constructor(c){
this.cav = c
this.ctx = c.getContext('2d')
}
}
封装绘图方法
文本的绘制与图像的绘制不包含在内
class EasyCanvas {
// 填充路径
fill(color){
let ctx = this.ctx
// 判断有无输入颜色,有则更换颜色,无则继承颜色
color ? ctx.fillStyle = color : null
ctx.fill()
return this
}
// 绘制路径
stroke(color){
let ctx = this.ctx
// 判断有无输入颜色,有则更换颜色,无则继承颜色
color ? ctx.strokeStyle = color : null
ctx.stroke()
return this
}
// 橡皮擦
clear(x,y,w,h){
let ctx = this.ctx
ctx.clearRect(x,y,w,h)
return this
}
// 绘制填充的矩形
fillRect(x,y,w,h){
let ctx = this.ctx
ctx.fillRect(x,y,w,h)
return this
}
// 绘制矩形路径
strokeRect(x,y,w,h){
let ctx = this.ctx
ctx.strokeRect(x,y,w,h)
return this
}
}