Create a vibrant PNG image background that changes dynamically based on the dominant color of the

Is it possible to dynamically set the background color of a PNG image, either white or black, based on the dominant color in the image?

For example, this image should have a dark background:

https://i.stack.imgur.com/cerjn.png

And this one should have a white background:

https://i.stack.imgur.com/f5D9Z.png

Answer №1

I compiled all the pixel data, excluding colors with an alpha value of 0, into a histogram and selected the most popular color. This chosen color was then inverted and applied as the background for the image wrapper.

To work around the CORS policy restrictions affecting ctx.getImageData, I needed to convert the Imgur image URLs to Base64 in order to manipulate the canvas data. It's worth noting that selecting the most popular color may not always yield optimal results, as some colors are very close and only differ by a few bits. Using methods like average calculation or thresholding might be more effective for grouping similar colors in the histogram.

Note: While my approach is straightforward, there are specialized libraries such as Vibrant.js and Color Thief that are specifically designed to extract color palette information from images.

const ctx = document.querySelector('#hidden-canvas').getContext('2d');

// Helper functions for converting and inverting Hex values
const toHex = (...components) =>
  `#${components.map(v => v.toString(16).padStart(2, '0')).join('')}`;

const invertHex = (hex) => {
  if (hex.startsWith('#')) hex = hex.slice(1);
  const
    r = (255 - parseInt(hex.slice(0, 2), 16)).toString(16),
    g = (255 - parseInt(hex.slice(2, 4), 16)).toString(16),
    b = (255 - parseInt(hex.slice(4, 6), 16)).toString(16);
  return toHex(r, g, b);
}
// Function to extract pixels from an image
const extractPixels = (img, ignoreAlpha = true) => {
...
body {
  background: #222;
}

.dynamic-image-background {
  padding: 1em;
}

#hidden-canvas {
  display: none;
}
<script src="https://cdn.rawgit.com/jariz/vibrant.js/master/dist/Vibrant.js"></script>
<div class="dynamic-image-background">
...
</canvas>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to simulate a KeyboardEvent (DOM_VK_UP) that the browser will process as if it were actually pressed by the user?

Take a look at this code snippet inspired by this solution. <head> <meta charset="UTF-8"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> </head> <body> <script> $(this). ...

Reacting to the surprise of TS/JS async function behaving differently than anticipated

It appears that I'm facing a challenge with the small method; not sure if my brain is refusing to cooperate or what's going on. async fetchContacts() { await this.http.get('http://localhost:3000/contacts') .subscribe(res =& ...

I keep getting redirected to a blank page by JS

I've created a JavaScript script that smoothly fades in the page when a user enters it and fades out when they click a link to another page. The script is working as intended, but I'm facing an issue with anchor links on the page. Whenever I clic ...

NextJS rendering props in a loop

I need help figuring out how to render props in a loop using the forEach function. This is my current code: {console.log('the catalog inside the component ----->', catalog)} {Object.keys(catalog).forEach(key => { return ( <d ...

What is the best way for Protractor to effectively wait for a popover to be displayed and verify that it does not contain an empty string?

Whenever you hover over it, this appears - my popup: This is what the html looks like before we add the popover to the DOM: <span tariff-popover="popover.car2go.airport" class="ng-isolate-scope"> <span ng-transclude=""> ...

"Interactive jQuery feature allows users to edit table content live with the ability to update and delete data via

I am working on implementing live editing, updating, and deleting functionality in a table using jQuery. However, I have encountered two problems: When clicking the pen icon from order #3 to #1, it requires 3 clicks, but when clicking from order #1 to ...

Can we improve the coding of this as it seems inefficient and uses up too much room?

Do you think there is a more efficient way to write this code? It seems quite impractical and takes up a lot of space. Essentially, it's about the random chance of obtaining a rarity, like acquiring an Uncommon sword. if (Math.random() * 100 < 100 ...

Change the css code to override the color of the background material

Hey there, I'm facing an issue with overriding the background color of a material element. I've tried several methods but can't seem to get it to change. After inspecting the element on the web browser, I found the CSS code that controls th ...

What is the best way to incorporate sound into a button using HTML or CSS for maximum impact?

Can anyone help me with a school project? I need to make a button play a sound when clicked. I've tried using both the <button> and <audio> tags, but they don't seem to be working for me. Perhaps CSS could be a solution. So far, the o ...

Guide on utilizing JavaScript to modify the attribute of a chosen web element with Selenium WebDriver in Java

I am seeking a way to utilize Javascript in order to set attributes for the selected element on a webpage. After some research, I have discovered two methods for achieving this with Javascript: Method 1 WebDriver driver; // Assigned elsewhere Jav ...

What could be the reason my script fails to execute during an AJAX refresh?

As I was working on my project's avatar uploader, everything seemed to be going smoothly until this morning when chaos ensued. It was a moment of pure sadness. Initially, selecting a file would prompt the crop tool to appear immediately, and it worke ...

The props are not being pushed as expected when using this.$router.push

I am currently in the process of navigating from one webpage to another and attempting to pass along properties to the new page component. Take a look at how I have set up my router.push below: this.$router.push({ name: 'settings', params: { ...

Panel that collapses and increments its ID each time within my loop

I have a Collapsible Panel with this header, <div id="CollapsiblePanel1" class="CollapsiblePanel"> <div class="CollapsiblePanelTab" tabindex="0">Comments</div> <div class="CollapsiblePanelContent"> Content &l ...

I am able to successfully receive accurate data in JSON format, however I am facing difficulties binding it to a jquery

I am struggling with integrating data fetched in JSON format using $.ajax into a table using jquery's datatable. Below is the JavaScript code I have been trying: $(document).ready(function () { $.ajax({ type: "POST", url: "Result.aspx/getUser ...

Encountering the "Next Router not mounted" error while attempting to retrieve the locale variable from the path

In order to access the locale and locales properties from use router, I am importing them from next/router. However, an issue arises when using next/router. Interestingly, the problem disappears when I switch the import to next/navigation. Unfortunately, ...

Using javascript to quickly change the background to a transparent color

I am in the process of designing a header for my website and I would like to make the background transparent automatically when the page loads using JavaScript. So far, I have attempted several methods but none seem to be working as desired. The CSS styles ...

Images for navigating forward and backward in a jQuery datepicker

I'm experimenting with setting custom images for the previous and next month buttons. I attempted to utilize the prevText / nextText options of the datepicker in order to include a span with my own CSS class definition. However, this resulted in the c ...

Attempting to generate a nested array structure in order to produce a JSON object for output

I am currently working on a JavaScript script that interacts with the Netsuite ERP platform to retrieve data. Currently, the script is returning data in an array format, specifically product information. While this is functional, I would prefer it to retu ...

Search for "conditions" in a basic HTML DOM parser

I encountered an issue when trying to parse information from a website using simple HTML DOM parser. My code looks something like this: <li> <p class="x"></p><p>..</p> <p>..</p> <p>..</p> <p class ...

"Troubleshooting: Node.js encountering a path error while loading a JSON file with

I am organizing a collection of folders and files structured like this: viz |_ app.js // node application |_ public |_ css |_ bubblemap.css |_ images |_ nuts |_ nuts0.json |_ script ...