crux.land

Api
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { createCanvas } from "https://deno.land/x/canvas/mod.ts";
import * as chartjs from 'https://cdn.skypack.dev/chart.js';
function once(f) {
let executed = false;
return () => {
if (executed) return;
executed = true;
f();
};
}
// Init ChartJS globals
const globalInit = once(() => chartjs.Chart.register(...chartjs.registerables));
class DenoPlatform extends chartjs.BasePlatform {
acquireContext(canvas, _) {
return canvas.getContext("2d");
}
}
export function render(width, height, chartjsConfig, imageType="image/png") {
// Init globals once
globalInit();
// Create canvas
const canvas = createCanvas(width, height);
// Patch options
chartjsConfig.options = chartjsConfig.options || {};
chartjsConfig.options.responsive = false;
chartjsConfig.options.animation = false;
// Temporarily patch console.error, since we'll fail with
// console.error("Failed to create chart: can't acquire context from the given item");
// due to ctx not having a .canvas attribute
const oldConsoleError = globalThis.console.error;
globalThis.console.error = () => {};
// Init chart, expect to fail
const chart = new chartjs.Chart(
canvas,
{
...chartjsConfig,
platform: DenoPlatform,
},
);
// Restore console.error
globalThis.console.error = oldConsoleError;
// Finish init: set canvas, width & height
chart.canvas = canvas;
chart.width = width;
chart.height = height;
// Do render
chart._initialize();
chart.update();
return canvas.toBuffer(imageType);
}
© 2020-2021 Denosaurs
GitHubDiscordTwitter