近来做的两个项目都是关于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()
}
}