认识canvas(画扇形 动态画圆弧(requestAnimationFrame结合settimeout做的动画)、画表盘)

27次阅读

共计 2432 个字符,预计需要花费 7 分钟才能阅读完成。

最近做的两个项目都是关于 canvas 的,做完整理一下,方便下一次使用,在 vue 里写的小 demo,功能:画扇形 动态画圆弧(requestAnimationFrame 结合 settimeout 做的动画)、画表盘 1、创建一个 ctx 对象
2、begain() 方法开始画笔
3、fillStyple 设置填充颜色 [strokeStyle]
4、arc(x,y,r,startAngle,endAngle,direction) true 是顺时针 false 是逆时针 默认是逆时针
5、closePath() 结束画笔 开始填充 fill() [没有 closePah 直接 stroke()]
mounted () {
this.$nextTick(() => {
/*
1、创建一个 ctx 对象
2、begain() 方法开始画笔
3、fillStyple 设置填充颜色 [strokeStyle]
4、arc(x,y,r,startAngle,endAngle,direction) true 是顺时针 false 是逆时针 默认是逆时针
5、closePath() 结束画笔 开始填充 fill() [没有 closePah 直接 stroke()]
*/
// 封装画扇形
let ctx = this.$refs.can01.getContext(‘2d’)
this.drawFanShapes(ctx, 400, 400, 0, 0, 150, ‘red’, false)
this.drawFanShapes(ctx, 400, 400, 0, 120, 200, ‘green’, false)
// 动态画圆弧
let ctx02 = this.$refs.can02.getContext(‘2d’)
this.drawArc(ctx02, 400, 400, 100, 0, 360, ‘#ddd’, 10, ’round’, false)
let globalAni = null
let endAngle = 0
let _self = this
function animate () {
let timer = setTimeout(() => {
globalAni = requestAnimationFrame(animate)
if (endAngle < 270) {
endAngle += 10
_self.drawArc(ctx02, 400, 400, 100, 0, endAngle, ‘green’, 10, ’round’, false)
} else {
clearTimeout(timer)
cancelAnimationFrame(globalAni)
}
}, 20)
}
globalAni = requestAnimationFrame(animate)
// 画时钟表盘
let ctx03 = this.$refs.can03.getContext(‘2d’)
this.drawClock(ctx03, 200, 200, 60, -180 – 160, 1, ‘red’)
})
},
methods: {
// 画表刻度(ctx,x,y, 刻度数,startX, endY,lineWidth, strokeColor)
drawClock (ctx, x, y, num, startX, endY, lineWidth, strokeColor) {
for (let i = 0; i < 60; i++) {
ctx.save()
ctx.lineWidth = 1
ctx.strokeStyle = ‘red’
ctx.translate(200, 200)
ctx.rotate(6 * i * Math.PI / 180)
ctx.beginPath()
ctx.moveTo(0, -180)
ctx.lineTo(0, -160)
ctx.stroke()
ctx.restore()
}
},
// 画扇形 (ctx,width,height,半径 [0 自动算半径],开始角度,结束角度,填充颜色,方向 )
drawArc (ctx, width, height, radius, startAngle, endAngle, strokeColor, lineWidth, round, direction) {
ctx.save()
let basic = {
x: width / 2,
y: height / 2,
r: (!radius) ? (width – lineWidth) / 2 : radius,
startAngle: (startAngle / 180) * Math.PI,
endAngle: (endAngle / 180) * Math.PI,
direction: direction || false
}
ctx.beginPath()
ctx.strokeStyle = strokeColor
ctx.lineWidth = lineWidth
ctx.arc(basic.x, basic.y, basic.r, basic.startAngle, basic.endAngle, direction)
ctx.lineCap = round
ctx.stroke()
ctx.restore()
},
// 画圆弧 (ctx,x,y,半径 [0 自动算半径],开始角度,结束角度,画的颜色,是否圆角,方向 )
drawFanShapes (ctx, width, height, radius, startAngle, endAngle, fillColor, direction) {
let basic = {
x: width / 2,
y: height / 2,
r: (!radius) ? width / 2 : radius,
startAngle: (startAngle / 180) * Math.PI,
endAngle: (endAngle / 180) * Math.PI,
direction: direction || false
}
ctx.beginPath()
ctx.fillStyle = fillColor
ctx.moveTo(basic.x, basic.y)
ctx.arc(basic.x, basic.y, basic.r, basic.startAngle, basic.endAngle, direction)
ctx.closePath()
ctx.fill()
}
}

正文完
 0