I think what you are looking for is an average between each color.
Take a look here: link
function tratarInput(arr, degraus) {
arr = arr.toLowerCase();
if (arr.length == 3) {
var partes = arr.split('');
for (var i = 0; i < arr.length; i++) {
if (!~degraus.indexOf(arr[i])) {
alert('formato errado!')
return false;
}
}
arr = [partes[0], partes[0], partes[1], partes[1], partes[2], partes[2]].join('');
} else if (arr.length == 6) {} else {
alert('formato errado!')
return false;
}
return arr;
}
$('button').click(function () {
var degraus = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'];
var cor1 = $('#cor1').val().replace('#', '');
var cor2 = $('#cor2').val().replace('#', '');
cor1 = tratarInput(cor1, degraus);
cor2 = tratarInput(cor2, degraus);
// realiza a mistura
var mistura = [];
for (var i = 0; i < 6; i+=2) {
mistura[i] = Math.round((parseInt(cor1[i] + cor1[i + 1], 16) + parseInt(cor2[i] + cor2[i + 1], 16)) / 2);
mistura[i] = (0x1000000 | mistura[i]).toString(16).substring(5);
}
mistura = '#' + mistura.join('');
$('#cor_misturada').css('background-color', mistura);
$('h2 span').text(mistura);
});
This code may need some tweaking but rather explaining the steps it does:
- defines the variables. Here I've created an array for all color steps, this will be useful later. I also remove the
#
character to make it easier, but I'll re-enter it later. An advantage here is that if it does not use it fixes the same.
- I created a function to handle the input. Here the function converts all colors into 6 characters (in case the input was 3), check if there are invalid characters and if the inputs are 3 or 6 characters as expected
- then the
for
makes the mix itself. Calculates the position of that color in the array of steps and makes a mean. When you average it also rounds and uses the absolute value (to correct negative values). This value is a reference and is then used to fetch the actual value from the step array.
- Finally, before your code continues, I put the character
#
back to the value correct