chart.js poor animations and scaled on Retina fix

chart.js animations issues

Posted on October 21, 2013

I recently had a few problems with Chart.js increasing the size of the canvas on Retina screens by 4 and issues with poor, juddering animations.  Anyway, after looking through the code here are the fixes:

Removing scaling for retina

Comment out this code:

//High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
if (window.devicePixelRatio) {
	context.canvas.style.width = width + "px";
	context.canvas.style.height = height + "px";
	context.canvas.height = height * window.devicePixelRatio;
	context.canvas.width = width * window.devicePixelRatio;
	context.scale(window.devicePixelRatio, window.devicePixelRatio);
}

Improving animations

It’s just case of adding a conditional to the default options so the animationSteps are reduced by half for devices with a double pixel density. Here’s the conditional for Pie Charts:

if (window.devicePixelRatio) {

	this.Pie = function(data,options){
		chart.Pie.defaults = {
			segmentShowStroke : true,
			segmentStrokeColor : "#fff",
			segmentStrokeWidth : 2,
			animation : true,
			animationSteps : 100,
			animationEasing : "easeOutBounce",
			animateRotate : true,
			animateScale : false,
			onAnimationComplete : null
		};		

		var config = (options)? mergeChartConfig(chart.Pie.defaults,options) : chart.Pie.defaults;

		return new Pie(data,config,context);				
	};

}else{

	this.Pie = function(data,options){
		chart.Pie.defaults = {
			segmentShowStroke : true,
			segmentStrokeColor : "#fff",
			segmentStrokeWidth : 2,
			animation : true,
			animationSteps : 40,
			animationEasing : "easeOutBounce",
			animateRotate : true,
			animateScale : false,
			onAnimationComplete : null
		};		

		var config = (options)? mergeChartConfig(chart.Pie.defaults,options) : chart.Pie.defaults;

		return new Pie(data,config,context);				
	};

}