仿echart的简单仪表盘

const drawCanvas = () => {
	const ctx = $canvas.getContext('2d');
	const {width, height} = ctx.canvas;
	const radius = Math.min(width, height) / 2;
	const deg = Math.PI / 180;
	const radian = 270 * deg;
	const lineWidth = 20;
	const lineColors = [[0.3, '#67E0E3'], [0.7, '#37a2da'], [1, '#fd666d']];
	const tickColor = '#fff';



	const drawIndicator = (val = 0) => {
		val = val * 270 / 100;
		ctx.save();
		ctx.rotate((90 + val) * deg);
		ctx.beginPath();
		ctx.moveTo(0, 0 - radius + lineWidth / 2);
		ctx.lineTo(5, 0);
		ctx.lineTo(0, 10);
		ctx.lineTo(-5, 0);
		ctx.closePath();
		ctx.fillStyle = '#808080';
		ctx.fill();
		ctx.restore();
	}

	const drawFrame = () => {
		ctx.setTransform(1, 0, 0, 1, 0, 0);
		ctx.clearRect(0, 0, width, height);
		ctx.translate(width / 2, height / 2);
		ctx.rotate(radian / 2);

		ctx.save();
		ctx.lineWidth = lineWidth;
		lineColors.forEach((it, i, arr) => {
			ctx.beginPath();
			ctx.arc(0, 0, radius - lineWidth / 2, i === 0 ? 0 :  arr[i - 1][0] * radian, it[0] * radian, false);
			ctx.strokeStyle = it[1];
			ctx.stroke();
		});
		ctx.restore();

		ctx.save(); // 刻度线
		for (let i = 1; i < 50; i++) {
			ctx.rotate(radian / 50);
			ctx.beginPath();
			ctx.moveTo(radius, 0);
			if (i % 5 === 0) {
				ctx.lineTo(radius - lineWidth, 0);
				ctx.lineWidth = 3;
			} else {
				ctx.lineTo(radius - lineWidth / 3, 0);
				ctx.lineWidth = 2;
			}
			ctx.strokeStyle = tickColor;
			ctx.stroke();
		}
		ctx.restore();

		ctx.save(); // 文字
		ctx.rotate(90 * deg);
		ctx.font = '16px auto';
		ctx.textAlign = 'center';
		ctx.textBaseline = 'top';
		ctx.fillStyle = '#808080';
		const y = 0 - radius + lineWidth + parseInt(ctx.font) / 2;
		for (let i = 0; i <= 10; i++) {
			ctx.fillText((i * 10).toFixed(0), 0, y);
			ctx.rotate(radian / 10);
		}
		ctx.restore();
	}


	const draw = () => {
		const {total, free} = process.getSystemMemoryInfo();
		const percent = Math.random() * 100;//free / total * 100;
		drawFrame();
		drawIndicator(percent);
	}
	draw();
	setInterval(draw, 1000);
};
posted @ 2023-03-24 09:26  风的线条昵称已被使用  阅读(34)  评论(0编辑  收藏  举报