Native pie chart

This commit is contained in:
Neale Pickett 2023-03-11 11:27:16 -07:00
parent f9c74c2aac
commit 2faa8f9d8c
4 changed files with 48 additions and 33 deletions

View File

@ -1,4 +1,4 @@
import * as WebStat from "./webstat.mjs"
import * as WebStat from "./stat/webstat.mjs"
const Millisecond = 1
const Second = 1000 * Millisecond

View File

@ -1,4 +1,4 @@
import Chart from "https://cdn.jsdelivr.net/npm/chart.js@4.2.1/auto/+esm"
const τ = Math.PI * 2
function qpush(arr, val, len) {
arr.push(val)
@ -109,45 +109,60 @@ class PieChart {
constructor(element, stat) {
this.stat = stat
this.canvas = element.appendChild(document.createElement("canvas"))
this.data ={
labels: ["user", "nice", "sys", "idle", "wait"],
datasets: []
}
this.chart = new Chart(
this.canvas,
{
type: "pie",
data: this.data,
options: {
animation: false,
borderWidth: 0,
backgroundColor: [
"blue",
"red",
"orange",
"rgba(255, 255, 0, 0.2)",
"cyan",
],
plugins: {
legend: { display: false },
},
},
}
)
this.ctx = this.canvas.getContext("2d")
this.r = 250
this.θ = 0
this.canvas.width = this.r*2
this.canvas.height = this.r*2
}
arc(angle, color) {
this.ctx.fillStyle = color
this.ctx.beginPath()
this.ctx.arc(this.r, this,r, this,r, this.θ, this.θ + angle)
this.ctx.fill()
}
async update() {
let cpu = this.stat.cpu()
this.data.datasets = [{
label: "Current",
data: [cpu.user, cpu.nice, cpu.sys, cpu.idle, cpu.wait],
}]
this.chart.update()
this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
let colors = ["SkyBlue", "SeaGreen", "Gold", "Tomato"]
let values = [cpu.user, cpu.nice, cpu.sys, cpu.wait]
let labels = ["u", "n", "s", "w"]
let θ = -τ/4
this.ctx.save()
this.ctx.translate(this.r, this.r)
this.ctx.font = `bold ${this.r/3}px sans-serif`
for (let i = 0; i < colors.length; i++) {
let angle = values[i] * τ
this.ctx.fillStyle = colors[i]
this.ctx.beginPath()
this.ctx.arc(0, 0, this.r, θ, θ + angle, false)
this.ctx.lineTo(0, 0)
this.ctx.fill()
if (angle > τ/12) {
let mid = θ + angle/2
this.ctx.save()
this.ctx.rotate(mid)
this.ctx.translate(this.r*0.7, 0)
this.ctx.rotate(-mid)
this.ctx.fillStyle = "black"
this.ctx.textBaseline = "middle"
this.ctx.textAlign = "center"
this.ctx.fillText(labels[i], 0, 0)
this.ctx.restore()
}
θ += angle
}
this.ctx.restore()
}
}
export {
Stat,
AreaChart,
PieChart,
}