效果:
源码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>CPU占用率</title>
<style type="text/css">
.myChart{
border:1px solid #ccc;
}
</style>
</head>
<body>
<canvas class="myChart" id="myChart"></canvas>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
var canvas_cpu = document.getElementById("myChart");
var context = canvas_cpu.getContext("2d");
if (!canvas_cpu.getContext) { // 浏览器不支持canvas
return;
}
// 创建文字:canvas 2D对象,内容文字,画布X轴,Y轴,样式
function DrawCPUText(ctx, title, x, y, style) {
ctx.save();
ctx.beginPath();
ctx.font = style.font + " Arial";
ctx.fillStyle = style.color;
ctx.textBaseline = 'middle';
var tw = ctx.measureText(title).width;
ctx.fillText(title, x - tw / 2, y);
ctx.closePath();
ctx.restore();
}
// canvas画布宽,高,样式
function CpuPie(width, height, setValueObj){
var total = 100; // 总容量
var startAngle = (Math.PI*-1/2); // 圆开始角度
var endAngle = 30; // 圆结束角度(已用容量)
var currValue = 30; // 已用容量
// 设置画布宽高
canvas_cpu.setAttribute('width', width);
canvas_cpu.setAttribute('height', height);
var circleX = width / 2,
circleY = height / 2 - setValueObj['labelWidth'];
var radius = 0;
if( circleX <= circleY)
{
radius = width / 2 - setValueObj['labelWidth']*3;
}
else
{
radius = height / 2 - setValueObj['labelWidth']*3;
}
// 圆心文字:占用率
var text = currValue + "%";
DrawCPUText(
context,
text,
circleX,
circleY,
{
font:setValueObj["fontSize"],
color: setValueObj["fontColor"],
}
);
// 圆环底部文字
var title_text = "CPU占用率"
DrawCPUText(
context,
title_text,
circleX,
height/2 + radius+10,
{
font:"15px",
color: setValueObj["fontColor"],
}
);
// 绘制背景圆
context.save();
context.beginPath();
context.strokeStyle = "#e7e7e7";
context.lineWidth = setValueObj['labelWidth'];
context.arc(circleX, circleY, radius, 0, Math.PI * 2, false);
context.closePath();
context.stroke();
context.restore();
// 绘制占用率部分
context.save();
context.beginPath();
context.strokeStyle = setValueObj["color"];
context.lineWidth = setValueObj['labelWidth'];
context.arc(circleX, circleY, radius, startAngle, (Math.PI*-1/2) + endAngle/100 * (Math.PI*2), false);
context.stroke();
context.restore();
}
$(function(){
var initStyle = {
labelWidth: 8,
fontColor: "#555",
fontSize: "20px",
color: "#3390d7"
};
var Width = $(window).width()/3;
var Height = $(window).height()/3;
CpuPie(Width, Height, initStyle);
// 画布响应屏幕大小
window.onresize = function(){
Width = $(window).width()/3;
Height = $(window).height()/3;
CpuPie(Width, Height, initStyle);
};
});
</script>
</body>
</html>