组件 cavas
<template> <div class="count-wrap" :style="{width+'px',height:height+'px', position: 'relative'}"> <canvas :id="canvaId" :width="width" :height="height"></canvas> </div> </template> <script> export default { name: "cavas", props: { { type: Number, default: 300 }, height: { type: Number, default: 300 }, canvaId: { type: String, default: "canvasId" }, config: { type: Object, default: {} } }, data() { return {}; }, mounted() { var timeCanvas = document.getElementById(this.canvaId); this.drawMain(timeCanvas, this.config); }, methods: { drawMain(drawingElem, config = {}) { config = Object.assign( {}, { bgcolor: "#eee", lineWidth: 20, data: [], colorList: [],lineCap:'butt' }, config ); var context = drawingElem.getContext("2d"); var centerX = drawingElem.width / 2; var centerY = drawingElem.height / 2; var rad = (Math.PI * 2) / 100;//总的角度分配到100里面 function backgroundCircle() { context.save(); context.beginPath(); context.lineWidth = config.lineWidth; var radius = centerX - context.lineWidth;//设置半径 context.lineCap = "round";//设置或返回线条末端线帽的样式。 context.strokeStyle = config.bgcolor;//设置线颜色 // x 圆的中心的 x 坐标。 y 圆的中心的 y 坐标。 r 圆的半径。 sAngle 起始角,以弧度计。(弧的圆形的三点钟位置是 0 度)。 eAngle 结束角,以弧度计。 counterclockwise 可选。规定应该逆时针还是顺时针绘图。False = 顺时针,true = 逆时针。 // context.arc(centerX, centerY, radius, 0, Math.PI * 2, false);//画圆线 context.stroke();//绘制已定义的路径 context.closePath(); context.restore();//返回之前保存过的路径状态和属性 } function foregroundCircle(start, end, color) { context.save(); context.strokeStyle = color; if (color === "#eee") { context.lineWidth = 0; } else { context.lineWidth = config.lineWidth; } context.lineCap = config.lineCap; var radius = centerX - context.lineWidth; context.beginPath(); context.arc(centerX, centerY, radius, start, end, false); context.stroke(); context.closePath(); context.restore(); } backgroundCircle(); //画每段圆环 let radArr = []; config.data.forEach((item, index) => { radArr[index] = -Math.PI / 2 + (item + (index == 0 ? 0 : config.data[index - 1])) * rad; foregroundCircle( index == 0 ? -Math.PI / 2 : radArr[index - 1], radArr[index], config.colorList[index] ); }); } } }; </script> <style lang="less" scoped> .count-wrap { #time-graph-canvas { 100%; height: 100%; position: absolute; top: 0; } } </style>
调用组件