I want to create a form where the user clicks on the desired color and the script generates a random shade of that color.

I generate the rgb color using random . But I can't figure out how to make a color shade that is generated, and not a random color.

 $(function() { $('#color').change(function() { var min = 0, max = 255; var rgbColor = 'rgb('+(Math.floor(Math.random() * (max - min)) + min)+','+(Math.floor(Math.random() * (max - min)) + min)+','+(Math.floor(Math.random() * (max - min)) + min)+')'; $('#shade').val(rgbColor).css('border-color', rgbColor); }); }); 
 #shade {border: 2px solid #000;} 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <p>Выберите цвет: <select id="color"> <option style="display: none;">Выбрать цвет...</option> <option value="red">Красный</option> <option value="green">Зелёный</option> <option value="yellow">Жёлтый</option> <option value="blue">Синий</option> <option value="grey">Серый</option> </select> </p> <p> Оттенок: <input type="text" id="shade"> </p> 

How to make a shade?

    3 answers 3

    It is necessary to record the code of all shades necessary

     $(function() { $('#color').change(function() { var self = this, // Создаём список цветов colorsModels = { 'red': {'r': '50-255', 'g': '0', 'b': '0'}, 'green': {'r': '0', 'g': '50-255', 'b': '0'}, 'yellow': {'r': '50-255', 'g': 'r', 'b': '0'}, 'blue': {'r': '0', 'g': '0', 'b': '50-255'}, 'grey': {'r': '50-200', 'g': 'r', 'b': 'r'} }; // Проверяем, существует ли цвет указанный в списке if( colorsModels[self.value] !== undefined ){ // Передаём массив цвета в переменную и создаём rgb var model = colorsModels[self.value], rgb = {r: null, g: null, b: null}; // Перебираем каждый цвет из массива for(var key in model){ if( /\d{1,3}\-\d{1,3}/.exec(model[key]) ){ // Проверяем, указано ли значение диапазоном // Вычисляем минимум и максимум с диапазона var min = parseFloat( model[key].replace(/(\d{1,3})\-\d{1,3}/, '$1') ), max = parseFloat( model[key].replace(/\d{1,3}\-(\d{1,3})/, '$1') ); // Вычисляем рандомное число в этом диапазоне var value = Math.floor(Math.random() * (max - min)) + min; // Применяем значение rgb[key] = value; }else if( /\d{1,3}/.exec(model[key]) ){ // Если цвет указан не диапазоном, то проверяем, цифра ли это // Преобразовываем значение в цифру var value = parseFloat( model[key] ); // Применяем значение rgb[key] = value; }else if( model[key] === 'r' || model[key] === 'g' || model[key] === 'b' ){ // Проверяем, ну казано ли значение повторяющим цветом (не равно ли значение пердыдущим цветам) // Проверяем, на допустимость повторения if( (key !== 'r' && key !== model[key]) || (model[key] === 'g' && key !== 'r') ){ // Если всё нормально, то копируем значение rgb[key] = rgb[model[key]]; }else{ console.error('Invalid!'); }; }else{ console.error('Undefined a value color!'); }; }; // Устанавливаем значение var rgbColor = 'rgb('+rgb['r']+','+rgb['g']+','+rgb['b']+')'; $('#shade').val(rgbColor).css('border-color', rgbColor); }else{ console.error('Undefined a color!'); }; }); }); 
     #shade {border: 2px solid #000;} 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <p>Выберите цвет: <select id="color"> <option style="display: none;">Выбрать цвет...</option> <option value="red">Красный</option> <option value="green">Зелёный</option> <option value="yellow">Жёлтый</option> <option value="blue">Синий</option> <option value="grey">Серый</option> </select> </p> <p> Оттенок: <input type="text" id="shade"> </p> 

      Usually, the color is transferred to the HSV color model, the color shade is changed (Hue) and transferred back to RGB. If you need to change the saturation - Saturation. If lightness - Volume.

      See also other color models - many of them are "sharpened" for different things.

        For gray, you need to throw away one random, and assign the value to all channels (r, g, b). For other colors, generate values ​​not in the full range [0, 255], but separately by channels, giving preference to one or another of them.

         function limitedRandom (min, max) { return (Math.floor(Math.random() * (max - min)) + min); } red = { r: limitedRandom(150, 255); g: limitedRandom(0, 100); b: limitedRandom(0, 100); }; yellow = { r: limitedRandom(150, 255); g: limitedRandom(150, 255); b: limitedRandom(0, 100); }; // and so on 

        Specific boundaries of color ranges can be selected according to your taste in a graphic editor.

        • Why do you have random random colors? If green is red, it will turn yellow .. - Yuri
        • If you mix in a bit, it will not, red will still dominate. Perhaps 100 is too much, you can turn it down, but randomly across all channels allows you to get exactly different shades. If you just need a pure color of different intensity, write in g and b zeros for red, b for yellow, etc. - Aleksei