1
0
mirror of https://github.com/thangisme/notes.git synced 2024-06-11 19:01:00 +00:00
notes/node_modules/onecolor/lib/plugins/toAlpha.js
Patrick Marsceill b7b0d0d7bf
Initial commit
2017-03-09 13:16:08 -05:00

47 lines
1.5 KiB
JavaScript

// Adapted from http://gimp.sourcearchive.com/documentation/2.6.6-1ubuntu1/color-to-alpha_8c-source.html
// toAlpha returns a color where the values of the argument have been converted to alpha
module.exports = function toAlpha(color) {
color.installMethod('toAlpha', function (color) {
var me = this.rgb(),
other = color(color).rgb(),
epsilon = 1e-10,
a = new color.RGB(0, 0, 0, me._alpha),
channels = ['_red', '_green', '_blue'];
channels.forEach(function (channel) {
if (me[channel] < epsilon) {
a[channel] = me[channel];
} else if (me[channel] > other[channel]) {
a[channel] = (me[channel] - other[channel]) / (1 - other[channel]);
} else if (me[channel] > other[channel]) {
a[channel] = (other[channel] - me[channel]) / other[channel];
} else {
a[channel] = 0;
}
});
if (a._red > a._green) {
if (a._red > a._blue) {
me._alpha = a._red;
} else {
me._alpha = a._blue;
}
} else if (a._green > a._blue) {
me._alpha = a._green;
} else {
me._alpha = a._blue;
}
if (me._alpha < epsilon) {
return me;
}
channels.forEach(function (channel) {
me[channel] = (me[channel] - other[channel]) / me._alpha + other[channel];
});
me._alpha *= a._alpha;
return me;
});
};