How to Compare Colors in JavaScript

How can I compare two color values in jQuery/JavaScript?

What about...

if ($('#element').css('color') == 'rgb(0, 0, 0)')
{
// do something
}

Replace 0, 0, 0 with the red, green and blue values of the colour value you want to compare.

.css() jQuery API

Comparing RGB colors in JavaScript

Ok so I set up an example here and it looks like the problem is that your initial set of colours don't have spaces between the commas:

var colors = [
"rgb(255,0,0)",
"rgb(255,255,0)",
"rgb(0,255,0)",
"rgb(0,255,255)",
"rgb(0,0,255)",
"rgb(255,0,255)"
];

clickedColor has no spaces and the pickedColor does, so changing this to:

var colors = [
"rgb(255, 0, 0)",
"rgb(255, 255, 0)",
"rgb(0, 255, 0)",
"rgb(0, 255, 255)",
"rgb(0, 0, 255)",
"rgb(255, 0, 255)"
];

Should do the trick.

Can I compare two RGB colors in Javascript? And how?

You can use getComputedStyle() to get the list of possible css properties and then look for the value of fill style to match with the expected rgb() value.

let elem = document.querySelector('span');let style = getComputedStyle(elem);if (style.fill === 'rgb(255, 255, 255)') {  console.log('matched!');}
.circle {  fill: rgb(255,255,255);}
<span class="circle">Circle</span>

Is there a way to compare 2 colors in JS, like 'If Color A is darker than #202020'

You could write a function that converts between RGB and HSL or HSV, and use the lightness or brightness value.

Wikipedia has the math for HSV -> RGB conversion, but not the other way.

http://en.wikipedia.org/wiki/HSL_and_HSV#Converting_to_RGB

You could also probably pull some JS from this page.

http://www.csgnetwork.com/csgcolorsel4.html

How to compare an object's color property | Three.js

You can compare colors using a pattern like so:

var color = new THREE.Color( 0xff0000 ); // create once and reuse if needed

console.log( material.color.equals( color ); );

three.js .r85

Color difference/similarity% between two values with JS

Just compute an Euclidean distance:

var c1 = [0, 0, 0],    c2 = [30, 30, 30],    c3 = [90, 0, 0],    distance = function(v1, v2){        var i,            d = 0;
for (i = 0; i < v1.length; i++) { d += (v1[i] - v2[i])*(v1[i] - v2[i]); } return Math.sqrt(d); };
console.log( distance(c1, c2), distance(c1, c3), distance(c2, c3) );//will give you 51.96152422706632 90 73.48469228349535


Related Topics



Leave a reply



Submit