Skip to content

Conversation

SeanSobey
Copy link
Contributor

@SeanSobey SeanSobey commented Mar 8, 2018

A pretty small change, which allows ChartJS to run on Node using a virtual canvas like node-canvas.

All that is required is that browser specific APIs are not referenced, like window or document. I only found 1 that was missing an undefined guard.

ChartJS can be used on node like so:

const ChartJs = require('chart.js');
const { createCanvas } = require('canvas');

function renderPNG(configuration) {
	
	const canvas = createCanvas(800, 600);	
	// Disable animation (otherwise charts will throw exceptions)
	configuration.options = configuration.options || {};
	configuration.options.responsive = false;
	configuration.options.animation = false;
	canvas.style = {};
	const context = canvas.getContext('2d');
	const chart = new ChartJs(context, configuration);
	return new Promise((resolve, reject) => {
                // or `pngStream` `toDataURL`, etc
		chart.canvas.toBuffer((error, buffer) => {
			if (error) {
				return reject(error);
			}
			return resolve(buffer);
		});
	});
}

@etimberg etimberg requested a review from simonbrunel March 9, 2018 14:47
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants