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 Millisecond = 1
const Second = 1000 * Millisecond 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) { function qpush(arr, val, len) {
arr.push(val) arr.push(val)
@ -109,45 +109,60 @@ class PieChart {
constructor(element, stat) { constructor(element, stat) {
this.stat = stat this.stat = stat
this.canvas = element.appendChild(document.createElement("canvas")) this.canvas = element.appendChild(document.createElement("canvas"))
this.data ={ this.ctx = this.canvas.getContext("2d")
labels: ["user", "nice", "sys", "idle", "wait"], this.r = 250
datasets: [] this.θ = 0
} this.canvas.width = this.r*2
this.chart = new Chart( this.canvas.height = this.r*2
this.canvas, }
{
type: "pie", arc(angle, color) {
data: this.data, this.ctx.fillStyle = color
options: { this.ctx.beginPath()
animation: false, this.ctx.arc(this.r, this,r, this,r, this.θ, this.θ + angle)
borderWidth: 0, this.ctx.fill()
backgroundColor: [
"blue",
"red",
"orange",
"rgba(255, 255, 0, 0.2)",
"cyan",
],
plugins: {
legend: { display: false },
},
},
}
)
} }
async update() { async update() {
let cpu = this.stat.cpu() let cpu = this.stat.cpu()
this.data.datasets = [{ this.ctx.clearRect(0, 0, this.canvas.width, this.canvas.height)
label: "Current",
data: [cpu.user, cpu.nice, cpu.sys, cpu.idle, cpu.wait], let colors = ["SkyBlue", "SeaGreen", "Gold", "Tomato"]
}] let values = [cpu.user, cpu.nice, cpu.sys, cpu.wait]
this.chart.update() 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 { export {
Stat, Stat,
AreaChart,
PieChart, PieChart,
} }