
組件 cavas
<template>
<div class="count-wrap" :style="{width:width+'px',height:height+'px', position: 'relative'}">
<canvas :id="canvaId" :width="width" :height="height"></canvas>
</div>
</template>
<script>
export default {
name: "cavas",
props: {
width: {
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 {
width: 100%;
height: 100%;
position: absolute;
top: 0;
}
}
</style>
調用組件

