封装设置线条样式方法
代码
// 设置线条样式
class EasyCanvas {
constructor(c){
this.cav = c
this.ctx = c.getContext('2d')
}
lineStyle(width, cap, join, miter){
let ctx = this.ctx
cap ? ctx.lineCap = cap : null
join ? ctx.lineJoin = join : null
width ? ctx.lineWidth = width : null
join === 'miter' && miter ? ctx.miterLimit = miter : null
return this
}
}
分别判断传入的cap(lineCap),join(lineJoin),width(lineWidth)是否不为空,是则赋值,空则继承
miter是miterlimit属性,是指最大斜接长度,仅在join为’miter’的时候存在,因此需要join为’miter’且miter值不为空
使用示例
let ecav4 = new EasyCanvas(document.getElementById('lineStyle'))
ecav4.begin()
.lineStyle('4', 'butt', 'bevel')
.start(10,10)
.link(30,10)
.link(20,30)
.stroke()
.begin()
.lineStyle('4', 'round', 'round')
.start(40,10)
.link(60,10)
.link(50,30)
.stroke()
.begin()
.lineStyle('4', 'square', 'miter', 5)
.start(70,10)
.link(90,10)
.link(80,30)
.stroke()
图像
封装设置阴影方法
代码
// 阴影
class EasyCanvas {
constructor(c){
this.cav = c
this.ctx = c.getContext('2d')
}
shadow(blur,color,offx,offy){
let ctx = this.ctx
blur ? ctx.shadowBlur = blur : null
color ? ctx.shadowColor = color : null
offx ? ctx.shadowOffsetX = offx : null
offy ? ctx.shadowOffsetY = offy : null
return this
}
}
分别传入blur 模糊距离,color 阴影颜色,offx 阴影x轴偏移,offy 阴影y轴偏移来设置阴影参数
使用示例
绘制一个长为50的正方形并且设置其阴影模糊为10,颜色为red,x、y偏移为5
let ecav5 = new EasyCanvas(document.getElementById('shadow'))
ecav5.shadow(10,'red',5,5)
.rect(10,10,50,50)
.fill('#ccc')
图像
总结
线条与阴影的样式设置都相对简单,唯有线条样式中miter属性相对难以理解,有兴趣可以去看一下w3c中miterLimit 属性给出的解释,我个人觉得说的还是比较清楚的