JavaScript style.background-color - PullRequest
       12

JavaScript style.background-color

0 голосов
/ 09 декабря 2018

У меня есть вопрос по поводу моего кода, где я пытаюсь создать динамический фон с помощью веб-камеры, которая с помощью .jquery дает lightIntensity в количестве 0-255, который я хотел бы использовать дляфон, я не могу заставить его работать.

    $(document).ready(function() {
        $.fn.webcamLightSensor({ refreshInterval: 100 }, function(lightIntensity) {
            $('.container p').text(lightIntensity);
            console.log(lightIntensity)
        });
        function decimalToHex(lightIntensity) {
        var hex = Number(lightIntensity).toString(16);
        hex = "000000".substr(0, 6 - hex.length) + hex;
        return hex;
            document.body.style.backgroundColor = hex;
        }

    });

'lightIntenisty' - это число от 0 до 255, которое нужно перевести в RGB или шестнадцатеричный код (я думаю).

Код использует библиотеку jQuery:

  1. jquery-1.9.1.js
  2. jquery.image-bright.js
  3. jquery.webcam-light-sensor.js

<script src="https://github.com/ErwynIzaaekJoziasse/js/blob/master/jquery.webcam-light-sensor.js"></script>
<script src="https://github.com/ErwynIzaaekJoziasse/js/blob/master/jquery.image-brightness.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Light -> colour</title>

	<script src="js/jquery-1.9.1.js" ></script>
	<script src="js/jquery.image-brightness.js" ></script>
	<script src="js/jquery.webcam-light-sensor.js" ></script>
</head>
<body>
	<div>
		<div class="container">
			<!-- in between the <p> the 'amount' of light is displayed (0/255) -->
			<p></p>
		</div>
	</div>
	<script>
		$(document).ready(function() {
			$.fn.webcamLightSensor({ refreshInterval: 100 }, function(lightIntensity) {
				$('.container p').text(lightIntensity);
				console.log(lightIntensity)
			});
			function decimalToHex(lightIntensity) {
    		var hex = Number(lightIntensity).toString(16);
    		hex = "000000".substr(0, 6 - hex.length) + hex;
    		document.body.style.backgroundColor = '#' + hex;
    		return hex;
				}
		});
	</script>
</body>
</html>

Ответы [ 3 ]

0 голосов
/ 09 декабря 2018

Я бы взял код из https://jqueryui.com/slider/#colorpicker

function hexFromRGB(r, g, b) {
  var hex = [
    r.toString( 16 ),
    g.toString( 16 ),
    b.toString( 16 )
  ];
  $.each( hex, function( nr, val ) {
    if ( val.length === 1 ) {
      hex[ nr ] = "0" + val;
    }
  });
  return hex.join( "" ).toUpperCase();
}

Это, конечно, требует красного, зеленого и синего значений.Вы получаете только 1 значение от 0 до 255. Так что не знаете, как получить из этого «цвет».

В вашем примере кода также нет ничего, что бы вызывало это.Я бы настроил обратный вызов, а затем назначил шестнадцатеричное значение на основе этого события.

 $.fn.webcamLightSensor({ refreshInterval: 100 }, function(lightIntensity) {
   $('.container p').text(lightIntensity);
   console.log(lightIntensity);
   $("body").css("background", "#" + hexFromRGB(lightIntensity, lightIntensity, lightIntensity));
 });

Надеюсь, это поможет.

0 голосов
/ 09 декабря 2018

с 1 значением, вы не получите насыщенный цвет, но попробуйте это

function decimalToHex(i) {
  var hex = i.toString(16);
  hex = hex.length == 1 ? "0" + hex : hex;
  result = '#' + hex.repeat(3);
  document.body.style.backgroundColor = result;
  return result;
}

var num = 0;

$('button').on('click', function() {
  if (num > 255) return
  result = decimalToHex(num);
  console.clear()
  console.log(num, result)
  num = num + 20;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

<button>
Change background
</button>
0 голосов
/ 09 декабря 2018

Вы возвращаетесь до установки backgroundColor, поэтому она никогда не достигает.

function newColor() {
  decimalToHex(Math.floor((Math.random() * 16777215) + 1));
}

function decimalToHex(lightIntensity) {
    var hex = Number(lightIntensity).toString(16);
    hex = "000000".substr(0, 6 - hex.length) + hex;
    document.body.style.backgroundColor = '#' + hex;
    console.log(hex);
    return hex;
}
html, body {
width: 100%;
height: 100%;
}
<button onclick="newColor()">Change</button>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...