简体   繁体   English

根据图像主色更改背景颜色?

[英]Change color of background based on image main color?

I don't know if this is actually possible but it would be nice if it is.我不知道这是否真的可能,但如果是的话就太好了。 Taaking inspiration from the new iTunes where the background color seems to be set via the (major) color of the artwork image, I'm looking to do something similar with javascript/cs maybe using jQuery. essentially changing the background-color of a div based on an image inside it.从新的 iTunes 中汲取灵感,其中背景颜色似乎是通过艺术品图像的(主要)颜色设置的,我正在寻找与 javascript/cs 类似的东西,可能使用 jQuery。本质上改变了 div 的背景颜色基于其中的图像。

Here's what you could try out: 以下是您可以尝试的内容:

https://github.com/lokesh/color-thief https://github.com/lokesh/color-thief

This library has a pretty cool demo: http://lokeshdhakar.com/projects/color-thief/ 这个库有一个非常酷的演示: http//lokeshdhakar.com/projects/color-thief/

Found here: Get average color of image via Javascript 在此处找到: 通过Javascript获取图像的平均颜色

Hi i managed today to do that, i was working a week on it to find the solution, So heres my code explained, hope it can help u:嗨,我今天设法做到了,我花了一个星期的时间来寻找解决方案,所以这是我的代码解释,希望它能帮助你:

 function getLogoColor() { // Get all the logo images var logos = document.querySelectorAll('.company-logo--image'); // Loop through the logo images for (var i = 0; i < logos.length; i++) { var canvas = document.createElement("canvas"); var context = canvas.getContext("2d"); var img = new Image(); img.src = logos[i].src; canvas.width = img.width; canvas.height = img.height; context.drawImage(img, 0, 0, img.width, img.height); // Get the image data var imageData = context.getImageData(0, 0, img.width, img.height); var data = imageData.data; // Initialize variables var colorFrequency = {}; var dominantColor = ''; var maxFrequency = 0; // Loop through the image data for (var j = 0; j < data.length; j += 4) { var red = data[j]; var green = data[j + 1]; var blue = data[j + 2]; // Convert the RGB values to a hex code var color = rgbToHex(red, green, blue); // Check if the color is already in the colorFrequency object if (colorFrequency[color]) { colorFrequency[color]++; } else { colorFrequency[color] = 1; } } // Get the dominant color from the color frequency object for (var color in colorFrequency) { if (colorFrequency[color] > maxFrequency) { maxFrequency = colorFrequency[color]; dominantColor = color; } } // Set the --logo-color variable document.documentElement.style.setProperty('--logo-color', dominantColor); }

u need to add this html on main page u want the color to be as main color of logo and the css, u can combine it for your needs, thanks!你需要在主页上添加这个 html 你希望颜色作为徽标的主要颜色和 css,你可以根据你的需要组合它,谢谢!

 :root { --logo-color: #ed0000; }.job-overview ul li i { background: var(--logo-color); color: white; }
 <script src="path/to/single-job-classic.js"></script>

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

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