简体   繁体   中英

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.

Here's what you could try out:

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

This library has a pretty cool demo: http://lokeshdhakar.com/projects/color-thief/

Found here: Get average color of image via 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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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