TinyColor icon indicating copy to clipboard operation
TinyColor copied to clipboard

Blend colors

Open Langmans opened this issue 8 years ago • 3 comments

I stumbled upon https://gist.github.com/JordanDelcros/518396da1c13f75ee057 yesterday. Maybe a nice idea to integrate it?

        tinycolor.prototype.blendWith = function (that) {
            if (!this.isValid()) {
                throw 'Invalid base color';
            }
            if (!that instanceof tinycolor || !that.isValid()) {
                throw 'Invalid blend color';
            }

            var base = [this._r, this._g, this._b, this._a];
            var added = [that._r, that._g, that._b, that._a];

            var mix = [];
            mix[3] = 1 - (1 - added[3]) * (1 - base[3]); // alpha
            mix[0] = Math.round((added[0] * added[3] / mix[3]) + (base[0] * base[3] * (1 - added[3]) / mix[3])); // red
            mix[1] = Math.round((added[1] * added[3] / mix[3]) + (base[1] * base[3] * (1 - added[3]) / mix[3])); // green
            mix[2] = Math.round((added[2] * added[3] / mix[3]) + (base[2] * base[3] * (1 - added[3]) / mix[3])); // blue

            return tinycolor.fromRatio({r: mix[0], g: mix[1], b: mix[2], a: mix[3]});
        }

Langmans avatar Apr 28 '17 07:04 Langmans

Just have added examples here and here

hinell avatar Oct 24 '17 19:10 hinell

@rubenvincenten How would you mix it a certain amount? Can you update it to have the signature someColor.blendWith(other, amount) where amount is a number between 0 and 100?

trusktr avatar Aug 15 '19 20:08 trusktr

Ah, here we go:

function(color1, color2, amount) {
    amount = (amount === 0) ? 0 : (amount || 50);

    var rgb1 = tinycolor(color1).toRgb();
    var rgb2 = tinycolor(color2).toRgb();

    var p = amount / 100;

    var rgba = {
        r: ((rgb2.r - rgb1.r) * p) + rgb1.r,
        g: ((rgb2.g - rgb1.g) * p) + rgb1.g,
        b: ((rgb2.b - rgb1.b) * p) + rgb1.b,
        a: ((rgb2.a - rgb1.a) * p) + rgb1.a
    };

    return tinycolor(rgba);
}

And it is also available not just as static helper, but as prototype property on @ctrl/tinycolor, a forked and updated tinycolor.

trusktr avatar Aug 15 '19 20:08 trusktr