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

Implement a dispatcher in raw JavaScript using React combined with the Redux Toolkit package

In my React app, I have been using Redux and Redux Toolkit within React components by utilizing the useDispatch and useSelector hooks. However, I now need to update the Redux store from a pure JavaScript module that interacts with IndexedDB to save user da ...

What happens when a browser can support multiple versions of a font - which one does it choose

If I have two versions of a font, customFont1.woff2 and customFont1.woff, and I list the woff2 version first followed by the woff version in the font declaration file, what happens when the browser supports both formats? Will it download both fonts or ju ...

Can you tell me the standard CSS easing curves?

When working with css, we have the option to incorporate easing for transitions, like this: transition: all .5s ease-in-out CSS provides predefined easings such as ease, ease-in, ease-out, and ease-in-out. We can also create a customized easing using a ...

Tips for handling arguments in functional components within React applications

Is it possible to pass arguments to a function in a functional component without creating the function directly in JSX? I've heard that creating functions in JSX is not recommended, so what's a better way to achieve this? function MyComponent(pr ...

Maintain GoogleMaps map object across different views in AngularJS

I have made the decision to utilize the AngularUI Map plugin for displaying Google Maps within a specific view. Here is how the template is structured: <div id="map"> <div ui-map="map" ui-options="mapOptions" id="map-canvas" ui-event="{&apo ...

Floating elements are misaligned and not laying out correctly

I've encountered an issue where the footer div is appearing behind the right-hand side div. I have a central container div with two floated divs next to each other, and the footer is separate. I've spent hours trying to fix it but can't figu ...

Dealing with a section that won't stay in place but the rest of the webpage is

I recently came across the angular-split library while trying to address a specific need. It partially solved my problem, but I still have some remaining challenges. In my setup, I have divided my content into 2 sections using angular-split. The goal is f ...

VueJS component fails to properly sanitize the readme file, as discovered by Marked

Could someone explain why the output from the compiledMarkdown function is not sanitized, resulting in unstyled content from the markdown file? <template> <div style="padding:35px;"> <div v-html="compiledMarkdown" ...

What is the optimal approach for managing server-side data stored as a JavaScript variable?

When dealing with global variables like JSON inserted into a web page server side with PHP, the best way to handle it is up for debate. Options might include leaving it for garbage collection, omitting var initialization and deleting the variable, or simpl ...

Extract information from a JSON string stored in a variable and transform it into objects within the $scope.variable

I currently have a string variable that contains JSON data displayed below. var jsonstring = [{"latitude":"51.5263","longitude":"-0.120285","altitude":"","device":"123","rating":"5","region":"Europe","customer":"","time":"1-2 Weeks","error":"Error 1","app ...

Setting up the foundation for a Bootstrap footer: A step-by-step guide

I've been struggling to implement the HTML5 structure within Bootstrap 4 grid system to match the design shown in the attached images. The layout should resemble the top image when viewed on a phone, phablet, or tablet in portrait mode, and the bottom ...

Set iframe scroll to match the height of the user's screen resolution

Can the height of an iframe scroll be adjusted to match the size of the screen (browser)? Essentially replacing the default browser scroll with the iframe scroll. Here's what I'm looking to achieve: Currently, my browser scroll is disabled: < ...

Retrieving online content and updating it upon reestablishing internet connection

Currently, I am in the process of developing an app that will feature a substantial amount of web content. My plan is to use Phone Gap build for its release; however, I intend to host all the content online and link to it from within the app. I have been c ...

JavaScript - Issue arises when evaluating the sine of complex numbers of large magnitudes

I have developed a unique sine calculator that can handle the evaluation of the sine of complex numbers by utilizing polar coordinates and computing part of the infinite series defining the sine function. The calculator performs smoothly when dealing wit ...

Jasmine and Karma encountered a TypeError stating that the function this.role.toLowerCase is not valid

Currently, I am in the process of writing a test case for a page within an application that our team is actively developing. However, I have encountered a challenging error within one of the test cases that I am struggling to overcome. Below is my Spec fil ...

Tips for looping through a JSON object?

Similar Question: How to extract a specific value from a nested JSON data structure? I am looking to loop through a two-dimensional JSON object, whereas I already know how to do so for a one-dimensional JSON object. for (var key in data) { alert(data ...

Get rid of all the formatting on an HTML button or submit

Is there a method to entirely eliminate the styling of a button in Internet Explorer? I am utilizing a CSS sprite for my button and everything appears fine. However, when I click on the button, it shifts slightly upwards which distorts its appearance. Are ...

The passing of query string parameters from JavaScript to a PHP processing script is ineffective

I am looking to dynamically populate a jQWidgets listbox control on my webpage with data retrieved from a MySQL database table once the page has finished loading and rendering. PARTIAL SOLUTION: You can find a solution here. NEW PROBLEM: I have created a ...

Basic event listener function, functional in CodePen but not operating in Chrome web browser

I'm experiencing an issue where event listener functions are not working on my browser (Chrome), but they work fine on CodePen. I've been troubleshooting this for about 2 hours, and I'm seeking some insights. Can anyone help? CodePen Link: ...

Is it possible for Javascript, AJAX, or JQuery to determine if a form has been manually inputted into

My goal is to change the contents of a form field and submit the form through the console. However, when I use either jQuery or JavaScript to modify the field and submit it, the page only recognizes values that were manually typed in. In the code snippet ...