• Stars
    star
    6,553
  • Rank 5,875 (Top 0.2 %)
  • Language
    JavaScript
  • Created over 10 years ago
  • Updated over 6 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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.

More Repositories

1

rgbaster.js

🎨 A simple library for extracting dominant colors from images.
TypeScript
1,736
star
2

jquery.pep.js

👟 Pep, a lightweight plugin for kinetic drag on mobile/desktop
JavaScript
1,297
star
3

fontprep

🔣 The missing font generator for Mac OSX.
JavaScript
1,232
star
4

jquery.arbitrary-anchor.js

⚓ Arbitrary anchors for any element on your page using a little jQuery magic.
JavaScript
370
star
5

codrops-medium-style-page-transitions

The repository for this article: http://tympanus.net/codrops/2013/10/30/medium-style-page-transition/
CSS
257
star
6

termrc

Take your iTerm2 environments with you wherever you go.
Ruby
88
star
7

cocoa-rack

Run rack apps within Mac apps.
Objective-C
87
star
8

alfred-messages

Message your Apple Contacts via Alfred using Messages
Swift
66
star
9

awesome-applescripts

A collection of awesome, useful, not-so-obvious applescripts.
AppleScript
63
star
10

craigslist-scout

A dead simple command line tool to query multiple Craigslist cities (subdomains) and email out new results.
JavaScript
19
star
11

gridss

A CSS Grid microlib.
HTML
15
star
12

calle-app

CalleApp: El ultimo SF food truck locator.
JavaScript
12
star
13

gulp-file-contents-to-json

Slurp in some files, output a JSON representation of their contents.
JavaScript
12
star
14

nesta-boilerplate

Nesta starting point with baked-in H5BP, Compass, Semantic GS, & Capistrano
JavaScript
11
star
15

border-animate.js

Effortless border-length animations.
JavaScript
11
star
16

google-drive-email-saver

google-drive-email-saver
Ruby
10
star
17

broccoli-file-contents-to-json

Given a directory of files, output a JSON representation of their contents.
JavaScript
9
star
18

inkpress

A small, lightweight, dead simple content management system built on free & open source technologies.
JavaScript
8
star
19

top

Top: OSX App to emulate iOS's scroll-to-top functionality
Objective-C
6
star
20

alfred-reminders

View, add, and complete reminders via Alfred.
JavaScript
6
star
21

briangonzalez.org

My website built atop Hexo, VueJS, and Github Pages.
CSS
6
star
22

Sirkel

Geolocation-based chat app
JavaScript
5
star
23

cleardns

Dependency-free, platform-aware, DNS-clearing library.
JavaScript
5
star
24

animicons

Animicons: Sprite Animations with Icon Fonts
4
star
25

reminders-menu-bar

Reminders in your menu bar.
JavaScript
4
star
26

alfred-cleardns

Clear your DNS via Alfred.
JavaScript
4
star
27

dotfile-cabinet

Responsibly manage your dotfiles with Dropbox.
Ruby
4
star
28

eotlitetool.py

Create EOT version of OpenType font for use with IE
Python
3
star
29

fontprep-crx

A Chrome extension for FontPrep.
JavaScript
3
star
30

auth-code-copy

Copy auth codes sent via iMessage to your clipboard.
JavaScript
3
star
31

jquery.pep.js-website

jquery.pep.js website (built on Sinatra)
JavaScript
2
star
32

compass2css

Convert Compass to CSS. On the web.
Ruby
2
star
33

poly-cms-gem

A simple way to manage your content.
Ruby
2
star
34

ember-polymorphic

Polymorphic relationship example in Ember.
JavaScript
2
star
35

grunt-starter

A simple grunt starter project.
JavaScript
2
star
36

underscore-template-fetcher

A small utility function built on top of underscore.js which provides a simple API for fetching template strings via AJAX.
JavaScript
2
star
37

sinatra-webdav-neue

A Sinatra-based webdav server powered by rack_dav.
Ruby
2
star
38

origin

a simple sinatra starter
JavaScript
2
star
39

async-await-import-export

Passing around async functions.
JavaScript
1
star
40

code-copy

A macOS for copying auth codes sent via iMessage.
TypeScript
1
star
41

stub-stub

A node module for quick and dirty API stubbing based on YAML files inside a sensible directory structure.
JavaScript
1
star
42

farkle-ai

A Sinatra interface to a Monte Carlo-based Farkle AI.
Ruby
1
star
43

ts-export-import-demo

TypeScript
1
star
44

alfred-table

Paste a random table flip to your clipboard ┬──┬ ノ( ゜-゜ノ)
JavaScript
1
star
45

blog-compile-handlebars-templates-ember-with-gulp

Compile Handlebars templates for Ember with Gulp.
JavaScript
1
star