Home > front end >  How to change font color based on background image with javascript?
How to change font color based on background image with javascript?

Time:07-26

I want to change the font color based on the color of the image. The font color must be black or white, but it should change proportionally to the color of the image as it does in the code below.

So, I have this js function that if you move the mouse it changes the background color and consequently also the text (in the snippet move the pointer under the background). Obviously the part where you move the mouse to change color doesn't interest me, it's just a test. Is there a way to apply the function to my personal div?

In simple terms I want the color of the text to change based on my background and not if you move the mouse. Sorry for the poor explanation, I'm relatively new here, trying to learn how to exercise this function. Currently I don't know how to do it, I appreciate any answer, thanks.

function getTextColor(rgba){
  rgba = rgba.match(/\d /g);
  if((rgba[0]*0.299) (rgba[1]*0.587) (rgba[2]*0.114)>186) {
    return 'black';
  } else {
    return 'white';
  }
}

var div = document.createElement('div');
div.style.height = '100vh';
document.body.appendChild(div);

div.addEventListener('mousemove', (event)=>{
  var x = event.clientX;
  var y = event.clientY;
  div.textContent = `${x} , ${y}`;
  div.style.backgroundColor = `rgba(${x},${y},100,100)`;
  div.style.color = getTextColor(div.style.backgroundColor);
});
.background {
  height: 100vh;
  background: url("https://i.pinimg.com/originals/bc/a3/2d/bca32d5cdfabeaeb4faeb12bff160524.jpg");
}
<div >Background example</div>

CodePudding user response:

Explanation


Here is an example showing how to get the average using a canvas rendered to a 1x1-px scale. From there we set the header background and then apply a light or dark class based on the luminance of the aforementioned average.

Notes


Note 1: There is some extra code to allow for easier visualization, this is commented and can be removed.

Note 2: The below code is not guaranteed to run on all browsers. Please see this thread for more specifics.

Example

/* 
     
     THE TOGGLE ACTION
     
     */

/* The urls for toggling between */
const urlLight = 'https://images.unsplash.com/photo-1484503793037-5c9644d6a80a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=930&q=80';
const urlDark = 'https://images.unsplash.com/photo-1517999144091-3d9dca6d1e43?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=627&q=80';
let currentUrl = urlLight;

const toggle = document.getElementById('toggle');

toggle.addEventListener("click", function() {
  if (currentUrl === urlLight) {
    currentUrl = urlDark;
  } else {
    currentUrl = urlLight;
  }

  getImageBrightness(currentUrl, function(brightness) {

    const header = document.getElementById("header");
    header.style.backgroundImage = `url(${currentUrl}`;

    header.classList.remove("dark");
    header.classList.remove("light");

    console.log(brightness);

    if (brightness > 225 / 2) {
      header.classList.toggle("dark");

    } else {
      header.classList.toggle("light");
    }
  });

});

/* 

Important get brightness code

*/

function getImageBrightness(imageSrc, callback) {
  var img = document.createElement("img");
  img.src = imageSrc;
  img.style.display = "none";
  img.crossOrigin = "anonymous";
  document.body.appendChild(img);

  var colorSum = 0;

  img.onload = function() {
    // create canvas
    var canvas = document.createElement("canvas");
    canvas.width = this.width;
    canvas.height = this.height;

    var ctx = canvas.getContext("2d");
    ctx.drawImage(this, 0, 0);

    var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
    var data = imageData.data;
    var r, g, b, avg;

    for (var x = 0, len = data.length; x < len; x  = 4) {
      r = data[x];
      g = data[x   1];
      b = data[x   2];

      avg = Math.floor((r   g   b) / 3);
      colorSum  = avg;
    }

    var brightness = Math.floor(colorSum / (this.width * this.height));
    callback(brightness);
  }
}



getImageBrightness(currentUrl, function(brightness) {

  const header = document.getElementById("header");
  header.style.backgroundImage = `url(${currentUrl}`;

  header.classList.remove("dark");
  header.classList.remove("light");


  if (brightness > 225 / 2) {
    header.classList.toggle("dark");

  } else {
    header.classList.toggle("light");
  }
});
.dark {
  color: black;
}

.light {
  color: white;
}

* {
  text-align: center;
}

#header {
  padding: 2rem 0;
  font-size: 4rem;
  background-size: cover;
  margin-bottom: 1rem;
  background-position: center center;
}
<div id="header">
  Header
</div>

<button id='toggle'>
Toggle Background
</button>

  • Related