🦎 A jQuery plugin for extracting the dominant color from images and applying the color to their parent.

Overview

artboard

jquery.adaptive-backgrounds.js

A simple jQuery plugin to extract the dominant color of an image and apply it to the background of its parent element.

Check it out on the web!

OpenCollective Backers OpenCollective Sponsors

Getting Started

Install via bower:

bower install --save adaptive.background

Then simply include jQuery and the script in your page, and invoke it like so:

$(document).ready(function(){
  $.adaptiveBackground.run();
});

The script looks for image(s) with the data-adaptive-background attribute:

<img src="/image.jpg" data-adaptive-background>

Using an element with a CSS background image

Instead of using an <img> element nested inside of parent element, AB supports grabbing the dominant color of a background image of a standalone element, then applying the corresponding dominant color as the background color of said element.

Enable this functionality by adding a data property, data-ab-css-background to the element. See the example below:

<div style='background-image: url(/some-image.jpg)' data-adaptive-background data-ab-css-background></div>

Demo

Here's a little demo of how it works. (1) The page loads (2) the dominant background color of the image is extracted (3) said color is applied to parent of image. Demo drastically slowed down to show effect.


API

This plugin exposes one method:

  • $.adaptiveBackground.run(opts) arg: opts (Object) an optional argument to be merged in with the defaults.

Default Options

  • selector String (default: 'img[data-adaptive-background="1"]') a CSS selector which denotes which images to grab/process. Ideally, this selector would start with img, to ensure we only grab and try to process actual images.
  • parent falsy (default: null) a CSS selector which denotes which parent to apply the background color to. By default, the color is applied to the parent one level up the DOM tree.
  • normalizeTextColor boolean (default: false) option to normalize the color of the parent text if background color is too dark or too light.
  • normalizedTextColors Object Literal (default: {dark: '#000', light: '#fff'}) text colors used when background is either too dark/light.
  • shadeVariation blend|true|false (default) option to shade the color of the parent ligher or darker (see shadePercentage) or blend the color of the parent with another color by a certain percentage (see shadeColors).
  • shadePercentage float (default: 0) sets the percentage of shading or blending used. Can be adjusted from -1.00 to 1.00.
  • shadeColors Object Literal ( default: {light:'rgb(255,255,255)',dark:'rgb(0,0,0)'} ) sets the color that will be used to blend the background color with. Two values are provided to account for the background color to be light or dark to start with.
  • transparent Transparent dominant color. Can be adjusted from 0.01 to 0.99.

Example: Call the run method, passing in any options you'd like to override.

var defaults      = {
  selector:             '[data-adaptive-background="1"]',
  parent:               null,
  exclude:              [ 'rgb(0,0,0)', 'rgba(255,255,255)' ],
  shadeVariation:   false,
  shadePercentage:  0,
  shadeColors:  {
    light:      'rgb(255,255,255)',
    dark:       'rgb(0,0,0)' 
  },
  normalizeTextColor:   false,
  normalizedTextColors:  {
    light:      "#fff",
    dark:       "#000"
  },
  lumaClasses:  {
    light:      "ab-light",
    dark:       "ab-dark"
  },
  transparent: null
};
$.adaptiveBackground.run(defaults)

Events Emitted

  • ab-color-found Event This event is fired when the dominant color of the image is found. The payload includes the dominant color as well as the color palette contained in the image.

Example: Bind to the ab-color-found event like so:

$('img.my-image').on('ab-color-found', function(ev,payload){
  console.log(payload.color);   // The dominant color in the image.
  console.log(payload.palette); // The color palette found in the image.
  console.log(ev);   // The jQuery.Event object
});

Success Callback

You may wish to supply a callback function which is called once the magic has been performed.

$.adaptiveBackground.run({
  success: function($img, data) {
    console.log('Success!', $img, data);
  }
});

Note, this callback is called once for each image.

Caveats

This plugin utlizes the <canvas> element and the ImageData object, and due to cross-site security limitations, the script will fail if one tries to extract the colors from an image not hosted on the current domain, unless the image allows for Cross Origin Resource Sharing.

Enabling CORS on S3

To enable CORS for images hosted on S3 buckets, follow the Amazon guide here; adding the following to the bucket's CORS configuration:

<CORSRule>
 <AllowedOrigin>*</AllowedOrigin>
 <AllowedMethod>GET</AllowedMethod>
</CORSRule>

For all images, you can optionally also include a cross-origin attribute in your image. This is not absolutely necessary since the anonymous origin is set in the Javascript code, but kudos to you for being a super-developer.

<img src="/image.jpg" data-adaptive-background cross-origin="anonymous"/>

Credit

This plugin is built on top of a script called RGBaster.

Collaborators

Brian Gonzalez Scott Stern Alfred J Kwack
Brian Gonzalez Scott Stern Alfred J Kwack

This project exists thanks to all the people who contribute. [Contribute].

Backers

Thank you to all our backers! 🙏 [Become a backer]

Sponsors

Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor]

License

MIT, yo.

Comments
  • Add support for Picture element

    Add support for Picture element

    Added support for Picture element for this brilliant plugin.

    NOTE: your element is required to have at least 1 <img> (it is the only valid markup for this element but still)

    opened by IgorUsoltsev 9
  • Applying to another div other than the parent?

    Applying to another div other than the parent?

    This plug in works great. Spectacular work. Is there a quick and easy way to apply the adaptive color pulled from the image to another div other than the parent?

    opened by jeffcorey 8
  • Issue with black and white images

    Issue with black and white images

    Hi,

    When I have a black and white image, I get this error : Cannot read property '0' of null.

    It comes from the fact that RGBaster return an empty "rgb()" when the pixels are black or white.

    Is there a fix to still get a black or white background applied to the parent container ?

    You can try it with these two images :

    blackbgimage whitebgimage

    opened by winstef 7
  • Change parents text color according background contrast

    Change parents text color according background contrast

    I had problem with subscribing to ab-color-found so i patched plugin for my needs.

    When we change color of background, color of text do not always match background, dark text on dark background and vice versa, so it would be great if this plugin have native support for this.

    Seems to me that this is common problem with changing background, i would like to hear other thoughts on this.

    Cheers, Aleksandar

    opened by rastasheep 7
  • Not processing remote image

    Not processing remote image

    I'am trying to user adaptive-backgrounds with remote images, but i got "Not processing remote image: http://xxx".

    It's the same for 'demos/remote-image.html' example.

    Is it possible to make this with remote images?

    opened by rastasheep 7
  • Return wrong dominant color in chrome, firefox but alright in safari

    Return wrong dominant color in chrome, firefox but alright in safari

    Hi,

    I was testing some artist image with your plugin, but I found out that some of my picture is picking the incorrect dominant color. This only occur on chrome and firefox. But safari seem to doing pretty nice.

    Attached 2 images for your comparison. safari chrome

    opened by mokku86 6
  • remote-image demo not working

    remote-image demo not working

    Hi! I'm trying to get the remote-image.html demo to work but it never does. I've tried on Firefox and Chrome.

    Is it possible to use your plugin with remote images?

    Thank you! Great work!

    opened by s6joui 6
  • Demo website crashes Chrome on iPad

    Demo website crashes Chrome on iPad

    I just tried to access your demo website with Chrome on iPad and it keeps on crashing even before it is fully loaded.

    Otherwise it is an awesome script.

    opened by puikinsh 6
  • If dominant color is the transparent color, returns

    If dominant color is the transparent color, returns "rgb()" and throws error

    For the below image of a square outline over a transparent background, the returned dominant color is "rgb()", and while attempting to parse the RGB values, the library throws this error: Uncaught TypeError: Cannot read property '0' of null.

    image

    opened by darrylyeo 5
  • Update Readme.MD for shade variations features

    Update Readme.MD for shade variations features

    Now that we've merged #41 (Shade Variations by @DigitalKrony) we'll want to update the readme.

    Default options section would be the logical place to insert a new bullet or somesutch.

    The coded default options that would need to be added to the readme are:

    shadeVariation:         false,
    shadePercentage:        0,
    shadeColors:            {
      light:      'rgb(255,255,255)',
      dark:       'rgb(0,0,0)' 
    }
    

    The readme edit could look something like this:

    • shadeVariation blend|true|false (default) option to shade the color of the parent ligher or darker (see shadePercentage) or blend the color of the parent with another color by a certain percentage (see shadeColors).
    • shadePercentage integer (default: 0) sets the percentage of shading or blending used. Can be adjusted from -100 to 100.
    • shadeColors Object Literal ( default: {light:'rgb(255,255,255)',dark:'rgb(0,0,0)'} ) sets the color that will be used to blend the background color with. Two values are provided to account for the background color to be light or dark to start with.

    @briangonzalez and @DigitalKrony any thoughts or edits on this?

    opened by AlfredJKwack 4
  • Add class to parent selector (dark/light)

    Add class to parent selector (dark/light)

    Firstly, lovely plugin – thanks for sharing :+1:

    Secondly, I'm wondering if it's possible to check whether the main colour detected is either dark or light, and then apply a class name (dark or light) to the parent selector?

    Any thoughts/ideas? Or am I best looking elsewhere?

    opened by richgcook 4
  • About updating release with master branch files

    About updating release with master branch files

    Preamble: This issue is not a bug report or a technical query, but rather a generic question to the maintainers and contributors of this repository. I hope it will be in accord your contributing guidelines nevertheless.

    While testing this script, I spent some time trying to configure the shade settings before finally realizing that it couldn't work as is. Indeed, I had downloaded the last available release (13 June 2015) while this feature has been developed subsequently (20 July 2017).

    I wonder why no maintainer has created a new release in order to incorporate these significant new features (added in the README after the version 1.0.3). And if no new release is planned (for whatever reason), I think it might be convenient to indicate in the README file that it is better to download files from the current master branch to use certain features.

    opened by gizmecano 0
  • Image with wrong Dominant Colors

    Image with wrong Dominant Colors

    I if use this example image: http://cdn.laprensa.com.ni/wp-content/uploads/2015/09/270915espElChipotephoto05.jpg

    Got as dominant color,

    rgb(255,255,253)

    I want specifically detect if the dominant color is white, and this image does not. Yet I am getting this image as a valid one when is not?

    I used the base-single.html from demo folder. How this can be solved?

    opened by hugorojasppm 1
  • Dist folder in v1.0.3

    Dist folder in v1.0.3

    Hi The version 1.0.3 has no dist folder As was asked here https://github.com/cdnjs/cdnjs/pull/12023#issuecomment-340676829, can you build you lib and add to version in order to provide better hosting on cdnjs? Thanks

    opened by sashberd 1
  • Performance with Background Images

    Performance with Background Images

    The current version has some serious performance issues.

    I created a jsfiddle to demonstrate the problem:

    https://jsfiddle.net/honsa/e7wjvmLb/3/

    After page load the whole page is blocked for more than 3sec.

    Here is the developer tools performance report:

    https://chromedevtools.github.io/timeline-viewer/?loadTimelineFromURL=https://gist.github.com/honsa/e9ae7b7b008f7ad5a2739061fa0e3a46/raw/0b93e524582e9d206f90f2ffe12dd04828e2b6c6/gistfile1.txt

    Profile-20170901T175757.zip

    adaptive

    opened by honsa 2
  • Respect 'opts.parent' when using 'data-ab-css-background'

    Respect 'opts.parent' when using 'data-ab-css-background'

    The current implementation will ignore opts.parent option when using the data-ab-css-background feature. This behaviour is as per design and explicitly stated as such in the documentation.

    The proposed enhancement would:

    1. respect opts.parent if it has been set and the parent exists.
    2. set the background colour of the element with a CSS background image only when a) no 'parent' is set or b) if no parent was found.

    The implementation would affect the code around lines #L117-L130

    Anyone want to chime in on the merits and rulesets?

    enhancement 
    opened by AlfredJKwack 0
  • Getting Organized

    Getting Organized

    In order to keep this project on the up and up, we'll need to implement a little process and organization.

    Technical

    • [ ] Continuous integration with Circle / Travis
    • [ ] Publish npm / bower
    • [ ] Increment to version 2.0.0 and then adopt semver
    • [ ] Create non-jQuery version *
    • [ ] Badges (npm/travis)

    Code

    • [ ] eslint (AirBnB)
    • [ ] Build pipeline w/ gulp
    • [ ] .nvmrc

    Process

    • [ ] Block builds using GH status API for code review
    • [ ] Block builds using GH status API for unit tests

    Issues / PRs

    • [ ] Label all issues w/ { Bug, Code Review, Feature, etc. }
    • [ ] Setup ReviewNinja or LGTM
    • [ ] Close old / unrelated issues
    • Nice to have.
    enhancement 
    opened by briangonzalez 0
Releases(1.0.3)
Owner
Brian Gonzalez
Web craftsman and constant tinkerer. Ideas win, people don't.
Brian Gonzalez
small/cute/fun projects that don't need their own repo

experiments Hi! This repository is where I'm going to put short fun things I made that are probably never going to be touched again. cursed-k8s-x86 A

Nikhil Jha 20 Jun 15, 2022
A subtle tilt effect for images. The idea is to move and rotate semi-transparent copies with the same background image in order to create a subtle motion or depth effect.

Image Tilt Effect A subtle tilt effect for images. The idea is to move and rotate semi-transparent copies with the same background image in order to c

Codrops 571 Nov 21, 2022
Animated haze distortion effect for images and text, with WebGL.

Animated Heat Distortion Effects with WebGL A tutorial on how to use fragment shaders in WebGL to create an animated heat haze distortion effect on im

Lucas Bebber 289 Nov 1, 2022
Animated images that are superficially attractive and entertaining but intellectually undemanding. Cool as all hell though!

MMM-EyeCandy Animated images that are superficially attractive and entertaining but intellectually undemanding. Add some EyeCandy to your mirror. Some

Mykle 36 Dec 28, 2022
Javascript library to draw and animate images on hover

Hover effect Javascript library to draw and animate images on hover. If this project help you, you like this library or you just want to thank me, you

