Javascript-форум (https://javascript.ru/forum/)
-   jQuery (https://javascript.ru/forum/jquery/)
-   -   Почему возвращает значения RGB каналов? (https://javascript.ru/forum/jquery/67237-pochemu-vozvrashhaet-znacheniya-rgb-kanalov.html)

Black_Star 05.02.2017 14:11

Почему возвращает значения RGB каналов?
 
Добрый день уважаемые. Столкнулся с не пониманием почему JS возвращает значения RGB каналов хотя в CSS задаю под HSL. В целом задача состоит такая- необходимо каждые две секунды менять значения цветов у квадратов. Первый и второй блоки (столбци) квадратов должны получать +10 к hue каналу каждые две секунды ( То есть после второй секунды у классов .first_st* должны быть значения h =11 а у классов .second_st* = 21 ).
Если значения h доходят до 360 то добавляется сколько возможно а затем всё стартует с нуля. (То есть на 36 итерации у классов .first_st* должны быть значения h =1 а у классов .second_st* = 11)

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
	<style>
		.first_st1{
			fill: hsl(1, 50%, 50%);
		}
		.first_st2{
			fill: hsl(1, 70%, 40%);
		}
		.first_st3{
			fill: hsl(1, 90%, 30%);
		}

		.second_st1{
			fill: hsl(11, 50%, 50%);
		}
		.second_st2{
			fill: hsl(11, 70%, 40%);
		}
		.second_st3{
			fill: hsl(11, 90%, 30%);
		}
	</style>
</head>
<body>
	<svg width="600" height="240">
		<rect class="first_st1" width="80" height="80" x="0" y="0"></rect>
		<rect class="first_st2" width="80" height="80" x="0" y="80"></rect>
		<rect class="first_st3" width="80" height="80" x="0" y="160"></rect>

		<rect class="second_st1" width="80" height="80" x="160" y="0"></rect>
		<rect class="second_st2" width="80" height="80" x="160" y="80"></rect>
		<rect class="second_st3" width="80" height="80" x="160" y="160"></rect>
	</svg>
<script>
window.onload = function(){

	var allFirstColors = $("[class^='first_st']"),
		firstColorsLength = allFirstColors.length,

		allSecondColors = $("[class^='second_st']"),
		secondColorsLength = allFirstColors.length;

	var h,s,l;

		console.log(" st1 = " + $(".first_st1").css("fill") ); // Почему возвращает RGB каналы? 

		allFirstColors.each(function(indx, el){
				let  color = $(el).css("fill"),
				[h,s,l] = color.match(/\d+/g);
	console.log("[h,s,l] = " + [h,s,l]);
		});	

}
</script>
</body>
</html>

рони 05.02.2017 15:04

Цитата:

Сообщение от Black_Star
Почему возвращает RGB каналы?

это же замечательно, раньше каждый браузер сам решал что ему возвращать. прими как особенность.

Black_Star 05.02.2017 15:19

:cray: Я хочу то что положено стилями в css файле. Так не честно :cray:

рони 05.02.2017 15:20

Black_Star,
так правила css и фильтруй тоже самое похоже RGB, только ie сохраняет формат

Black_Star 05.02.2017 17:04

А возможно ли гнать это все дело через data тэги ? Что-то по типу такого ?
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
	<svg width="600" height="240">
		<rect class="first_st1" data-hsl="(1, 50%, 50%)" width="80" height="80" x="0" y="0"></rect>
		<rect class="first_st2" data-hsl="(1, 70%, 40%)" width="80" height="80" x="0" y="80"></rect>
		<rect class="first_st3" data-hsl="(1, 90%, 30%)" width="80" height="80" x="0" y="160"></rect>

		<rect class="second_st1" data-hsl="(11, 50%, 50%)" width="80" height="80" x="160" y="0"></rect>
		<rect class="second_st2" data-hsl="(11, 70%, 40%)" width="80" height="80" x="160" y="80"></rect>
		<rect class="second_st3" data-hsl="(11, 90%, 30%)" width="80" height="80" x="160" y="160"></rect>
	</svg>
<script>
window.onload = function(){

	var allFirstColors = $("[class^='first_st']"),
		firstColorsLength = allFirstColors.length,

		allSecondColors = $("[class^='second_st']"),
		secondColorsLength = allFirstColors.length;

	var h,s,l;

		allFirstColors.each(function(indx, el){
		
		let  color = $(el).data("hsl");

		$(el).data("hsl", h+', '+s+', '+l);

		console.log("color = " + color );

		});	
}

</script>
</body>
</html>

laimas 05.02.2017 17:08

Если так принципиально, используйте конвертор для вычислений.

destus 05.02.2017 17:45

Black_Star,
Зачем все эти танцы с атрибутами data? Начальное состояние блоков известно же, для остальных двух параметров явно прослеживается зависимость блока от индекса. Да и конверторы никакие не нужны.
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
	<style>
		.first_st1{
			fill: hsl(1, 50%, 50%);
		}
		.first_st2{
			fill: hsl(1, 70%, 40%);
		}
		.first_st3{
			fill: hsl(1, 90%, 30%);
		}

		.second_st1{
			fill: hsl(11, 50%, 50%);
		}
		.second_st2{
			fill: hsl(11, 70%, 40%);
		}
		.second_st3{
			fill: hsl(11, 90%, 30%);
		}
	</style>
</head>
<body>
	<svg width="600" height="240">
		<rect class="first_st1" width="80" height="80" x="0" y="0"></rect>
		<rect class="first_st2" width="80" height="80" x="0" y="80"></rect>
		<rect class="first_st3" width="80" height="80" x="0" y="160"></rect>

		<rect class="second_st1" width="80" height="80" x="160" y="0"></rect>
		<rect class="second_st2" width="80" height="80" x="160" y="80"></rect>
		<rect class="second_st3" width="80" height="80" x="160" y="160"></rect>
	</svg>
<script>

window.onload = function(){

	var initialH1 = 1
		initialH2 = 11,	
		allFirstColors = $("[class^='first_st']"),
		firstColorsLength = allFirstColors.length,
		allSecondColors = $("[class^='second_st']"),
		secondColorsLength = allFirstColors.length;
		
	window.setInterval(function(){

		initialH1 = initialH1 === 360 ? 1 : initialH1 + 10 < 360 ? initialH1 + 10 : 360;
		initialH2 = initialH2 === 360 ? 11 : initialH2 + 10 < 360 ? initialH2 + 10 : 360;
		
		allFirstColors.each(function(i){
			$(this).css("fill", `hsl(${initialH1}, ${50 + i * 20}%, ${50 - i * 10}%)`); 
		})
		
		allSecondColors.each(function(i){
			$(this).css("fill", `hsl(${initialH2}, ${50 + i * 20}%, ${50 - i * 10}%)`); 
		})
		
	}, 200)	
}
</script>
</body>
</html>

Black_Star 05.02.2017 18:07

Это всё замечательно, но оно работает не правильно. :)
Как бы вообще условия не соблюдаются.
1) Цветовые каналы первой колонки блоков на второй итерации должны отвечать цветовым каналам второй колонки блоков что значит:
.first_st1{fill: hsl(1, 50%, 50%); должен стать fill: hsl(11, 50%, 50%);}
.first_st2{fill: hsl(1, 70%, 40%); должен стать fill: hsl(11, 70%, 40%);}
.first_st3{ fill: hsl(1, 90%, 30%); должен стать fill: hsl(11, 90%, 30%);}
Соответственно для второй колонки блоков
.second_st1{fill: hsl(11, 50%, 50%); должен стать fill: hsl(21, 50%, 50%);}
.second_st2{fill: hsl(11, 70%, 40%); должен стать fill: hsl(21, 70%, 40%);}
.second_st3{ fill: hsl(11, 90%, 30%); должен стать fill: hsl(21, 90%, 30%);}
И так далие на каждой итерации...(когда значение h канала становиться >360 то прибавляется сколько возможно а остаток прибавляет к нулю) надеюсь так стало понятнее.
(Цифры 1 и 11 взяты для наглядности, на самом деле там в 3 квадратах совершенно разные цифры для h канала)
Ваш вариант выдает совершенно сказочные вещи если смотреть в консоль :)
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <style>
        .first_st1{
            fill: hsl(1, 50%, 50%);
        }
        .first_st2{
            fill: hsl(1, 70%, 40%);
        }
        .first_st3{
            fill: hsl(1, 90%, 30%);
        }
 
        .second_st1{
            fill: hsl(11, 50%, 50%);
        }
        .second_st2{
            fill: hsl(11, 70%, 40%);
        }
        .second_st3{
            fill: hsl(11, 90%, 30%);
        }
    </style>
