enguerranws
enguerranws

Reputation: 8233

JS : from RGB Blue to RGB Red

I'm trying to convert RGB color from blue (rgba(0,0,255)) to red (rgba(255,0,0)) on JS mouseenter, progressively.

So, each time the mouse enter an element, it "increments" its background color, from blue to green and then to red.

With a WIP live demo : http://codepen.io/enguerranws/pen/ZQOBwe

Here's what I've done so far :

function onGridDone(){
  var gridders = document.querySelectorAll('.gridder');
  for(var i = 0; i < gridders.length; i++){
    gridders[i].addEventListener('mouseenter', onHover );
  }  
}
function onHover () {
  var currentColor = this.style.backgroundColor,
      currentColorArr = currentColor.replace(/[^\d,]/g, '').split(',');
      R = currentColorArr[0],
      G = currentColorArr[1],
      B = currentColorArr[2];
  console.log(R,G,B);
  if(B > 0) B = B-10;
  var indic = 255-B;
  G = indic/2;
  R = indic;

  this.style.backgroundColor = "rgb("+R+","+G+","+B+")";
}

I've tried multiple things, but basically, I want my color to go from rgba(0,0,255), then rgba(0,255,130), then rgba(255,130,0) and finally rgba(255,0,0) (so, from blue to green then green to red).

I know I could do multiple if/else statements to check each case, but I'm just wandering if there'is a more efficient way using maths ?

I'm not trying to do any animations / transitions.

Upvotes: 1

Views: 1154

Answers (1)

lex82
lex82

Reputation: 11297

To make use of a mathematical formula, it is helpful to have some numeric indicator of progress, e.g., from 0 to 255 and then calculate the colors from that.

It is not exactly what you "basically" asked for but it illustrates what I mean: Let's say the red component would increase linearly from 0 to 255 during the process. Then you could look at an existing field's red value and know immediately where you are. If you wanted to move through green, this should be close to what you want to do:

// assume r,g,b are the current values
var progress = r;
progress += 1; // of course you can increment faster
r = progress;
g = 255 - (255 * (Math.abs(progress-127)/128))
b = 255 - progress;

This way you will not pass the color rgba(255,130,0) as in your question. However, I think it might still solve your problem. r increases linearly, b decreases linearly and g first increases and then decreases after 50% of the process.

Upvotes: 2

Related Questions