最近作的兩個項目都是關於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() } }