пятница, 31 октября 2014 г.

Calculating linear trend line for the chart components in JS

Display trend line is quite common problem while working with charts as front-end developer. Here I provide example of JS function for calculation linear trend line values and adding values to provided array of JSON values.
function(scores) {
    // Calculating the Slope (m) of the Trendline

    var count = scores.length;
    var ySum = 0, xSum = 0, xySum = 0, xSqSum = 0;
    $.each(scores, function( index, value ) {
        xSum += value.day;
        ySum += value.score;
        xySum += value.day * value.score;
        xSqSum += Math.pow(value.day, 2);
    });
    var slope = ((count * xySum) - (xSum * ySum)) / ((count * xSqSum) - Math.pow(ySum, 2));
    // Calculating the y-intercept (b) of the Trendline

    var yIntercept = (ySum - slope*xSum) / count;

    $.each(scores, function( index, value ) {
        value.trend = (value.day * slope) + yIntercept;
    });
};

пятница, 17 октября 2014 г.

Correctly display of negative ranges on ExtJS bar graphs

Bar graphs from Sencha ExtJS are great, but not without challenges for developers:) On of such issue I found during building graph with both, positive and negative, ranges. For example, your values are in the range [-100, 100].  In this case default behaviour of bar chart will be to have bars drawn from "zero" vertical line, but you need to be drawn from -100. My solution was to change values first to be "actualValue+100" (always positive in our case) and then make labels display correct value, it's done with customized render function:

axes: [{
        type: 'numeric',
        position: 'bottom',
        fields: 'score',
        minimum: 0,
        maximum: 200,
        majorTickSteps: 4,
        renderer: function (v) {
            // Make axis label display correct actual value
            return v - 100;
        }
    },
    ...

четверг, 16 октября 2014 г.

Crossbrowser solution to copy canvas elements

Sometimes you need to clone exisitng canvas elements to the new place, keeping its content. Solution for this problem is simple, but for IE additional workaround should be implemented, as always:)

/**
 * Copy canvas element image content.
 * @param oldCanvas old canvas element
 * @param newCanvas new canvas element
 * @param document current window document
 */
copyCanvas: function (oldCanvas, newCanvas, document) {
        if (oldCanvas) {
            try {
                // For IE browser replace canvas element with img with
                // source of old canvas, as drawImage causes
                // TypeMismatchError
                var agent = window.navigator.userAgent;
                // Check for both, IE11 and older versions
                if ((agent.indexOf('MSIE ') > -1) || (agent.indexOf('Trident/') > -1)) {
                    var oldImage = oldCanvas.toDataURL();
                    var img = document.createElement("img");
                    img.src = oldImage;
                    $(newCanvas).replaceWith(img);
                } else {
                    var context = newCanvas.getContext('2d');
                    context.drawImage(oldCanvas, 0, 0);
                }
            } catch (e) {
                console.log(e.name);
            }
        }
    }