简体   繁体   English

如何使用 javascript 根据背景图像更改字体颜色?

[英]How to change font color based on background image with javascript?

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).所以,我有这个js function,如果你移动鼠标,它会改变背景颜色,因此也会改变文本(在片段中将指针移动到背景下)。 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?有没有办法将 function 应用于我的个人 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.抱歉解释不佳,我在这里比较新,试图学习如何练习这个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 class="background">Background example</div>

Explanation解释


Here is an example showing how to get the average using a canvas rendered to a 1x1-px scale.下面是一个示例,展示了如何使用 canvas 以 1x1 像素的比例获取平均值。 From there we set the header background and then apply a light or dark class based on the luminance of the aforementioned average.从那里我们设置 header 背景,然后根据上述平均值的亮度应用浅色或深色 class。

Notes笔记


Note 1: There is some extra code to allow for easier visualization, this is commented and can be removed.注意 1:有一些额外的代码可以更容易地可视化,这是注释并且可以删除。

Note 2: The below code is not guaranteed to run on all browsers.注意 2:以下代码不保证在所有浏览器上运行。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM