Giter Club home page Giter Club logo

chart.js-node-ssr-example's Introduction

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.

This example uses no native modules, so it can be easily installed on various platforms.

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           # run webpacked
$ npm run start:v12   # run non-webpacked ES Modules (Node.js >= 12.0.0)
$ npm run start:v14   # run non-webpacked ES Modules (Node.js >= 13.0.0)

Example

import { SvgCanvas,
         Rect2D,
         SvgCanvas2DGradient } from 'red-agate-svg-canvas/modules';

// NOTE: hack bad .d.ts definition for ESM.
// import * as ChartJs from 'chart.js'; // <- This is fine if you only use webpack.
import * as ChartJs_ from 'chart.js';
const ChartJs: typeof ChartJs_ = (ChartJs_ as any).default || ChartJs_;


// Get the global scope.
// If running on a node, "g" points to a "global" object.
// When running on the browser, "g" points to the "window" object.
const g = Function('return this')();

// Chart options
// https://www.chartjs.org/docs/latest/getting-started/usage.html
const opts: any = { ... };


function main() {
    // SvgCanvas has a "CanvasRenderingContext2D"-compatible interface.
    const ctx = new SvgCanvas();

    // SvgCanvas lacks the canvas property.
    (ctx as any).canvas = {
        width: 800,
        height: 400,
        style: {
            width: '800px',
            height: '400px',
        },
    };

    // SvgCanvas does not have font glyph information,
    // so manually set the ratio of (font height / font width).
    ctx.fontHeightRatio = 2;

    // Chart.js needs a "HTMLCanvasElement"-like interface that has "getContext()" method.
    // "getContext()" should returns a "CanvasRenderingContext2D"-compatible interface.
    const el = { getContext: () => ctx };

    // If "devicePixelRatio" is not set, Chart.js get the devicePixelRatio from "window" object.
    // node.js environment has no window object.
    opts.options.devicePixelRatio = 1;

    // Disable animations.
    opts.options.animation = false;
    opts.options.events = [];
    opts.options.responsive = false;

    // Chart.js needs the "CanvasGradient" in the global scope.
    const savedGradient = g.CanvasGradient;
    g.CanvasGradient = SvgCanvas2DGradient;
    try {
        const chart = new ChartJs.Chart(el as any, opts);
    } finally {
        if (savedGradient) {
            g.CanvasGradient = savedGradient;
        }
    }

    // Render as SVG.
    const svgString = ctx.render(new Rect2D(0, 0 , 800, 400), 'px');
    console.log(svgString);
}

Rendering results

1

2

3

4

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.)

red-agate-svg-canvas/modules directory has a package.json file and determines that the source files are ES Modules.
See Node.js Documentation - ECMAScript Modules.

chart.js-node-ssr-example's People

Contributors

shellyln avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

chart.js-node-ssr-example's Issues

support for chart js event

Hi, is there any ways to add the chart JS interaction like the tool tip and clicking event back ?

Thanks,

Adrian

Build fails

After running npm run build with node.js v6.14.4:

$ npm run build

> [email protected] build /home/temuri/chart.js-node-ssr-example
> webpack-cli --mode=production --config webpack.config.js

Hash: 1bf3c5e4c635fb50a928
Version: webpack 4.39.1
Child
    Hash: 1bf3c5e4c635fb50a928
    Time: 128ms
    Built at: 08/04/2019 4:28:38 PM
     2 assets
    Entrypoint index = index.js index.js.map
    [0] multi ./src/index.ts 28 bytes {0} [built]
    [1] ./src/index.ts 2.95 KiB {0} [not cacheable] [built] [failed] [1 error]

    ERROR in ./src/index.ts
    Module build failed (from ./node_modules/ts-loader/index.js):
    /home/temuri/chart.js-node-ssr-example/node_modules/ts-loader/node_modules/micromatch/index.js:44
        let isMatch = picomatch(String(patterns[i]), { ...options, onResult }, true);
                                                       ^^^

    SyntaxError: Unexpected token ...
        at NativeCompileCache._moduleCompile (/home/temuri/chart.js-node-ssr-example/node_modules/v8-compile-cache/v8-compile-cache.js:240:18)

Does not work with chart.js version 3

After upgrading chart.js to 3.5.0 (latest version as of today), the build runs fine but this is what I get after running start:

> [email protected] start
> npm run start:wp


> [email protected] start:wp ~/chart.js-node-ssr-example
> node bin/index.js

~/chart.js-node-ssr-example/bin/index.js:2

# removed lots of meaningless output

Error: "linear" is not a registered scale.
    at Object._get (~/chart.js-node-ssr-example/bin/index.js:2:140751)
    at Object.getScale (~/chart.js-node-ssr-example/bin/index.js:2:139996)
    at ~/chart.js-node-ssr-example/bin/index.js:2:149372
    at R (~/chart.js-node-ssr-example/bin/index.js:2:41146)
    at ys.buildOrUpdateScales (~/chart.js-node-ssr-example/bin/index.js:2:149168)
    at ys.update (~/chart.js-node-ssr-example/bin/index.js:2:151091)
    at new ys (~/chart.js-node-ssr-example/bin/index.js:2:147717)
    at ~/chart.js-node-ssr-example/bin/index.js:2:225927
    at Object.717 (~/chart.js-node-ssr-example/bin/index.js:2:226036)
    at i (~/chart.js-node-ssr-example/bin/index.js:2:226123)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start:wp: `node bin/index.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] start:wp script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     ~/.npm/_logs/2021-08-14T15_18_58_083Z-debug.log

Could you please take a look at this?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.