Last Updated: February 25, 2016
·
2.866K
· darbicus

Javascript color smooth transition

I saw someone who made a color transition from a to b but they were using RGB and calculating it mathematically. I have thought about this before and I made a function that drew a linear gradient on a hidden canvas and grabs the color of each pixel. I'm not sure if this is any faster than any other method but I do know it is accurate and you don't have to do any extra math.

Here is the code:(I'm tired of typing this out and then closing and losing the window without posting it)

(function () {
        var pixel = function pixel(arr) {
        var _pixel = Object.create(null);
        _pixel.r = arr[0];
        _pixel.g = arr[1];
        _pixel.b = arr[2];
        _pixel.a = arr[3];
        _pixel.toString = function () {
            return "RGBA(" + _pixel.r + "," + _pixel.g + "," + _pixel.b + "," + _pixel.a + ")";
        };
        return _pixel;
    };

    var colors = function colors(color1, color2, steps) {
        var canvas = document.createElement('canvas'),
            c = canvas.getContext('2d');
        canvas.width = parseInt(steps, 10);
        canvas.height = 1;
        var grd = c.createLinearGradient(0, 0, canvas.width, 0);
        grd.addColorStop(0, color1);
        grd.addColorStop(1, color2);
        c.fillStyle = grd;
        c.fillRect(0, 0, canvas.width, 1);
        var imgd = c.getImageData(0, 0, canvas.width, 1);
        var pix = [].slice.call(imgd.data);
        var pixels = [];
        while (pix.length) {
            pixels.push(Object.create(pixel(pix.splice(0, 4))));
        }
        console.log(pixels);
        return pixels;
    };



    //this is just extra to display it and an example of the 
    colors("gold", "maroon", 40).forEach(function (e, i, a) {
        var s = document.createElement('span');
        s.style.border = "black 1px solid";
        s.style.display = "inline-block";;
        s.style.width = "1em";
        s.style.height = "1em";
        s.style.background = e;
        document.body.appendChild(s);
    });
})();