Chart.js server side rendering example on the node.js environment.
Render various charts using Chart.js into the SVG format.
Chart.js uses the HTML5 Canvas API.
However, the node.js environment does not have the Canvas API by default.
With red-agate-svg-canvas,
you can render the charts on the server side.
Get started
$ git clone https://github.com/shellyln/chart.js-node-ssr-example.git
$ cd chart.js-node-ssr-example
$ rm -rf ./.git
$ npm install
$ npm run build
$ npm start
Example
import { SvgCanvas,
Rect2D,
SvgCanvas2DGradient } from 'red-agate-svg-canvas/modules';
import * as ChartJs from 'chart.js';
const g = Function('return this')();
const opts: any = { ... };
function main() {
const ctx = new SvgCanvas();
(ctx as any).canvas = {
width: 800,
height: 400,
style: {
width: '800px',
height: '400px',
},
};
ctx.fontHeightRatio = 2;
const el = { getContext: () => ctx };
opts.options.devicePixelRatio = 1;
opts.options.animation = false;
opts.options.events = [];
opts.options.responsive = false;
const savedGradient = g.CanvasGradient;
g.CanvasGradient = SvgCanvas2DGradient;
try {
const chart = new ChartJs.Chart(el as any, opts);
} finally {
if (savedGradient) {
g.CanvasGradient = savedGradient;
}
}
const svgString = ctx.render(new Rect2D(0, 0 , 800, 400), 'px');
console.log(svgString);
}
Rendering results
Notes
To import the red-agate-svg-canvas, you need to use babel
+ webpack
.
(We have used the import
statements for doing the tree-shaking. The import
statements in the .js
not the .mjs
files cannot import from the vanilla node.js.)