玩转canvas之前期准备和封装绘图方法

前期准备

要封装canvas,首先需要对其的方法api有一个全局的认识
canvas的主要方法主要有以下几类

  1. 线条样式 lineStyle
  2. 笔触颜色 color
  3. 阴影 shadow
  4. 矩形 rect
  5. 路径 path
  6. 转换 transform
  7. 文本 font
  8. 图像 img
  9. 像素操作 imgData
  10. 合成 compose
  11. 存储 store

为了方便去封装类,我们可以将以上几类分成两大类
基础类

  1. lineStyle
  2. color
  3. shadow
  4. rect
  5. path
  6. font
  7. img

扩展类

  1. transform
  2. imgData
  3. compose
  4. 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
  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值