</head>
<body>
    <svg width="600" height="240">
        <rect class="first_st1" width="80" height="80" x="0" y="0"></rect>
        <rect class="first_st2" width="80" height="80" x="0" y="80"></rect>
        <rect class="first_st3" width="80" height="80" x="0" y="160"></rect>
 
        <rect class="second_st1" width="80" height="80" x="160" y="0"></rect>
        <rect class="second_st2" width="80" height="80" x="160" y="80"></rect>
        <rect class="second_st3" width="80" height="80" x="160" y="160"></rect>
    </svg>
<script>
 
window.onload = function(){
 
    var initialH1 = 1
        initialH2 = 11,
        allFirstColors = $("[class^='first_st']"),
        firstColorsLength = allFirstColors.length,
        allSecondColors = $("[class^='second_st']"),
        secondColorsLength = allFirstColors.length;
         
    window.setInterval(function(){
 
        initialH1 = initialH1 === 360 ? 1 : initialH1 + 10 < 360 ? initialH1 + 10 : 360;
        initialH2 = initialH2 === 360 ? 11 : initialH2 + 20 < 360 ? initialH2 + 20 : 360;
         
        allFirstColors.each(function(i){
            $(this).css("fill", `hsl(${initialH1}, ${50 + i * 20}%, ${50 - i * 10}%)`);

            console.log( $(this).css("fill") + " = first block" )
        })
         
        allSecondColors.each(function(i){
            $(this).css("fill", `hsl(${initialH2}, ${50 + i * 20}%, ${50 - i * 10}%)`);

            console.log( $(this).css("fill") + " = second block" )

        })
         
    }, 2000)
}
</script>
</body>
</html>

destus 05.02.2017 18:20

Black_Star,
Цитата:

console.log( $(this).css("fill") + " = first block" )
Ты о чем вообще? Непонятно как ты цифры проверяешь. Ты же сам писал, что возвращается rgb, вот он тебе и вернулся. .

Смысл в том, что на каждом интвервале, ты устанавливаешь fill в формате hsl, а браузер внутри себя это приводит к rgb и отрисовывает.

Black_Star 05.02.2017 18:31

Так ведь RGB тоже должны совпадать. 1->2 2->3; 2->3 3->4.... Система то не меняется. Я наглядно вижу что первые блоки не переходят в значения вторих на следующей итерации


Часовой пояс GMT +3, время: 08:50.