Robin Delaporte 1.5k Dec 23, 2022
A motion hover effect for a background grid of images.

Image Grid Motion Effect A motion hover effect for a background grid of images. Article on Codrops Demo Installation Install dependencies: npm install

Codrops 118 Dec 31, 2022
A set of effects for mouse-following image trails that show a random series of images.

Image Trail Effects A set of effects for mouse-following image trails that show a random series of images. Inspired by the effect seen on VLNC Studio.

Codrops 177 Dec 28, 2022
Javascript library enabling magnifying glass effect on an images

Magnifier.js Javascript library enabling magnifying glass effect on an images. Demo and documentation Features: Zoom in / out functionality using mous

Mark Rolich 808 Dec 18, 2022
A set of playful dragging effects for images using various techniques.

Image Dragging Effects A set of playful effects for dragging images. Article on Codrops Demo Installation Install dependencies: npm install Compile t

Codrops 71 Dec 4, 2022
Add a retro/vintage effect to images using the HTML5 canvas element

vintageJS Add a retro/vintage effect to images using the HTML5 canvas element. Installation $ npm install vintagejs How to use vintagejs is a functio

Robert Fleischmann 829 Dec 25, 2022
A tutorial on how to create a thumbnail grid with an expanding image preview similar to the effect seen on Google Images.

Thumbnail Grid with Expanding Preview A tutorial on how to create a thumbnail grid with an expanding image preview similar to the effect seen on Googl

Codrops 353 Jan 4, 2023
Some shape morphing hover effects on images using SVG clipPath.

Organic Shape Animations with SVG clipPath Some shape morphing hover effects using SVG clipPath on an image. Article on Codrops Demo Credits Anime.js

Codrops 197 Oct 16, 2022
imagesLoaded - JavaScript is all like "You images done yet or what?"

imagesLoaded JavaScript is all like "You images done yet or what?" imagesloaded.desandro.com Detect when images have been loaded.

David DeSandro 8.8k Dec 29, 2022
Warp drive is a lightweight jQuery plugin that helps you create a cool, interactive, configurable, HTML5 canvas based warp drive/starfield effect.

Warp drive jQuery plugin (jquery-warpdrive-plugin) Preview Description Warp drive is a lightweight jQuery plugin that helps you create a cool, interac

Niklas 51 Nov 15, 2022
Simple jQuery plugin for 3d Hover effect

jQuery Hover3d jQuery Hover3d is a simple hover script for creating 3d hover effect. It was my experiment on exploring CSS3 3d transform back in 2015

Rian Ariona 333 Jan 4, 2023
Create a beautiful 3D tilted effect on scroll with jQuery Tilted Page Scroll plugin

#Tilted Page Scroll by Pete R. Create a beautilful 3D tilted scrolling effect for your website with jQuery Tilted Page Scroll. Created by Pete R., Fou

Pete R. 321 Sep 18, 2022
fakeLoader.js is a lightweight jQuery plugin that helps you create an animated spinner with a fullscreen loading mask to simulate the page preloading effect.

What is fakeLoader.js fakeLoader.js is a lightweight jQuery plugin that helps you create an animated spinner with a fullscreen loading mask to simulat

João Pereira 721 Dec 6, 2022
Lightweight, simple to use jQuery plugin to animate SVG paths

jQuery DrawSVG This plugin uses the jQuery built-in animation engine to transition the stroke on every <path> inside the selected <svg> element, using

Leonardo Santos 762 Dec 20, 2022
A simple yet powerful native javascript plugin for a cool typewriter effect.

TypewriterJS v2 NPM Repository JSFiddle Example Emoji Example CDN You can use the CDN version of this plugin for fast and easy setup. <script src="htt

Tameem Safi 1.8k Jan 4, 2023