4 * Version: {{ version }}
6 * Copyright 2015 Nick Downie
7 * Released under the MIT license
8 * https://github.com/nnnick/Chart.js/blob/master/LICENSE.md
16 //Declare root variable - window in the browser, global on the server
18 previous = root.Chart;
20 //Occupy the global variable of Chart, and create a simple base class
21 var Chart = function(context){
23 this.canvas = context.canvas;
27 //Variables global to the chart
28 var computeDimension = function(element,dimension)
30 if (element['offset'+dimension])
32 return element['offset'+dimension];
36 return document.defaultView.getComputedStyle(element).getPropertyValue(dimension);
40 var width = this.width = computeDimension(context.canvas,'Width') || context.canvas.width;
41 var height = this.height = computeDimension(context.canvas,'Height') || context.canvas.height;
43 // Firefox requires this to work correctly
44 context.canvas.width = width;
45 context.canvas.height = height;
47 width = this.width = context.canvas.width;
48 height = this.height = context.canvas.height;
49 this.aspectRatio = this.width / this.height;
50 //High pixel density displays - multiply the size of the canvas height/width by the device pixel ratio, then scale.
51 helpers.retinaScale(this);
55 //Globally expose the defaults to allow for user updating/changing
58 // Boolean - Whether to animate the chart
61 // Number - Number of animation steps
64 // String - Animation easing effect
65 animationEasing: "easeOutQuart",
67 // Boolean - If we should show the scale at all
70 // Boolean - If we want to override with a hard coded scale
73 // ** Required if scaleOverride is true **
74 // Number - The number of steps in a hard coded scale
76 // Number - The value jump in the hard coded scale
78 // Number - The scale starting value
79 scaleStartValue: null,
81 // String - Colour of the scale line
82 scaleLineColor: "rgba(0,0,0,.1)",
84 // Number - Pixel width of the scale line
87 // Boolean - Whether to show labels on the scale
88 scaleShowLabels: true,
90 // Interpolated JS string - can access value
91 scaleLabel: "<%=value%>",
93 // Boolean - Whether the scale should stick to integers, and not show any floats even if drawing space is there
94 scaleIntegersOnly: true,
96 // Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
97 scaleBeginAtZero: false,
99 // String - Scale label font declaration for the scale label
100 scaleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
102 // Number - Scale label font size in pixels
105 // String - Scale label font weight style
106 scaleFontStyle: "normal",
108 // String - Scale label font colour
109 scaleFontColor: "#666",
111 // Boolean - whether or not the chart should be responsive and resize when the browser does.
114 // Boolean - whether to maintain the starting aspect ratio or not when responsive, if set to false, will take up entire container
115 maintainAspectRatio: true,
117 // Boolean - Determines whether to draw tooltips on the canvas or not - attaches events to touchmove & mousemove
120 // Boolean - Determines whether to draw built-in tooltip or call custom tooltip function
121 customTooltips: false,
123 // Array - Array of string names to attach tooltip events
124 tooltipEvents: ["mousemove", "touchstart", "touchmove", "mouseout"],
126 // String - Tooltip background colour
127 tooltipFillColor: "rgba(0,0,0,0.8)",
129 // String - Tooltip label font declaration for the scale label
130 tooltipFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
132 // Number - Tooltip label font size in pixels
135 // String - Tooltip font weight style
136 tooltipFontStyle: "normal",
138 // String - Tooltip label font colour
139 tooltipFontColor: "#fff",
141 // String - Tooltip title font declaration for the scale label
142 tooltipTitleFontFamily: "'Helvetica Neue', 'Helvetica', 'Arial', sans-serif",
144 // Number - Tooltip title font size in pixels
145 tooltipTitleFontSize: 14,
147 // String - Tooltip title font weight style
148 tooltipTitleFontStyle: "bold",
150 // String - Tooltip title font colour
151 tooltipTitleFontColor: "#fff",
153 // Number - pixel width of padding around tooltip text
156 // Number - pixel width of padding around tooltip text
159 // Number - Size of the caret on the tooltip
162 // Number - Pixel radius of the tooltip border
163 tooltipCornerRadius: 6,
165 // Number - Pixel offset from point x to tooltip edge
168 // String - Template string for single tooltips
169 tooltipTemplate: "<%if (label){%><%=label%>: <%}%><%= value %>",
171 // String - Template string for single tooltips
172 multiTooltipTemplate: "<%= value %>",
174 // String - Colour behind the legend colour block
175 multiTooltipKeyBackground: '#fff',
177 // Function - Will fire on animation progression.
178 onAnimationProgress: function(){},
180 // Function - Will fire on animation completion.
181 onAnimationComplete: function(){}
186 //Create a dictionary of chart types, to allow for extension of existing types
189 //Global Chart helpers object for utility methods and classes
190 var helpers = Chart.helpers = {};
192 //-- Basic js utility methods
193 var each = helpers.each = function(loopable,callback,self){
194 var additionalArgs = Array.prototype.slice.call(arguments, 3);
195 // Check to see if null or undefined firstly.
197 if (loopable.length === +loopable.length){
199 for (i=0; i<loopable.length; i++){
200 callback.apply(self,[loopable[i], i].concat(additionalArgs));
204 for (var item in loopable){
205 callback.apply(self,[loopable[item],item].concat(additionalArgs));
210 clone = helpers.clone = function(obj){
212 each(obj,function(value,key){
213 if (obj.hasOwnProperty(key)){
214 objClone[key] = value;
219 extend = helpers.extend = function(base){
220 each(Array.prototype.slice.call(arguments,1), function(extensionObject) {
221 each(extensionObject,function(value,key){
222 if (extensionObject.hasOwnProperty(key)){
229 merge = helpers.merge = function(base,master){
230 //Merge properties in left object over to a shallow clone of object right.
231 var args = Array.prototype.slice.call(arguments,0);
233 return extend.apply(null, args);
235 indexOf = helpers.indexOf = function(arrayToSearch, item){
236 if (Array.prototype.indexOf) {
237 return arrayToSearch.indexOf(item);
240 for (var i = 0; i < arrayToSearch.length; i++) {
241 if (arrayToSearch[i] === item) return i;
246 where = helpers.where = function(collection, filterCallback){
249 helpers.each(collection, function(item){
250 if (filterCallback(item)){
257 findNextWhere = helpers.findNextWhere = function(arrayToSearch, filterCallback, startIndex){
258 // Default to start of the array
262 for (var i = startIndex + 1; i < arrayToSearch.length; i++) {
263 var currentItem = arrayToSearch[i];
264 if (filterCallback(currentItem)){
269 findPreviousWhere = helpers.findPreviousWhere = function(arrayToSearch, filterCallback, startIndex){
270 // Default to end of the array
272 startIndex = arrayToSearch.length;
274 for (var i = startIndex - 1; i >= 0; i--) {
275 var currentItem = arrayToSearch[i];
276 if (filterCallback(currentItem)){
281 inherits = helpers.inherits = function(extensions){
282 //Basic javascript inheritance based on the model created in Backbone.js
284 var ChartElement = (extensions && extensions.hasOwnProperty("constructor")) ? extensions.constructor : function(){ return parent.apply(this, arguments); };
286 var Surrogate = function(){ this.constructor = ChartElement;};
287 Surrogate.prototype = parent.prototype;
288 ChartElement.prototype = new Surrogate();
290 ChartElement.extend = inherits;
292 if (extensions) extend(ChartElement.prototype, extensions);
294 ChartElement.__super__ = parent.prototype;
298 noop = helpers.noop = function(){},
299 uid = helpers.uid = (function(){
302 return "chart-" + id++;
305 warn = helpers.warn = function(str){
306 //Method for warning of errors
307 if (window.console && typeof window.console.warn === "function") console.warn(str);
309 amd = helpers.amd = (typeof define === 'function' && define.amd),
311 isNumber = helpers.isNumber = function(n){
312 return !isNaN(parseFloat(n)) && isFinite(n);
314 max = helpers.max = function(array){
315 return Math.max.apply( Math, array );
317 min = helpers.min = function(array){
318 return Math.min.apply( Math, array );
320 cap = helpers.cap = function(valueToCap,maxValue,minValue){
321 if(isNumber(maxValue)) {
322 if( valueToCap > maxValue ) {
326 else if(isNumber(minValue)){
327 if ( valueToCap < minValue ){
333 getDecimalPlaces = helpers.getDecimalPlaces = function(num){
334 if (num%1!==0 && isNumber(num)){
335 var s = num.toString();
336 if(s.indexOf("e-") < 0){
337 // no exponent, e.g. 0.01
338 return s.split(".")[1].length;
340 else if(s.indexOf(".") < 0) {
341 // no decimal point, e.g. 1e-9
342 return parseInt(s.split("e-")[1]);
345 // exponent and decimal point, e.g. 1.23e-9
346 var parts = s.split(".")[1].split("e-");
347 return parts[0].length + parseInt(parts[1]);
354 toRadians = helpers.radians = function(degrees){
355 return degrees * (Math.PI/180);
357 // Gets the angle from vertical upright to the point about a centre.
358 getAngleFromPoint = helpers.getAngleFromPoint = function(centrePoint, anglePoint){
359 var distanceFromXCenter = anglePoint.x - centrePoint.x,
360 distanceFromYCenter = anglePoint.y - centrePoint.y,
361 radialDistanceFromCenter = Math.sqrt( distanceFromXCenter * distanceFromXCenter + distanceFromYCenter * distanceFromYCenter);
364 var angle = Math.PI * 2 + Math.atan2(distanceFromYCenter, distanceFromXCenter);
366 //If the segment is in the top left quadrant, we need to add another rotation to the angle
367 if (distanceFromXCenter < 0 && distanceFromYCenter < 0){
373 distance: radialDistanceFromCenter
376 aliasPixel = helpers.aliasPixel = function(pixelWidth){
377 return (pixelWidth % 2 === 0) ? 0 : 0.5;
379 splineCurve = helpers.splineCurve = function(FirstPoint,MiddlePoint,AfterPoint,t){
380 //Props to Rob Spencer at scaled innovation for his post on splining between points
381 //http://scaledinnovation.com/analytics/splines/aboutSplines.html
382 var d01=Math.sqrt(Math.pow(MiddlePoint.x-FirstPoint.x,2)+Math.pow(MiddlePoint.y-FirstPoint.y,2)),
383 d12=Math.sqrt(Math.pow(AfterPoint.x-MiddlePoint.x,2)+Math.pow(AfterPoint.y-MiddlePoint.y,2)),
384 fa=t*d01/(d01+d12),// scaling factor for triangle Ta
388 x : MiddlePoint.x-fa*(AfterPoint.x-FirstPoint.x),
389 y : MiddlePoint.y-fa*(AfterPoint.y-FirstPoint.y)
392 x: MiddlePoint.x+fb*(AfterPoint.x-FirstPoint.x),
393 y : MiddlePoint.y+fb*(AfterPoint.y-FirstPoint.y)
397 calculateOrderOfMagnitude = helpers.calculateOrderOfMagnitude = function(val){
398 return Math.floor(Math.log(val) / Math.LN10);
400 calculateScaleRange = helpers.calculateScaleRange = function(valuesArray, drawingSize, textSize, startFromZero, integersOnly){
402 //Set a minimum step of two - a point at the top of the graph, and a point at the base
404 maxSteps = Math.floor(drawingSize/(textSize * 1.5)),
405 skipFitting = (minSteps >= maxSteps);
407 var maxValue = max(valuesArray),
408 minValue = min(valuesArray);
410 // We need some degree of separation here to calculate the scales if all the values are the same
411 // Adding/minusing 0.5 will give us a range of 1.
412 if (maxValue === minValue){
414 // So we don't end up with a graph with a negative start value if we've said always start from zero
415 if (minValue >= 0.5 && !startFromZero){
419 // Make up a whole number above the values
424 var valueRange = Math.abs(maxValue - minValue),
425 rangeOrderOfMagnitude = calculateOrderOfMagnitude(valueRange),
426 graphMax = Math.ceil(maxValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
427 graphMin = (startFromZero) ? 0 : Math.floor(minValue / (1 * Math.pow(10, rangeOrderOfMagnitude))) * Math.pow(10, rangeOrderOfMagnitude),
428 graphRange = graphMax - graphMin,
429 stepValue = Math.pow(10, rangeOrderOfMagnitude),
430 numberOfSteps = Math.round(graphRange / stepValue);
432 //If we have more space on the graph we'll use it to give more definition to the data
433 while((numberOfSteps > maxSteps || (numberOfSteps * 2) < maxSteps) && !skipFitting) {
434 if(numberOfSteps > maxSteps){
436 numberOfSteps = Math.round(graphRange/stepValue);
437 // Don't ever deal with a decimal number of steps - cancel fitting and just use the minimum number of steps.
438 if (numberOfSteps % 1 !== 0){
442 //We can fit in double the amount of scale points on the scale
444 //If user has declared ints only, and the step value isn't a decimal
445 if (integersOnly && rangeOrderOfMagnitude >= 0){
446 //If the user has said integers only, we need to check that making the scale more granular wouldn't make it a float
447 if(stepValue/2 % 1 === 0){
449 numberOfSteps = Math.round(graphRange/stepValue);
451 //If it would make it a float break out of the loop
456 //If the scale doesn't have to be an int, make the scale more granular anyway.
459 numberOfSteps = Math.round(graphRange/stepValue);
466 numberOfSteps = minSteps;
467 stepValue = graphRange / numberOfSteps;
471 steps : numberOfSteps,
472 stepValue : stepValue,
474 max : graphMin + (numberOfSteps * stepValue)
478 /* jshint ignore:start */
479 // Blows up jshint errors based on the new Function constructor
481 //Javascript micro templating by John Resig - source at http://ejohn.org/blog/javascript-micro-templating/
482 template = helpers.template = function(templateString, valuesObject){
484 // If templateString is function rather than string-template - call the function for valuesObject
486 if(templateString instanceof Function){
487 return templateString(valuesObject);
491 function tmpl(str, data){
492 // Figure out if we're getting a template, or if we need to
493 // load the template - and be sure to cache the result.
494 var fn = !/\W/.test(str) ?
495 cache[str] = cache[str] :
497 // Generate a reusable function that will serve as a template
498 // generator (and which will be cached).
500 "var p=[],print=function(){p.push.apply(p,arguments);};" +
502 // Introduce the data as local variables using with(){}
503 "with(obj){p.push('" +
505 // Convert the template into pure JavaScript
507 .replace(/[\r\t\n]/g, " ")
508 .split("<%").join("\t")
509 .replace(/((^|%>)[^\t]*)'/g, "$1\r")
510 .replace(/\t=(.*?)%>/g, "',$1,'")
511 .split("\t").join("');")
512 .split("%>").join("p.push('")
513 .split("\r").join("\\'") +
514 "');}return p.join('');"
517 // Provide some basic currying to the user
518 return data ? fn( data ) : fn;
520 return tmpl(templateString,valuesObject);
522 /* jshint ignore:end */
523 generateLabels = helpers.generateLabels = function(templateString,numberOfSteps,graphMin,stepValue){
524 var labelsArray = new Array(numberOfSteps);
526 each(labelsArray,function(val,index){
527 labelsArray[index] = template(templateString,{value: (graphMin + (stepValue*(index+1)))});
532 //--Animation methods
533 //Easing functions adapted from Robert Penner's easing equations
534 //http://www.robertpenner.com/easing/
535 easingEffects = helpers.easingEffects = {
536 linear: function (t) {
539 easeInQuad: function (t) {
542 easeOutQuad: function (t) {
543 return -1 * t * (t - 2);
545 easeInOutQuad: function (t) {
546 if ((t /= 1 / 2) < 1){
547 return 1 / 2 * t * t;
549 return -1 / 2 * ((--t) * (t - 2) - 1);
551 easeInCubic: function (t) {
554 easeOutCubic: function (t) {
555 return 1 * ((t = t / 1 - 1) * t * t + 1);
557 easeInOutCubic: function (t) {
558 if ((t /= 1 / 2) < 1){
559 return 1 / 2 * t * t * t;
561 return 1 / 2 * ((t -= 2) * t * t + 2);
563 easeInQuart: function (t) {
564 return t * t * t * t;
566 easeOutQuart: function (t) {
567 return -1 * ((t = t / 1 - 1) * t * t * t - 1);
569 easeInOutQuart: function (t) {
570 if ((t /= 1 / 2) < 1){
571 return 1 / 2 * t * t * t * t;
573 return -1 / 2 * ((t -= 2) * t * t * t - 2);
575 easeInQuint: function (t) {
576 return 1 * (t /= 1) * t * t * t * t;
578 easeOutQuint: function (t) {
579 return 1 * ((t = t / 1 - 1) * t * t * t * t + 1);
581 easeInOutQuint: function (t) {
582 if ((t /= 1 / 2) < 1){
583 return 1 / 2 * t * t * t * t * t;
585 return 1 / 2 * ((t -= 2) * t * t * t * t + 2);
587 easeInSine: function (t) {
588 return -1 * Math.cos(t / 1 * (Math.PI / 2)) + 1;
590 easeOutSine: function (t) {
591 return 1 * Math.sin(t / 1 * (Math.PI / 2));
593 easeInOutSine: function (t) {
594 return -1 / 2 * (Math.cos(Math.PI * t / 1) - 1);
596 easeInExpo: function (t) {
597 return (t === 0) ? 1 : 1 * Math.pow(2, 10 * (t / 1 - 1));
599 easeOutExpo: function (t) {
600 return (t === 1) ? 1 : 1 * (-Math.pow(2, -10 * t / 1) + 1);
602 easeInOutExpo: function (t) {
609 if ((t /= 1 / 2) < 1){
610 return 1 / 2 * Math.pow(2, 10 * (t - 1));
612 return 1 / 2 * (-Math.pow(2, -10 * --t) + 2);
614 easeInCirc: function (t) {
618 return -1 * (Math.sqrt(1 - (t /= 1) * t) - 1);
620 easeOutCirc: function (t) {
621 return 1 * Math.sqrt(1 - (t = t / 1 - 1) * t);
623 easeInOutCirc: function (t) {
624 if ((t /= 1 / 2) < 1){
625 return -1 / 2 * (Math.sqrt(1 - t * t) - 1);
627 return 1 / 2 * (Math.sqrt(1 - (t -= 2) * t) + 1);
629 easeInElastic: function (t) {
642 if (a < Math.abs(1)) {
646 s = p / (2 * Math.PI) * Math.asin(1 / a);
648 return -(a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));
650 easeOutElastic: function (t) {
663 if (a < Math.abs(1)) {
667 s = p / (2 * Math.PI) * Math.asin(1 / a);
669 return a * Math.pow(2, -10 * t) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) + 1;
671 easeInOutElastic: function (t) {
678 if ((t /= 1 / 2) == 2){
684 if (a < Math.abs(1)) {
688 s = p / (2 * Math.PI) * Math.asin(1 / a);
691 return -0.5 * (a * Math.pow(2, 10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p));}
692 return a * Math.pow(2, -10 * (t -= 1)) * Math.sin((t * 1 - s) * (2 * Math.PI) / p) * 0.5 + 1;
694 easeInBack: function (t) {
696 return 1 * (t /= 1) * t * ((s + 1) * t - s);
698 easeOutBack: function (t) {
700 return 1 * ((t = t / 1 - 1) * t * ((s + 1) * t + s) + 1);
702 easeInOutBack: function (t) {
704 if ((t /= 1 / 2) < 1){
705 return 1 / 2 * (t * t * (((s *= (1.525)) + 1) * t - s));
707 return 1 / 2 * ((t -= 2) * t * (((s *= (1.525)) + 1) * t + s) + 2);
709 easeInBounce: function (t) {
710 return 1 - easingEffects.easeOutBounce(1 - t);
712 easeOutBounce: function (t) {
713 if ((t /= 1) < (1 / 2.75)) {
714 return 1 * (7.5625 * t * t);
715 } else if (t < (2 / 2.75)) {
716 return 1 * (7.5625 * (t -= (1.5 / 2.75)) * t + 0.75);
717 } else if (t < (2.5 / 2.75)) {
718 return 1 * (7.5625 * (t -= (2.25 / 2.75)) * t + 0.9375);
720 return 1 * (7.5625 * (t -= (2.625 / 2.75)) * t + 0.984375);
723 easeInOutBounce: function (t) {
725 return easingEffects.easeInBounce(t * 2) * 0.5;
727 return easingEffects.easeOutBounce(t * 2 - 1) * 0.5 + 1 * 0.5;
730 //Request animation polyfill - http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
731 requestAnimFrame = helpers.requestAnimFrame = (function(){
732 return window.requestAnimationFrame ||
733 window.webkitRequestAnimationFrame ||
734 window.mozRequestAnimationFrame ||
735 window.oRequestAnimationFrame ||
736 window.msRequestAnimationFrame ||
738 return window.setTimeout(callback, 1000 / 60);
741 cancelAnimFrame = helpers.cancelAnimFrame = (function(){
742 return window.cancelAnimationFrame ||
743 window.webkitCancelAnimationFrame ||
744 window.mozCancelAnimationFrame ||
745 window.oCancelAnimationFrame ||
746 window.msCancelAnimationFrame ||
748 return window.clearTimeout(callback, 1000 / 60);
751 animationLoop = helpers.animationLoop = function(callback,totalSteps,easingString,onProgress,onComplete,chartInstance){
754 easingFunction = easingEffects[easingString] || easingEffects.linear;
756 var animationFrame = function(){
758 var stepDecimal = currentStep/totalSteps;
759 var easeDecimal = easingFunction(stepDecimal);
761 callback.call(chartInstance,easeDecimal,stepDecimal, currentStep);
762 onProgress.call(chartInstance,easeDecimal,stepDecimal);
763 if (currentStep < totalSteps){
764 chartInstance.animationFrame = requestAnimFrame(animationFrame);
766 onComplete.apply(chartInstance);
769 requestAnimFrame(animationFrame);
772 getRelativePosition = helpers.getRelativePosition = function(evt){
774 var e = evt.originalEvent || evt,
775 canvas = evt.currentTarget || evt.srcElement,
776 boundingRect = canvas.getBoundingClientRect();
779 mouseX = e.touches[0].clientX - boundingRect.left;
780 mouseY = e.touches[0].clientY - boundingRect.top;
784 mouseX = e.clientX - boundingRect.left;
785 mouseY = e.clientY - boundingRect.top;
794 addEvent = helpers.addEvent = function(node,eventType,method){
795 if (node.addEventListener){
796 node.addEventListener(eventType,method);
797 } else if (node.attachEvent){
798 node.attachEvent("on"+eventType, method);
800 node["on"+eventType] = method;
803 removeEvent = helpers.removeEvent = function(node, eventType, handler){
804 if (node.removeEventListener){
805 node.removeEventListener(eventType, handler, false);
806 } else if (node.detachEvent){
807 node.detachEvent("on"+eventType,handler);
809 node["on" + eventType] = noop;
812 bindEvents = helpers.bindEvents = function(chartInstance, arrayOfEvents, handler){
813 // Create the events object if it's not already present
814 if (!chartInstance.events) chartInstance.events = {};
816 each(arrayOfEvents,function(eventName){
817 chartInstance.events[eventName] = function(){
818 handler.apply(chartInstance, arguments);
820 addEvent(chartInstance.chart.canvas,eventName,chartInstance.events[eventName]);
823 unbindEvents = helpers.unbindEvents = function (chartInstance, arrayOfEvents) {
824 each(arrayOfEvents, function(handler,eventName){
825 removeEvent(chartInstance.chart.canvas, eventName, handler);
828 getMaximumWidth = helpers.getMaximumWidth = function(domNode){
829 var container = domNode.parentNode,
830 padding = parseInt(getStyle(container, 'padding-left')) + parseInt(getStyle(container, 'padding-right'));
831 // TODO = check cross browser stuff with this.
832 return container.clientWidth - padding;
834 getMaximumHeight = helpers.getMaximumHeight = function(domNode){
835 var container = domNode.parentNode,
836 padding = parseInt(getStyle(container, 'padding-bottom')) + parseInt(getStyle(container, 'padding-top'));
837 // TODO = check cross browser stuff with this.
838 return container.clientHeight - padding;
840 getStyle = helpers.getStyle = function (el, property) {
841 return el.currentStyle ?
842 el.currentStyle[property] :
843 document.defaultView.getComputedStyle(el, null).getPropertyValue(property);
845 getMaximumSize = helpers.getMaximumSize = helpers.getMaximumWidth, // legacy support
846 retinaScale = helpers.retinaScale = function(chart){
848 width = chart.canvas.width,
849 height = chart.canvas.height;
851 if (window.devicePixelRatio) {
852 ctx.canvas.style.width = width + "px";
853 ctx.canvas.style.height = height + "px";
854 ctx.canvas.height = height * window.devicePixelRatio;
855 ctx.canvas.width = width * window.devicePixelRatio;
856 ctx.scale(window.devicePixelRatio, window.devicePixelRatio);
860 clear = helpers.clear = function(chart){
861 chart.ctx.clearRect(0,0,chart.width,chart.height);
863 fontString = helpers.fontString = function(pixelSize,fontStyle,fontFamily){
864 return fontStyle + " " + pixelSize+"px " + fontFamily;
866 longestText = helpers.longestText = function(ctx,font,arrayOfStrings){
869 each(arrayOfStrings,function(string){
870 var textWidth = ctx.measureText(string).width;
871 longest = (textWidth > longest) ? textWidth : longest;
875 drawRoundedRectangle = helpers.drawRoundedRectangle = function(ctx,x,y,width,height,radius){
877 ctx.moveTo(x + radius, y);
878 ctx.lineTo(x + width - radius, y);
879 ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
880 ctx.lineTo(x + width, y + height - radius);
881 ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
882 ctx.lineTo(x + radius, y + height);
883 ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
884 ctx.lineTo(x, y + radius);
885 ctx.quadraticCurveTo(x, y, x + radius, y);
890 //Store a reference to each instance - allowing us to globally resize chart instances on window resize.
891 //Destroy method on the chart will remove the instance of the chart from this reference.
892 Chart.instances = {};
894 Chart.Type = function(data,options,chart){
895 this.options = options;
898 //Add the chart instance to the global namespace
899 Chart.instances[this.id] = this;
901 // Initialize is always called when a chart type is created
902 // By default it is a no op, but it should be extended
903 if (options.responsive){
906 this.initialize.call(this,data);
909 //Core methods that'll be a part of every chart type
910 extend(Chart.Type.prototype,{
911 initialize : function(){return this;},
917 // Stops any current animation loop occuring
918 Chart.animationService.cancelAnimation(this);
921 resize : function(callback){
923 var canvas = this.chart.canvas,
924 newWidth = getMaximumWidth(this.chart.canvas),
925 newHeight = this.options.maintainAspectRatio ? newWidth / this.chart.aspectRatio : getMaximumHeight(this.chart.canvas);
927 canvas.width = this.chart.width = newWidth;
928 canvas.height = this.chart.height = newHeight;
930 retinaScale(this.chart);
932 if (typeof callback === "function"){
933 callback.apply(this, Array.prototype.slice.call(arguments, 1));
938 render : function(reflow){
943 if (this.options.animation && !reflow){
944 var animation = new Chart.Animation();
945 animation.numSteps = this.options.animationSteps;
946 animation.easing = this.options.animationEasing;
949 animation.render = function(chartInstance, animationObject) {
950 var easingFunction = helpers.easingEffects[animationObject.easing];
951 var stepDecimal = animationObject.currentStep / animationObject.numSteps;
952 var easeDecimal = easingFunction(stepDecimal);
954 chartInstance.draw(easeDecimal, stepDecimal, animationObject.currentStep);
958 animation.onAnimationProgress = this.options.onAnimationProgress;
959 animation.onAnimationComplete = this.options.onAnimationComplete;
961 Chart.animationService.addAnimation(this, animation);
965 this.options.onAnimationComplete.call(this);
969 generateLegend : function(){
970 return template(this.options.legendTemplate,this);
972 destroy : function(){
974 unbindEvents(this, this.events);
975 var canvas = this.chart.canvas;
977 // Reset canvas height/width attributes starts a fresh with the canvas context
978 canvas.width = this.chart.width;
979 canvas.height = this.chart.height;
981 // < IE9 doesn't support removeProperty
982 if (canvas.style.removeProperty) {
983 canvas.style.removeProperty('width');
984 canvas.style.removeProperty('height');
986 canvas.style.removeAttribute('width');
987 canvas.style.removeAttribute('height');
990 delete Chart.instances[this.id];
992 showTooltip : function(ChartElements, forceRedraw){
993 // Only redraw the chart if we've actually changed what we're hovering on.
994 if (typeof this.activeElements === 'undefined') this.activeElements = [];
996 var isChanged = (function(Elements){
999 if (Elements.length !== this.activeElements.length){
1004 each(Elements, function(element, index){
1005 if (element !== this.activeElements[index]){
1010 }).call(this, ChartElements);
1012 if (!isChanged && !forceRedraw){
1016 this.activeElements = ChartElements;
1019 if(this.options.customTooltips){
1020 this.options.customTooltips(false);
1022 if (ChartElements.length > 0){
1023 // If we have multiple datasets, show a MultiTooltip for all of the data points at that index
1024 if (this.datasets && this.datasets.length > 1) {
1028 for (var i = this.datasets.length - 1; i >= 0; i--) {
1029 dataArray = this.datasets[i].points || this.datasets[i].bars || this.datasets[i].segments;
1030 dataIndex = indexOf(dataArray, ChartElements[0]);
1031 if (dataIndex !== -1){
1035 var tooltipLabels = [],
1037 medianPosition = (function(index) {
1039 // Get all the points at that particular index
1048 helpers.each(this.datasets, function(dataset){
1049 dataCollection = dataset.points || dataset.bars || dataset.segments;
1050 if (dataCollection[dataIndex] && dataCollection[dataIndex].hasValue()){
1051 Elements.push(dataCollection[dataIndex]);
1055 helpers.each(Elements, function(element) {
1056 xPositions.push(element.x);
1057 yPositions.push(element.y);
1060 //Include any colour information about the element
1061 tooltipLabels.push(helpers.template(this.options.multiTooltipTemplate, element));
1062 tooltipColors.push({
1063 fill: element._saved.fillColor || element.fillColor,
1064 stroke: element._saved.strokeColor || element.strokeColor
1069 yMin = min(yPositions);
1070 yMax = max(yPositions);
1072 xMin = min(xPositions);
1073 xMax = max(xPositions);
1076 x: (xMin > this.chart.width/2) ? xMin : xMax,
1079 }).call(this, dataIndex);
1081 new Chart.MultiTooltip({
1082 x: medianPosition.x,
1083 y: medianPosition.y,
1084 xPadding: this.options.tooltipXPadding,
1085 yPadding: this.options.tooltipYPadding,
1086 xOffset: this.options.tooltipXOffset,
1087 fillColor: this.options.tooltipFillColor,
1088 textColor: this.options.tooltipFontColor,
1089 fontFamily: this.options.tooltipFontFamily,
1090 fontStyle: this.options.tooltipFontStyle,
1091 fontSize: this.options.tooltipFontSize,
1092 titleTextColor: this.options.tooltipTitleFontColor,
1093 titleFontFamily: this.options.tooltipTitleFontFamily,
1094 titleFontStyle: this.options.tooltipTitleFontStyle,
1095 titleFontSize: this.options.tooltipTitleFontSize,
1096 cornerRadius: this.options.tooltipCornerRadius,
1097 labels: tooltipLabels,
1098 legendColors: tooltipColors,
1099 legendColorBackground : this.options.multiTooltipKeyBackground,
1100 title: ChartElements[0].label,
1102 ctx: this.chart.ctx,
1103 custom: this.options.customTooltips
1107 each(ChartElements, function(Element) {
1108 var tooltipPosition = Element.tooltipPosition();
1110 x: Math.round(tooltipPosition.x),
1111 y: Math.round(tooltipPosition.y),
1112 xPadding: this.options.tooltipXPadding,
1113 yPadding: this.options.tooltipYPadding,
1114 fillColor: this.options.tooltipFillColor,
1115 textColor: this.options.tooltipFontColor,
1116 fontFamily: this.options.tooltipFontFamily,
1117 fontStyle: this.options.tooltipFontStyle,
1118 fontSize: this.options.tooltipFontSize,
1119 caretHeight: this.options.tooltipCaretSize,
1120 cornerRadius: this.options.tooltipCornerRadius,
1121 text: template(this.options.tooltipTemplate, Element),
1123 custom: this.options.customTooltips
1130 toBase64Image : function(){
1131 return this.chart.canvas.toDataURL.apply(this.chart.canvas, arguments);
1135 Chart.Type.extend = function(extensions){
1139 var ChartType = function(){
1140 return parent.apply(this,arguments);
1143 //Copy the prototype object of the this class
1144 ChartType.prototype = clone(parent.prototype);
1145 //Now overwrite some of the properties in the base class with the new extensions
1146 extend(ChartType.prototype, extensions);
1148 ChartType.extend = Chart.Type.extend;
1150 if (extensions.name || parent.prototype.name){
1152 var chartName = extensions.name || parent.prototype.name;
1153 //Assign any potential default values of the new chart type
1155 //If none are defined, we'll use a clone of the chart type this is being extended from.
1156 //I.e. if we extend a line chart, we'll use the defaults from the line chart if our new chart
1157 //doesn't define some defaults of their own.
1159 var baseDefaults = (Chart.defaults[parent.prototype.name]) ? clone(Chart.defaults[parent.prototype.name]) : {};
1161 Chart.defaults[chartName] = extend(baseDefaults,extensions.defaults);
1163 Chart.types[chartName] = ChartType;
1165 //Register this new chart type in the Chart prototype
1166 Chart.prototype[chartName] = function(data,options){
1167 var config = merge(Chart.defaults.global, Chart.defaults[chartName], options || {});
1168 return new ChartType(data,config,this);
1171 warn("Name not provided for this chart, so it hasn't been registered");
1176 Chart.Element = function(configuration){
1177 extend(this,configuration);
1178 this.initialize.apply(this,arguments);
1181 extend(Chart.Element.prototype,{
1182 initialize : function(){},
1183 restore : function(props){
1185 extend(this,this._saved);
1187 each(props,function(key){
1188 this[key] = this._saved[key];
1194 this._saved = clone(this);
1195 delete this._saved._saved;
1198 update : function(newProps){
1199 each(newProps,function(value,key){
1200 this._saved[key] = this[key];
1205 transition : function(props,ease){
1206 each(props,function(value,key){
1207 this[key] = ((value - this._saved[key]) * ease) + this._saved[key];
1211 tooltipPosition : function(){
1217 hasValue: function(){
1218 return isNumber(this.value);
1222 Chart.Element.extend = inherits;
1225 Chart.Point = Chart.Element.extend({
1227 inRange: function(chartX,chartY){
1228 var hitDetectionRange = this.hitDetectionRadius + this.radius;
1229 return ((Math.pow(chartX-this.x, 2)+Math.pow(chartY-this.y, 2)) < Math.pow(hitDetectionRange,2));
1236 ctx.arc(this.x, this.y, this.radius, 0, Math.PI*2);
1239 ctx.strokeStyle = this.strokeColor;
1240 ctx.lineWidth = this.strokeWidth;
1242 ctx.fillStyle = this.fillColor;
1249 //Quick debug for bezier curve splining
1250 //Highlights control points and the line between them.
1251 //Handy for dev - stripped in the min version.
1254 // ctx.fillStyle = "black";
1255 // ctx.strokeStyle = "black"
1257 // ctx.arc(this.controlPoints.inner.x,this.controlPoints.inner.y, 2, 0, Math.PI*2);
1261 // ctx.arc(this.controlPoints.outer.x,this.controlPoints.outer.y, 2, 0, Math.PI*2);
1264 // ctx.moveTo(this.controlPoints.inner.x,this.controlPoints.inner.y);
1265 // ctx.lineTo(this.x, this.y);
1266 // ctx.lineTo(this.controlPoints.outer.x,this.controlPoints.outer.y);
1276 Chart.Arc = Chart.Element.extend({
1277 inRange : function(chartX,chartY){
1279 var pointRelativePosition = helpers.getAngleFromPoint(this, {
1284 //Check if within the range of the open/close angle
1285 var betweenAngles = (pointRelativePosition.angle >= this.startAngle && pointRelativePosition.angle <= this.endAngle),
1286 withinRadius = (pointRelativePosition.distance >= this.innerRadius && pointRelativePosition.distance <= this.outerRadius);
1288 return (betweenAngles && withinRadius);
1289 //Ensure within the outside of the arc centre, but inside arc outer
1291 tooltipPosition : function(){
1292 var centreAngle = this.startAngle + ((this.endAngle - this.startAngle) / 2),
1293 rangeFromCentre = (this.outerRadius - this.innerRadius) / 2 + this.innerRadius;
1295 x : this.x + (Math.cos(centreAngle) * rangeFromCentre),
1296 y : this.y + (Math.sin(centreAngle) * rangeFromCentre)
1299 draw : function(animationPercent){
1301 var easingDecimal = animationPercent || 1;
1307 ctx.arc(this.x, this.y, this.outerRadius, this.startAngle, this.endAngle);
1309 ctx.arc(this.x, this.y, this.innerRadius, this.endAngle, this.startAngle, true);
1312 ctx.strokeStyle = this.strokeColor;
1313 ctx.lineWidth = this.strokeWidth;
1315 ctx.fillStyle = this.fillColor;
1318 ctx.lineJoin = 'bevel';
1320 if (this.showStroke){
1326 Chart.Rectangle = Chart.Element.extend({
1329 halfWidth = this.width/2,
1330 leftX = this.x - halfWidth,
1331 rightX = this.x + halfWidth,
1332 top = this.base - (this.base - this.y),
1333 halfStroke = this.strokeWidth / 2;
1335 // Canvas doesn't allow us to stroke inside the width so we can
1336 // adjust the sizes to fit if we're setting a stroke on the line
1337 if (this.showStroke){
1338 leftX += halfStroke;
1339 rightX -= halfStroke;
1345 ctx.fillStyle = this.fillColor;
1346 ctx.strokeStyle = this.strokeColor;
1347 ctx.lineWidth = this.strokeWidth;
1349 // It'd be nice to keep this class totally generic to any rectangle
1350 // and simply specify which border to miss out.
1351 ctx.moveTo(leftX, this.base);
1352 ctx.lineTo(leftX, top);
1353 ctx.lineTo(rightX, top);
1354 ctx.lineTo(rightX, this.base);
1356 if (this.showStroke){
1360 height : function(){
1361 return this.base - this.y;
1363 inRange : function(chartX,chartY){
1364 return (chartX >= this.x - this.width/2 && chartX <= this.x + this.width/2) && (chartY >= this.y && chartY <= this.base);
1368 Chart.Animation = Chart.Element.extend({
1369 currentStep: null, // the current animation step
1370 numSteps: 60, // default number of steps
1371 easing: "", // the easing to use for this animation
1372 render: null, // render function used by the animation service
1374 onAnimationProgress: null, // user specified callback to fire on each step of the animation
1375 onAnimationComplete: null, // user specified callback to fire when the animation finishes
1378 Chart.Tooltip = Chart.Element.extend({
1381 var ctx = this.chart.ctx;
1383 ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
1385 this.xAlign = "center";
1386 this.yAlign = "above";
1388 //Distance between the actual element.y position and the start of the tooltip caret
1389 var caretPadding = this.caretPadding = 2;
1391 var tooltipWidth = ctx.measureText(this.text).width + 2*this.xPadding,
1392 tooltipRectHeight = this.fontSize + 2*this.yPadding,
1393 tooltipHeight = tooltipRectHeight + this.caretHeight + caretPadding;
1395 if (this.x + tooltipWidth/2 >this.chart.width){
1396 this.xAlign = "left";
1397 } else if (this.x - tooltipWidth/2 < 0){
1398 this.xAlign = "right";
1401 if (this.y - tooltipHeight < 0){
1402 this.yAlign = "below";
1406 var tooltipX = this.x - tooltipWidth/2,
1407 tooltipY = this.y - tooltipHeight;
1409 ctx.fillStyle = this.fillColor;
1419 //Draw a caret above the x/y
1421 ctx.moveTo(this.x,this.y - caretPadding);
1422 ctx.lineTo(this.x + this.caretHeight, this.y - (caretPadding + this.caretHeight));
1423 ctx.lineTo(this.x - this.caretHeight, this.y - (caretPadding + this.caretHeight));
1428 tooltipY = this.y + caretPadding + this.caretHeight;
1429 //Draw a caret below the x/y
1431 ctx.moveTo(this.x, this.y + caretPadding);
1432 ctx.lineTo(this.x + this.caretHeight, this.y + caretPadding + this.caretHeight);
1433 ctx.lineTo(this.x - this.caretHeight, this.y + caretPadding + this.caretHeight);
1442 tooltipX = this.x - tooltipWidth + (this.cornerRadius + this.caretHeight);
1445 tooltipX = this.x - (this.cornerRadius + this.caretHeight);
1449 drawRoundedRectangle(ctx,tooltipX,tooltipY,tooltipWidth,tooltipRectHeight,this.cornerRadius);
1453 ctx.fillStyle = this.textColor;
1454 ctx.textAlign = "center";
1455 ctx.textBaseline = "middle";
1456 ctx.fillText(this.text, tooltipX + tooltipWidth/2, tooltipY + tooltipRectHeight/2);
1461 Chart.MultiTooltip = Chart.Element.extend({
1462 initialize : function(){
1463 this.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
1465 this.titleFont = fontString(this.titleFontSize,this.titleFontStyle,this.titleFontFamily);
1467 this.height = (this.labels.length * this.fontSize) + ((this.labels.length-1) * (this.fontSize/2)) + (this.yPadding*2) + this.titleFontSize *1.5;
1469 this.ctx.font = this.titleFont;
1471 var titleWidth = this.ctx.measureText(this.title).width,
1472 //Label has a legend square as well so account for this.
1473 labelWidth = longestText(this.ctx,this.font,this.labels) + this.fontSize + 3,
1474 longestTextWidth = max([labelWidth,titleWidth]);
1476 this.width = longestTextWidth + (this.xPadding*2);
1479 var halfHeight = this.height/2;
1481 //Check to ensure the height will fit on the canvas
1482 if (this.y - halfHeight < 0 ){
1483 this.y = halfHeight;
1484 } else if (this.y + halfHeight > this.chart.height){
1485 this.y = this.chart.height - halfHeight;
1488 //Decide whether to align left or right based on position on canvas
1489 if (this.x > this.chart.width/2){
1490 this.x -= this.xOffset + this.width;
1492 this.x += this.xOffset;
1497 getLineHeight : function(index){
1498 var baseLineHeight = this.y - (this.height/2) + this.yPadding,
1499 afterTitleIndex = index-1;
1501 //If the index is zero, we're getting the title
1503 return baseLineHeight + this.titleFontSize/2;
1505 return baseLineHeight + ((this.fontSize*1.5*afterTitleIndex) + this.fontSize/2) + this.titleFontSize * 1.5;
1515 drawRoundedRectangle(this.ctx,this.x,this.y - this.height/2,this.width,this.height,this.cornerRadius);
1517 ctx.fillStyle = this.fillColor;
1521 ctx.textAlign = "left";
1522 ctx.textBaseline = "middle";
1523 ctx.fillStyle = this.titleTextColor;
1524 ctx.font = this.titleFont;
1526 ctx.fillText(this.title,this.x + this.xPadding, this.getLineHeight(0));
1528 ctx.font = this.font;
1529 helpers.each(this.labels,function(label,index){
1530 ctx.fillStyle = this.textColor;
1531 ctx.fillText(label,this.x + this.xPadding + this.fontSize + 3, this.getLineHeight(index + 1));
1533 //A bit gnarly, but clearing this rectangle breaks when using explorercanvas (clears whole canvas)
1534 //ctx.clearRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
1535 //Instead we'll make a white filled block to put the legendColour palette over.
1537 ctx.fillStyle = this.legendColorBackground;
1538 ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
1540 ctx.fillStyle = this.legendColors[index].fill;
1541 ctx.fillRect(this.x + this.xPadding, this.getLineHeight(index + 1) - this.fontSize/2, this.fontSize, this.fontSize);
1549 Chart.Scale = Chart.Element.extend({
1550 initialize : function(){
1553 buildYLabels : function(){
1556 var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
1558 for (var i=0; i<=this.steps; i++){
1559 this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
1561 this.yLabelWidth = (this.display && this.showLabels) ? longestText(this.ctx,this.font,this.yLabels) + 10 : 0;
1563 addXLabel : function(label){
1564 this.xLabels.push(label);
1568 removeXLabel : function(){
1569 this.xLabels.shift();
1573 // Fitting loop to rotate x Labels and figure out what fits there, and also calculate how many Y steps to use
1575 // First we need the width of the yLabels, assuming the xLabels aren't rotated
1577 // To do that we need the base line at the top and base of the chart, assuming there is no x label rotation
1578 this.startPoint = (this.display) ? this.fontSize : 0;
1579 this.endPoint = (this.display) ? this.height - (this.fontSize * 1.5) - 5 : this.height; // -5 to pad labels
1581 // Apply padding settings to the start and end point.
1582 this.startPoint += this.padding;
1583 this.endPoint -= this.padding;
1585 // Cache the starting endpoint, excluding the space for x labels
1586 var cachedEndPoint = this.endPoint;
1588 // Cache the starting height, so can determine if we need to recalculate the scale yAxis
1589 var cachedHeight = this.endPoint - this.startPoint,
1592 // Build the current yLabels so we have an idea of what size they'll be to start
1594 * This sets what is returned from calculateScaleRange as static properties of this class:
1602 this.calculateYRange(cachedHeight);
1604 // With these properties set we can now build the array of yLabels
1605 // and also the width of the largest yLabel
1606 this.buildYLabels();
1608 this.calculateXLabelRotation();
1610 while((cachedHeight > this.endPoint - this.startPoint)){
1611 cachedHeight = this.endPoint - this.startPoint;
1612 cachedYLabelWidth = this.yLabelWidth;
1614 this.calculateYRange(cachedHeight);
1615 this.buildYLabels();
1617 // Only go through the xLabel loop again if the yLabel width has changed
1618 if (cachedYLabelWidth < this.yLabelWidth){
1619 this.endPoint = cachedEndPoint;
1620 this.calculateXLabelRotation();
1625 calculateXLabelRotation : function(){
1626 //Get the width of each grid by calculating the difference
1627 //between x offsets between 0 and 1.
1629 this.ctx.font = this.font;
1631 var firstWidth = this.ctx.measureText(this.xLabels[0]).width,
1632 lastWidth = this.ctx.measureText(this.xLabels[this.xLabels.length - 1]).width,
1637 this.xScalePaddingRight = lastWidth/2 + 3;
1638 this.xScalePaddingLeft = (firstWidth/2 > this.yLabelWidth) ? firstWidth/2 : this.yLabelWidth;
1640 this.xLabelRotation = 0;
1642 var originalLabelWidth = longestText(this.ctx,this.font,this.xLabels),
1645 this.xLabelWidth = originalLabelWidth;
1646 //Allow 3 pixels x2 padding either side for label readability
1647 var xGridWidth = Math.floor(this.calculateX(1) - this.calculateX(0)) - 6;
1649 //Max label rotate should be 90 - also act as a loop counter
1650 while ((this.xLabelWidth > xGridWidth && this.xLabelRotation === 0) || (this.xLabelWidth > xGridWidth && this.xLabelRotation <= 90 && this.xLabelRotation > 0)){
1651 cosRotation = Math.cos(toRadians(this.xLabelRotation));
1653 firstRotated = cosRotation * firstWidth;
1654 lastRotated = cosRotation * lastWidth;
1656 // We're right aligning the text now.
1657 if (firstRotated + this.fontSize / 2 > this.yLabelWidth){
1658 this.xScalePaddingLeft = firstRotated + this.fontSize / 2;
1660 this.xScalePaddingRight = this.fontSize/2;
1663 this.xLabelRotation++;
1664 this.xLabelWidth = cosRotation * originalLabelWidth;
1667 if (this.xLabelRotation > 0){
1668 this.endPoint -= Math.sin(toRadians(this.xLabelRotation))*originalLabelWidth + 3;
1672 this.xLabelWidth = 0;
1673 this.xScalePaddingRight = this.padding;
1674 this.xScalePaddingLeft = this.padding;
1678 // Needs to be overidden in each Chart type
1679 // Otherwise we need to pass all the data into the scale class
1680 calculateYRange: noop,
1681 drawingArea: function(){
1682 return this.startPoint - this.endPoint;
1684 calculateY : function(value){
1685 var scalingFactor = this.drawingArea() / (this.min - this.max);
1686 return this.endPoint - (scalingFactor * (value - this.min));
1688 calculateX : function(index){
1689 var isRotated = (this.xLabelRotation > 0),
1690 // innerWidth = (this.offsetGridLines) ? this.width - offsetLeft - this.padding : this.width - (offsetLeft + halfLabelWidth * 2) - this.padding,
1691 innerWidth = this.width - (this.xScalePaddingLeft + this.xScalePaddingRight),
1692 valueWidth = innerWidth/Math.max((this.valuesCount - ((this.offsetGridLines) ? 0 : 1)), 1),
1693 valueOffset = (valueWidth * index) + this.xScalePaddingLeft;
1695 if (this.offsetGridLines){
1696 valueOffset += (valueWidth/2);
1699 return Math.round(valueOffset);
1701 update : function(newProps){
1702 helpers.extend(this, newProps);
1707 yLabelGap = (this.endPoint - this.startPoint) / this.steps,
1708 xStart = Math.round(this.xScalePaddingLeft);
1710 ctx.fillStyle = this.textColor;
1711 ctx.font = this.font;
1712 each(this.yLabels,function(labelString,index){
1713 var yLabelCenter = this.endPoint - (yLabelGap * index),
1714 linePositionY = Math.round(yLabelCenter),
1715 drawHorizontalLine = this.showHorizontalLines;
1717 ctx.textAlign = "right";
1718 ctx.textBaseline = "middle";
1719 if (this.showLabels){
1720 ctx.fillText(labelString,xStart - 10,yLabelCenter);
1723 // This is X axis, so draw it
1724 if (index === 0 && !drawHorizontalLine){
1725 drawHorizontalLine = true;
1728 if (drawHorizontalLine){
1733 // This is a grid line in the centre, so drop that
1734 ctx.lineWidth = this.gridLineWidth;
1735 ctx.strokeStyle = this.gridLineColor;
1737 // This is the first line on the scale
1738 ctx.lineWidth = this.lineWidth;
1739 ctx.strokeStyle = this.lineColor;
1742 linePositionY += helpers.aliasPixel(ctx.lineWidth);
1744 if(drawHorizontalLine){
1745 ctx.moveTo(xStart, linePositionY);
1746 ctx.lineTo(this.width, linePositionY);
1751 ctx.lineWidth = this.lineWidth;
1752 ctx.strokeStyle = this.lineColor;
1754 ctx.moveTo(xStart - 5, linePositionY);
1755 ctx.lineTo(xStart, linePositionY);
1761 each(this.xLabels,function(label,index){
1762 var xPos = this.calculateX(index) + aliasPixel(this.lineWidth),
1763 // Check to see if line/bar here and decide where to place the line
1764 linePos = this.calculateX(index - (this.offsetGridLines ? 0.5 : 0)) + aliasPixel(this.lineWidth),
1765 isRotated = (this.xLabelRotation > 0),
1766 drawVerticalLine = this.showVerticalLines;
1768 // This is Y axis, so draw it
1769 if (index === 0 && !drawVerticalLine){
1770 drawVerticalLine = true;
1773 if (drawVerticalLine){
1778 // This is a grid line in the centre, so drop that
1779 ctx.lineWidth = this.gridLineWidth;
1780 ctx.strokeStyle = this.gridLineColor;
1782 // This is the first line on the scale
1783 ctx.lineWidth = this.lineWidth;
1784 ctx.strokeStyle = this.lineColor;
1787 if (drawVerticalLine){
1788 ctx.moveTo(linePos,this.endPoint);
1789 ctx.lineTo(linePos,this.startPoint - 3);
1795 ctx.lineWidth = this.lineWidth;
1796 ctx.strokeStyle = this.lineColor;
1799 // Small lines at the bottom of the base grid line
1801 ctx.moveTo(linePos,this.endPoint);
1802 ctx.lineTo(linePos,this.endPoint + 5);
1807 ctx.translate(xPos,(isRotated) ? this.endPoint + 12 : this.endPoint + 8);
1808 ctx.rotate(toRadians(this.xLabelRotation)*-1);
1809 ctx.font = this.font;
1810 ctx.textAlign = (isRotated) ? "right" : "center";
1811 ctx.textBaseline = (isRotated) ? "middle" : "top";
1812 ctx.fillText(label, 0, 0);
1821 Chart.RadialScale = Chart.Element.extend({
1822 initialize: function(){
1823 this.size = min([this.height, this.width]);
1824 this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
1826 calculateCenterOffset: function(value){
1827 // Take into account half font size + the yPadding of the top value
1828 var scalingFactor = this.drawingArea / (this.max - this.min);
1830 return (value - this.min) * scalingFactor;
1832 update : function(){
1834 this.setScaleSize();
1836 this.drawingArea = (this.display) ? (this.size/2) - (this.fontSize/2 + this.backdropPaddingY) : (this.size/2);
1838 this.buildYLabels();
1840 buildYLabels: function(){
1843 var stepDecimalPlaces = getDecimalPlaces(this.stepValue);
1845 for (var i=0; i<=this.steps; i++){
1846 this.yLabels.push(template(this.templateString,{value:(this.min + (i * this.stepValue)).toFixed(stepDecimalPlaces)}));
1849 getCircumference : function(){
1850 return ((Math.PI*2) / this.valuesCount);
1852 setScaleSize: function(){
1854 * Right, this is really confusing and there is a lot of maths going on here
1855 * The gist of the problem is here: https://gist.github.com/nnnick/696cc9c55f4b0beb8fe9
1857 * Reaction: https://dl.dropboxusercontent.com/u/34601363/toomuchscience.gif
1861 * We assume the radius of the polygon is half the size of the canvas at first
1862 * at each index we check if the text overlaps.
1864 * Where it does, we store that angle and that index.
1866 * After finding the largest index and angle we calculate how much we need to remove
1867 * from the shape radius to move the point inwards by that x.
1869 * We average the left and right distances to get the maximum shape radius that can fit in the box
1870 * along with labels.
1872 * Once we have that, we can find the centre point for the chart, by taking the x text protrusion
1873 * on each side, removing that from the size, halving it and adding the left x protrusion width.
1875 * This will mean we have a shape fitted to the canvas, as large as it can be with the labels
1876 * and position it in the most space efficient manner
1878 * https://dl.dropboxusercontent.com/u/34601363/yeahscience.gif
1882 // Get maximum radius of the polygon. Either half the height (minus the text width) or half the width.
1883 // Use this to calculate the offset + change. - Make sure L/R protrusion is at least 0 to stop issues with centre points
1884 var largestPossibleRadius = min([(this.height/2 - this.pointLabelFontSize - 5), this.width/2]),
1889 furthestRight = this.width,
1897 radiusReductionRight,
1898 radiusReductionLeft,
1900 this.ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
1901 for (i=0;i<this.valuesCount;i++){
1902 // 5px to space the text slightly out - similar to what we do in the draw function.
1903 pointPosition = this.getPointPosition(i, largestPossibleRadius);
1904 textWidth = this.ctx.measureText(template(this.templateString, { value: this.labels[i] })).width + 5;
1905 if (i === 0 || i === this.valuesCount/2){
1906 // If we're at index zero, or exactly the middle, we're at exactly the top/bottom
1907 // of the radar chart, so text will be aligned centrally, so we'll half it and compare
1908 // w/left and right text sizes
1909 halfTextWidth = textWidth/2;
1910 if (pointPosition.x + halfTextWidth > furthestRight) {
1911 furthestRight = pointPosition.x + halfTextWidth;
1912 furthestRightIndex = i;
1914 if (pointPosition.x - halfTextWidth < furthestLeft) {
1915 furthestLeft = pointPosition.x - halfTextWidth;
1916 furthestLeftIndex = i;
1919 else if (i < this.valuesCount/2) {
1920 // Less than half the values means we'll left align the text
1921 if (pointPosition.x + textWidth > furthestRight) {
1922 furthestRight = pointPosition.x + textWidth;
1923 furthestRightIndex = i;
1926 else if (i > this.valuesCount/2){
1927 // More than half the values means we'll right align the text
1928 if (pointPosition.x - textWidth < furthestLeft) {
1929 furthestLeft = pointPosition.x - textWidth;
1930 furthestLeftIndex = i;
1935 xProtrusionLeft = furthestLeft;
1937 xProtrusionRight = Math.ceil(furthestRight - this.width);
1939 furthestRightAngle = this.getIndexAngle(furthestRightIndex);
1941 furthestLeftAngle = this.getIndexAngle(furthestLeftIndex);
1943 radiusReductionRight = xProtrusionRight / Math.sin(furthestRightAngle + Math.PI/2);
1945 radiusReductionLeft = xProtrusionLeft / Math.sin(furthestLeftAngle + Math.PI/2);
1947 // Ensure we actually need to reduce the size of the chart
1948 radiusReductionRight = (isNumber(radiusReductionRight)) ? radiusReductionRight : 0;
1949 radiusReductionLeft = (isNumber(radiusReductionLeft)) ? radiusReductionLeft : 0;
1951 this.drawingArea = largestPossibleRadius - (radiusReductionLeft + radiusReductionRight)/2;
1953 //this.drawingArea = min([maxWidthRadius, (this.height - (2 * (this.pointLabelFontSize + 5)))/2])
1954 this.setCenterPoint(radiusReductionLeft, radiusReductionRight);
1957 setCenterPoint: function(leftMovement, rightMovement){
1959 var maxRight = this.width - rightMovement - this.drawingArea,
1960 maxLeft = leftMovement + this.drawingArea;
1962 this.xCenter = (maxLeft + maxRight)/2;
1963 // Always vertically in the centre as the text height doesn't change
1964 this.yCenter = (this.height/2);
1967 getIndexAngle : function(index){
1968 var angleMultiplier = (Math.PI * 2) / this.valuesCount;
1969 // Start from the top instead of right, so remove a quarter of the circle
1971 return index * angleMultiplier - (Math.PI/2);
1973 getPointPosition : function(index, distanceFromCenter){
1974 var thisAngle = this.getIndexAngle(index);
1976 x : (Math.cos(thisAngle) * distanceFromCenter) + this.xCenter,
1977 y : (Math.sin(thisAngle) * distanceFromCenter) + this.yCenter
1983 each(this.yLabels, function(label, index){
1984 // Don't draw a centre value
1986 var yCenterOffset = index * (this.drawingArea/this.steps),
1987 yHeight = this.yCenter - yCenterOffset,
1990 // Draw circular lines around the scale
1991 if (this.lineWidth > 0){
1992 ctx.strokeStyle = this.lineColor;
1993 ctx.lineWidth = this.lineWidth;
1997 ctx.arc(this.xCenter, this.yCenter, yCenterOffset, 0, Math.PI*2);
2002 for (var i=0;i<this.valuesCount;i++)
2004 pointPosition = this.getPointPosition(i, this.calculateCenterOffset(this.min + (index * this.stepValue)));
2006 ctx.moveTo(pointPosition.x, pointPosition.y);
2008 ctx.lineTo(pointPosition.x, pointPosition.y);
2015 if(this.showLabels){
2016 ctx.font = fontString(this.fontSize,this.fontStyle,this.fontFamily);
2017 if (this.showLabelBackdrop){
2018 var labelWidth = ctx.measureText(label).width;
2019 ctx.fillStyle = this.backdropColor;
2021 this.xCenter - labelWidth/2 - this.backdropPaddingX,
2022 yHeight - this.fontSize/2 - this.backdropPaddingY,
2023 labelWidth + this.backdropPaddingX*2,
2024 this.fontSize + this.backdropPaddingY*2
2027 ctx.textAlign = 'center';
2028 ctx.textBaseline = "middle";
2029 ctx.fillStyle = this.fontColor;
2030 ctx.fillText(label, this.xCenter, yHeight);
2036 ctx.lineWidth = this.angleLineWidth;
2037 ctx.strokeStyle = this.angleLineColor;
2038 for (var i = this.valuesCount - 1; i >= 0; i--) {
2039 if (this.angleLineWidth > 0){
2040 var outerPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max));
2042 ctx.moveTo(this.xCenter, this.yCenter);
2043 ctx.lineTo(outerPosition.x, outerPosition.y);
2047 // Extra 3px out for some label spacing
2048 var pointLabelPosition = this.getPointPosition(i, this.calculateCenterOffset(this.max) + 5);
2049 ctx.font = fontString(this.pointLabelFontSize,this.pointLabelFontStyle,this.pointLabelFontFamily);
2050 ctx.fillStyle = this.pointLabelFontColor;
2052 var labelsCount = this.labels.length,
2053 halfLabelsCount = this.labels.length/2,
2054 quarterLabelsCount = halfLabelsCount/2,
2055 upperHalf = (i < quarterLabelsCount || i > labelsCount - quarterLabelsCount),
2056 exactQuarter = (i === quarterLabelsCount || i === labelsCount - quarterLabelsCount);
2058 ctx.textAlign = 'center';
2059 } else if(i === halfLabelsCount){
2060 ctx.textAlign = 'center';
2061 } else if (i < halfLabelsCount){
2062 ctx.textAlign = 'left';
2064 ctx.textAlign = 'right';
2067 // Set the correct text baseline based on outer positioning
2069 ctx.textBaseline = 'middle';
2070 } else if (upperHalf){
2071 ctx.textBaseline = 'bottom';
2073 ctx.textBaseline = 'top';
2076 ctx.fillText(this.labels[i], pointLabelPosition.x, pointLabelPosition.y);
2083 Chart.animationService = {
2087 addAnimation: function(chartInstance, animationObject) {
2088 for (var index = 0; index < this.animations.length; ++ index){
2089 if (this.animations[index].chartInstance === chartInstance){
2090 // replacing an in progress animation
2091 this.animations[index].animationObject = animationObject;
2096 this.animations.push({
2097 chartInstance: chartInstance,
2098 animationObject: animationObject
2101 // If there are no animations queued, manually kickstart a digest, for lack of a better word
2102 if (this.animations.length == 1) {
2103 helpers.requestAnimFrame.call(window, this.digestWrapper);
2106 // Cancel the animation for a given chart instance
2107 cancelAnimation: function(chartInstance) {
2108 var index = helpers.findNextWhere(this.animations, function(animationWrapper) {
2109 return animationWrapper.chartInstance === chartInstance;
2114 this.animations.splice(index, 1);
2117 // calls startDigest with the proper context
2118 digestWrapper: function() {
2119 Chart.animationService.startDigest.call(Chart.animationService);
2121 startDigest: function() {
2123 var startTime = Date.now();
2124 var framesToDrop = 0;
2126 if(this.dropFrames > 1){
2127 framesToDrop = Math.floor(this.dropFrames);
2128 this.dropFrames -= framesToDrop;
2131 for (var i = 0; i < this.animations.length; i++) {
2133 if (this.animations[i].animationObject.currentStep === null){
2134 this.animations[i].animationObject.currentStep = 0;
2137 this.animations[i].animationObject.currentStep += 1 + framesToDrop;
2138 if(this.animations[i].animationObject.currentStep > this.animations[i].animationObject.numSteps){
2139 this.animations[i].animationObject.currentStep = this.animations[i].animationObject.numSteps;
2142 this.animations[i].animationObject.render(this.animations[i].chartInstance, this.animations[i].animationObject);
2144 if (this.animations[i].animationObject.currentStep == this.animations[i].animationObject.numSteps){
2145 // executed the last frame. Remove the animation.
2146 this.animations.splice(i, 1);
2147 // Keep the index in place to offset the splice
2152 var endTime = Date.now();
2153 var delay = endTime - startTime - this.frameDuration;
2154 var frameDelay = delay / this.frameDuration;
2157 this.dropFrames += frameDelay;
2160 // Do we have more stuff to animate?
2161 if (this.animations.length > 0){
2162 helpers.requestAnimFrame.call(window, this.digestWrapper);
2167 // Attach global event to resize each chart instance when the browser resizes
2168 helpers.addEvent(window, "resize", (function(){
2169 // Basic debounce of resize function so it doesn't hurt performance when resizing browser.
2172 clearTimeout(timeout);
2173 timeout = setTimeout(function(){
2174 each(Chart.instances,function(instance){
2175 // If the responsive flag is set in the chart instance config
2176 // Cascade the resize event down to the chart.
2177 if (instance.options.responsive){
2178 instance.resize(instance.render, true);
2190 } else if (typeof module === 'object' && module.exports) {
2191 module.exports = Chart;
2196 Chart.noConflict = function(){
2197 root.Chart = previous;