最近作的两个项目都是关于canvas的,作完整理一下,方便下一次使用,在vue里写的小demo,
功能:画扇形 动态画圆弧(requestAnimationFrame结合settimeout作的动画)、画表盘
一、建立一个ctx对象vue
二、begain()方法开始画笔 三、fillStyple设置填充颜色 [strokeStyle] 四、arc(x,y,r,startAngle,endAngle,direction) true是顺时针 false是逆时针 默认是逆时针 五、closePath()结束画笔 开始填充fill() [没有closePah直接stroke()]
mounted () { this.$nextTick(() => { /* 一、建立一个ctx对象 二、begain()方法开始画笔 三、fillStyple设置填充颜色 [strokeStyle] 四、arc(x,y,r,startAngle,endAngle,direction) true是顺时针 false是逆时针 默认是逆时针 五、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() } }