GithubHelp home page GithubHelp logo

briangonzalez / jquery.adaptive-backgrounds.js Goto Github PK

View Code? Open in Web Editor NEW
6.6K 198.0 474.0 9.2 MB

๐ŸฆŽ A jQuery plugin for extracting the dominant color from images and applying the color to their parent.

Home Page: http://briangonzalez.github.io/jquery.adaptive-backgrounds.js/

HTML 0.26% JavaScript 95.60% CSS 4.14%

jquery.adaptive-backgrounds.js's Introduction

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.

jquery.adaptive-backgrounds.js's People

Contributors

alfredjkwack avatar asood123 avatar briangonzalez avatar chellem avatar igorusoltsev avatar lucanos avatar mongey avatar mortonfox avatar mzrnsh avatar rastasheep avatar sstern6 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

jquery.adaptive-backgrounds.js's Issues

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!

CORS demo does not work in chrome

i really pulled my hairs for about 3 hrs before discovering that chrome doesn't like cors objects it just hates them . It throws cors policy error every time u try

<img src="remote-image-url" crossorigin="anonymous" />

but FF is really happy to serve it easily without any errors .

The solution to this is to load all javascripts after images. if you put any JavaScript before images chrome throws cors error .

i really don't know how to fix this

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

Demos not work

when open one of the demos I can see the images but the background keep white

Question on setting selector based on parent div class

I want to show the background image color using data-adaptive-background data-ab-css-background only when the parent div has a class .is-selected but I'm having an issue setting the selector to do this. Is this possible with this setting or is there another way to do this?

selector: '.is-selected [data-adaptive-background]',

Mobile Safari

There seems to be a problem with CORS on Mobile Safari.

The plugin is managing to execute perfectly on regular browsers but when testing on the iPad and iPhone (latest OS) the plugin fails most of the time. The images either don't load at all, other times the image loads fine but the background colors are not extracted/applied, and other instances work as expected.

I can see CORS related errors in the console for Mobile Safari. Also, when I serve those same images from the same domain (instead of my cdn subdomain) these errors don't occur and the plugin works fine.

My host has also implemented the CORS rules mentioned in the plugin's caveats.

Impressive plugin. Just wish I could get it to work on iOS and my CDN.

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?

Image returns white dominant color when unwarranted

Running the following image https://imgur.com/nVqeA6i with no change in defaults will return rgb(255,255,255) while the array of results (below) has quite a different idea in mind.

["rgb(99,137,0)", "rgb(103,140,0)", "rgb(103,140,0)", "rgb(104,141,1)", "rgb(99,137,0)", "rgb(116,146,0)", "rgb(116,146,0)", "rgb(100,138,1)", "rgb(123,149,0)", "rgb(107,141,2)", "rgb(116,146,0)", "rgb(106,140,1)", "rgb(107,141,2)", "rgb(116,146,0)", "rgb(106,140,1)", "rgb(116,146,0)", "rgb(117,157,0)", "rgb(123,149,0)", "rgb(106,140,1)", "rgb(123,148,2)"]

I'm sure I'm missing something here.

Parent element custom issue

I have a problem, because my img inside the multi-layer div, I want the outer div to change the color, I look at the API method, where it is to change the value of the parent, but I do not know what? (I tried $ (". Test"), found no use), someone can help me?

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.

Add class to parent selector (dark/light)

Firstly, lovely plugin โ€“ thanks for sharing ๐Ÿ‘

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?

lumaclasses

could you include a sample on how to use lumaclasses

not really an issue, but had to post this somewhere.

Use second dominent colour, when dominent colour is excluded

I was expecting this to behave as the title described. Is it intentional that it doesn't?

For example, currently, if you have a red circle in a white square, with white being the dominant colour. You exclude white, then your background is set to black. If you also exclude black, your background is set to rgb(). I think it would make more sense if the background was set to red, once white has been excluded.

Edit: I'm guessing this is a bug, because I've noticed that when adding a 2px (red) border to the image I described above, it behaves as I originally expected.

use harmonious colours instead of dominant colour

Using the dominant colour is a bad idea because it will often be difficult to identify the bounds of the image. Instead, I recommend using colours that are harmonious with the image's dominant colour. Analogous colours are probably the best choice.

Does not work with srcset

If you attempt to use this with srcset only it will spit out an error because technically there is no image src. Right now I'm providing a very low resolution version of the image in the src attribute but this means an image is downloaded twice.

Typo in docs

Under "Events Emitted" example, pallette should read payload.pallette - correct?

I love this plugin - I often find myself doing this work on the server, this should effectively eliminate that work now!

Minimum image size?

Hi,
I want to use a 300x118 image and it causes an error:
TypeError: rgb is null
return ((rgb[0]_299)+(rgb[1]_587)+(rgb[2]*114))/1000;
I tried with a bigger image and it works as expected. But I really need to be able to use it on this image format. Is there a limitation or is it fixable?
(I attached the 2 images I was trying it on)

300x118
300x118-2

Complementary color as background

Hello, its is not really an issue but I think it would be great to have an option to use a complementary color as the background instead of the main image color. I think it would allow more "contrast" and improve the display of images.

Call to adaptiveBackground.run is causing page to load (GET) a not found resource

Hi, I just noticed that if I disable the following:

     $.adaptiveBackground.run();

It stops giving me an error related to a resource being queried against the localhost. In other words, there is an HTTP get being issued. This seems not to be entirely related to the adaptiveBackground. It seems that the adaptive's run is kicking something which is making my app to make that call โ€” I wonder if you have an idea or if you can add a bit on what adaptiveBackground.run does.

use rgba instead of rgb

Hello, is there any way to use rgba instead of rgb? maybe with defaults config? because alpha matters sometimes.

Thanks

exclude:

Hi I can't seem to add to the default 'exclude:' options.
var defaults = {
exclude: [ 'rgb(0,0,0)', 'rgb(255,255,255)', 'rgb(255, 255, 253)', 'rgb(247, 247, 247)' ]
};
$.adaptiveBackground.run(defaults);

Am I missing something?

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?

ab-color-found function not working in Opera / Safari

Testing with the below code:

var opts = {
    selector: '#top_image_wrap img',
    parent:   '#top_image_wrap',
    normalizeTextColor: true
}
jQuery.adaptiveBackground.run(opts)

jQuery('#top_image_wrap img').on('ab-color-found', function(){
    jQuery('#top_image_wrap > div').fadeIn(1000);               
});

Opera and Safari browsers don't process the fadeIn effect. Same result with a simple testing alert.

Fancy Box

How easy would it be to hook this up to say fancy box lightbox

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?

Could we have an option to ignore a certain color?

This plugin looks great, and I'm thinking of using it on a site where our users upload a logo, usually surrounded by a white background. I can only imagine everyone's "adaptive background" will end up being #fff. It'd be great to be able to pass in a hex code for a color NOT to use as the background. Thoughts?

Change the data selector

I think it could work with just [data-adaptive-background] instead of data-adaptive-background="1"

Does not work in Firefox or IE

This plugin does not function in Firefox or IE.

My code:

<section id="hero" style="background-image: url('/img/cover2.jpg')" data-adaptive-background="1" data-ab-css-background="1">
...
$(document).ready(function(){
  $.adaptiveBackground.run();
});

Chrome, OS X:
screenshot 2015-06-02 14 24 38

Chrome, Win 8:
snap 2015-06-02 at 14 27 03 1011x649

Safari, OS X:
screenshot 2015-06-02 14 24 59

Opera, Win 8:
snap 2015-06-02 at 14 27 23 1302x484

Firefox, OS X:
screenshot 2015-06-02 14 24 22

Firefox, Win 8:
snap 2015-06-02 at 14 27 49 1194x592

Internet Explorer 11, Win 8:
snap 2015-06-02 at 14 26 37 1365x614

Is this line correct?

// Helper function to calculate yiq - http://en.wikipedia.org/wiki/YIQ
var getYIQ = function(color){
var rgb = data.color.match(/\d+/g); // <--- is this correct?
return ((rgb[0]_299)+(rgb[1]_587)+(rgb[2]*114))/1000;
};

Shouldn't var rgb = color.match(/\d+/g); ?? (the color arg being passed into the function), not data.color.match(/\d+/g); (the callback data object's color) ??

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.

Loading Two Images

Is there any reason that when using adaptive backgrounds, it seems to be loading two of the same image?

screen shot 2015-05-22 at 00 34 36

Any help is appreciated. Thanks in advance!

imageData varies greatly between bg image and img tag

Using the exact same image as a background image and as an img src gave me vastly different results. The css background imageData came back with tons of empty pixel data, though the image had no transparent pixels in it. I'd say roughly the last third of the Uint8ClampedArray was just repeating zeros. The img tag was much more accurate. Though it's not perfect, I managed to normalize them by having getCSSBackground() function return an img element instead of the background source.

Apply to font colour

Can this be adapted to change a font colour?
I would like the font colour to contrast the image behind.

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

FireFox backgrounds weren't working.

The backgrounds weren't working in FireFox. FF was taking the relative URL displaying it as an absolute URL with quotation marks around it, which caused the plugin to search for "https://example.com/%22https://example.com/resource/image.jpg%22" which would 404. So I added a bit to remove the double quotation marks.

    <target_div style="background-image: url(resources/image.jpg);"></div>

    var getCSSBackground = function(){
      return $this.css('background-image')
                  .replace('url(','').replace(')','').replace(' ','').replace(/\"/g,'');
    };

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.