Coder Social home page Coder Social logo

kennethcachia / background-check Goto Github PK

View Code? Open in Web Editor NEW
3.3K 3.3K 283.0 2.28 MB

Automatically switch to a darker or a lighter version of an element depending on the brightness of images behind it.

Home Page: http://kennethcachia.com/background-check/

License: MIT License

JavaScript 86.73% CSS 13.27%

background-check's People

Contributors

kennethcachia avatar smilledge 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

background-check's Issues

Change only part of the element color

Nice library!

I've dragged the text element onto the black light on the middle picture.

screen shot 2013-09-23 at 11 23 51

It would be very nice if the text could then become white on the part which is above the light, and black on the white background.

cross-origin errors

Background-check fails not-so-gracefully if image elements don't share the same origin domain.

Modifying line 43:

attrs.images        = getElements(a.images || 'img', true);

to:

attrs.images        = getElements(a.images || 'img[src^="'+window.location.protocol+'//'+window.location.hostname+'"]', true);

prevents this issue when no image selector is provided, but it's still possible for a user to provide a selector that includes cross origin images.

Callback functions

Some callback functions would help a lot.
For example a callback function after all the classes have been added to targets, in order to immediately start doing something else based on what classes were added.

Thanks!

Checking Text on Background onscroll - Viewport Problem

Hello,
if I scroll and the text leaves the viewport, the class on some images changes from "background--dark" to "background--light". If the text is completely in the viewport, everything is fine, but if it leaves (complete or not), the backgroundcheck doesn't seem to work right.

I took a look at your plugin, and on line 78 I saw, that you run "check()" everytime you scroll.

window.addEventListener(resizeEvent, throttle.bind(null, function () {
     resizeCanvas();
     check();
}));

window.addEventListener('scroll', throttle.bind(null, check)); //<-- THIS LINE

resizeCanvas();
check();

I fixed this for me, by deleting the line 78 and creating a directive, which does the same (checks by scrolling), but adds a class "gotFontColor" to the element, which just appeared in the viewport when I scrolled and runs "BackgroundCheck.refresh();". If I scroll back to the element, I ask if the element got the class "gotFontColor", and if so, I just do nothing, so the class doesn't change after I just got one.

Cannot explain this proper, so here the code:

CheckoutApp.directive('checkViewport', function() {
    'use strict';
    // checks if specified element is in Viewport
    function isInViewport(element) {
        var rect = element.getBoundingClientRect();
        var html = document.documentElement;
        return (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= (window.innerHeight || html.clientHeight) &&
        rect.right <= (window.innerWidth || html.clientWidth)
        );
    }
    function check(element) {
        // is Element in Viewport
        if(isInViewport(element)) {
            // if element has not class "gotFontColor"
            if(!element.classList.contains('gotFontColor')) {
                // give element class "gotFontColor"
                element.classList.add('gotFontColor');
                // run BackgroundCheck.refresh()
                BackgroundCheck.refresh();
            }
        }
    }
    return {
        restrict: 'A',
        link: function(scope, element, attrs) {
            // Listens to scroll
            window.addEventListener('scroll', function() {
                // run check()
                check(element[0]);
            });
        }
    };
});

I would like to ask if it is possible to add something like this to your code, so the script doesn't check the same elements every time I scroll. Would be perfect, so I could use your code without removing it from the "bower_components". Better to use "official code" than my own "hacked version", if you know what I mean?

Failed to execute 'getImageData' on 'CanvasRenderingContext2D': the canvas has been tainted by cross-origin data

http://dragonbound.net/#server-6

When I try to change the ground map to put another console (in one game HTML5) give me error "Failed to execute 'getImageData' on 'CanvasRenderingContext2D': the canvas has been tainted by cross-origin data"

JS Code of the Game is on: http://dragonbound.net/static/js/repomdgs.js?4

Fragment of the JS Code Game from appears error... :

function CGround(a) {
var b = MapNumberToObject(a),
a = this.canvas = document.getElementById("ground_canvas"),
d = b.w,
c = b.h;
this.w = a.width = d;
this.h = a.height = c;
$("#ground_canvas").css({
width : d,
height : c
});
var e = DragonDecompress(b.ground),
f = a.getContext("2d");
this.imageData = f.createImageData(d, c);
BooleanArrayToImageData(e, this.imageData);
f.putImageData(this.imageData, 0, 0);
var j = new Image,
k = this;
j.onload = function () {
var a = ImageDataToBooleanArray(k.imageData);
f.drawImage(j, 0, 0, Math.max(b.w, j.width), Math.max(b.h,
j.height));
k.imageData = f.getImageData(0, 0, d, c);
BooleanArrayToImageData(a, k.imageData, !b.disable_shadow);
f.putImageData(k.imageData, 0, 0)
};
j.src = -1 == b.fg.indexOf("/") ? "/static/images/maps/" + b.fg + ".jpg" : b.fg;
a = b.bg;
-1 == a.indexOf("/") && (a = "/static/images/maps/" + a + ".jpg");
this.bg = a;
this.bgcolor = b.bgcolor;
this.SetMapBackground();
$("#gameScreen").css("background-color", b.bgcolor)
}

MAP Default of ground : http://dragonbound.net/static/images/maps/ground_forest.jpg
MAP of ground that I want: http://dieguinkey.0catch.com/db/maps/adium.png

Please Help me, thank you very much :)

Color detection on mousemove()

Hi Kenneth!

I´m planning to implement your great plugin into a new project. And I was thinking about to trigger the color detection to the mouse move event in order to use it for a slideshow.

What do you think? Would the plugin manage correctly all the process for the mouse event? It could be similar to handle it with the scroll one in performance terms, more or less, right?

Just let me know, please :)

In any case, this plugin is really fantastic, I really love it. I use it for everything now, for my sites, for opening the fridge, when my wife tells me something I don´t want to hear... for everything! XD

Thx!

Can't get it to work with IE9

For the life of me, I can't get it to work with Internet Explorer 9.

I get this message:

SCRIPT5007: Unable to get property 'remove' of undefined or null reference 
background-check.min.js, line 5 character 4834

Am I doing it wrong?

The code I use looks something like this:

BackgroundCheck.init({
      targets: ".bg-check-target",
      images: ".bg-check-img",
      windowEvents: false
});

Coloring in combination with Owl Carousel behaves odd

Somehow the colors backgroundcheck applies to my owl carousel buttons don't behave comprehensible (the color code is light=green, dark=red, complex=blue). But it turns out a little bit different: https://dl.dropboxusercontent.com/u/8578/bkgrdcheckCOLORS.mov

My relevant settings are:

The HTML snippet

<div id="about-imp" class="owl-carousel">
    <div><img src="img/1.jpg" alt="1"></div>
    <div><img src="img/2.jpg" alt="2"></div>
    <div><img src="img/3.jpg" alt="3"></div>
    <div><img src="img/4.jpg" alt="4"></div>
    <div><img src="img/5.jpg" alt="5"></div>
    <div><img src="img/6.jpg" alt="6"></div>
</div>

...the JS snippet:

$(document).ready(function() {
    $("#about-imp").owlCarousel({
        navigation:true,
        slideSpeed:300,
        paginationSpeed: 400,
        singleItem:true,
        afterInit: function(){
            BackgroundCheck.init({
              targets: '.owl-buttons div',
              images: '.owl-carousel img'
          });
        },
        afterMove: function() {
            BackgroundCheck.refresh();
        }
    });
});

…and the relevant CSS part about the buttons is:

.owl-theme .owl-controls .owl-buttons div {
  /*color: #FFF;*/
  display: inline-block;
  zoom: 1;
  margin: 5px;
  padding: 3px 10px;
  font-size: 12px;
  -webkit-border-radius: 30px;
  -moz-border-radius: 30px;
  border-radius: 30px;
  /*background: #869791;*/
  opacity: 0.5; }

.owl-prev {
  position: absolute;
  bottom: 50%;
  left: 1em; }

.owl-next {
  position: absolute;
  bottom: 50%;
  right: 1em; }

.owl-buttons div.background--light {
  background-color: green; }

.owl-buttons div.background--dark {
  background-color: red; }

.owl-buttons div.background--complex {
  background-color: blue; }

I've also checked the two selectors from the js backgroundcheck init: target and images. Both target the right elements:

bildschirmfoto 2014-02-24 um 01 32 52
bildschirmfoto 2014-02-24 um 01 33 05

Therefor I am a bit confused where to look for the error cuz on the code side everything looks basically correct in my eyes.

The sample project I've linked in my other issue is still online. But I could upload the one with three new images and the updated css I've pasted above if necessary.

Thanks in advance Ralf

Specify targets to refresh

Hi,

I've tried supplying both a string and a jQuery object to the refresh method, but it just throws "... is not a target".

I have three flexslider sliders on my page, and I'm needing to find a way to specify each slider individually so that clicking on a nav anchor which calls refresh doesn't apply it's classes to the wrong slider, which is what's happening.

Uncaught Elements not found

Getting an error: Uncaught Elements not found when trying to initialize.

BackgroundCheck.init({
  targets: '.title'
});

Even though .title exists.

Tutorial for designers?

Hi :) Your BackgroundCheck script is amazing,thank you!

I'm currently trying to use it in a project where I have breadcrumbs sitting over an image, but I can't for the life of me get it working. Could you please provide a html example page with the init command and css for this kind of scenario for myself and my fellow Javascript newbs :) (I do apologise - it's just that like many designers I love the solution but I'm like a fish out of water with JavaScript).

If it helps here is the html I'm using, and I've also attached a screenshot.

    <img src="img/placeholder.jpg" alt="" />
    <ul class="breadcrumbs">
      <li><a href="index.html">Home</a></li>
      <li><a href="committee.html">Committee</a></li>
      <li class="current"><a href="code-of-conduct.html">Code of Conduct</a></li>
    </ul>

screenshot

Many thanks!
Harmony

Multiple Instances

Is there anyway that we can run multiple instances of BackgroundCheck on the same page?

I tried assigning BackgroundCheck to different variables but to no avail.

'Unknown property'

Hi!

I´m using Background-Check in a project where I have some "targets" within a slider. These elements are working pretty well when I slide between images, I use the set method and refresh each time. I´m not sure if this is the best way, but it seems to work.

In other part I have 2 elements more that are over the images of the same slider (in other pages they can be single images, even videos). These elements are fixed and the images are displaced on scroll, so these elements need to listen the scroll event managed by the plugin. The most part of the time they work pretty well, but in some part of the scroll action the plugin returns this "Unknown property" and breaks/kills the plugin.

Do you know the reason of this? Did you experienced something similar in this sense?

The scroll listening is a very cool feature, but do you know if it affects the a general site performance?

Hope you can help with these details. I know this plugins does not make magics, but it is near!

Thanks a lot!

Broken on Android Firefix

I am testing the Background Check on Android and on the stock Internet App and Firefox the plugin doesn't add the background--light and background--dark classes.

I will do some more testing and add anything I find.

Doesn't work with AJAX ?

Hey there,
I use the magic BackgroundCheck plugin for a website where I use a full AJAX navigation. When I go to a photo page (fullscreen image), I do a BackgroundCheck.refresh();, but absolutely nothing happend. My "target" (body) has no "dark" of "light" class.
It just works at the first page load only if I am in a photo page but not with AJAX.

My function :

bgcheck: function(el, cond){
    if ($(el).hasClass(cond)){
        BackgroundCheck.init({
            targets: "body",
            images: "#thephoto",
            threshold: 50,
            classes: {
                dark: "dark",
                light: "light"
            }
        });
    }
}

What I run when the page is ready :

plugins.bgcheck("body", "single-photos");

What I do when AJAX is loaded (after the fadeIn effect on the container and the body class load) :

// Re-check background brightness
if (isType("photo/")){
    BackgroundCheck.refresh(); // Doesn't work
}

If you have an idea or something to help… Is it a bug ? or me doing something wrong ?
Thank you in advance.

———
Edit :

After a debug:true, I have this information :
"Skipping image - http://website.com/wp-content/uploads/DSC_9639-1500x996.jpg - area too small"
(it seems to be the old image and the not new one)

Flip the control?

Would it be possible to use this as a way to change the background depending on what the image sitting on top of it is?

The use case here is that we have an app at https://brandfolder.com/brandfolder and it would be nice if this could detect if the logo uploaded was lighter to show a dark background.

FlexSlider

Has anyone was able to make it work with FlexSlider 2?

TypeError: d.replace is not a function

Hi,

thanks for this great Script! Unfortunately I have a problem to use it on a Wordpress Page. I'm getting the following Error in the Console:

Chrome: Uncaught TypeError: undefined is not a function
FF: TypeError: d.replace is not a function
...new RegExp("(?:^|\s)"+b+"(?!\S)","g");d=d.replace(e,"")}a.className=d.trim()}f...

Thanks for your help.

Solid color

Would be nice if the plugin could work against solid colours too. That could be useful specially on sliders when sometimes you just a solid colour instead an image.

background-check.min.js doesn't work for me

Hi Kennethcachia,

Thanks for sharing such an amazing script.

I want to use this script in our project, but it doesn't work. Even when I downloaded your example, it doesn't work either. The only working one seems like your demo. Could you please check the uploaded script and your example? and I follow this tutorial you wrote down exactly, it doesn't work. See the link below(tutorial for designers):

#24

Thanks in advance for answering my question!

Inline Style

Hi I tested your plugin and is very awesome, otherwise the plugin don't work with background-image inline-style.

It is possible, to add support for this feature?

CDN Support

Is there anyway we can run images from a CDN without getting the cross origin error?

Can't get it to work locally

Hey Kenneth, thank you for making this great script work with background images as well. I have an issue with making it work locally though. I get this warning in Chrome (Version 30.0.1599.69)

screen shot 2013-10-06 at 10 29 08

Have any ideas how to fix this? I'm a newb when it comes to JS, but really love this script and would like to use it on all of my future projects. Thanks!

Canvas support

Support for canvas would be awesome. Might work on a pull request over the weekend if i get time.

Images from different domain

Is there a way to patch JS so it would be able to work with images which is served from different domain? The page im working on serves images from CDN with dedicated domain name and JS produces these errors.

Unable to get image data from canvas because the canvas has been tainted by cross-origin data. background-check.min.js:5
Uncaught SecurityError: An attempt was made to break through the security policy of the user agent.

Im able to add Access-Control-Allow-Origin to images served but dont know how to patch JS for it to post Origin header.

Feature: dominant colour.

In addition to processing for light or dark. You should surface the three most common color and set them as data properties. Such that you could pick complimentary colours the image, like they do in iTunes.

BackgroundCheck.refresh() refreshing but not updating class

I'm using this plugin with the jQuery Revolution slider and am having problems getting the refresh to work correctly on new slides. It seems that it is refreshing, but it's not adding the correct background class. Here's the code I have:

document.addEventListener('DOMContentLoaded', function() {
  var img = document.querySelector('.tp-bgimg');
  img.setAttribute('crossorigin', '');
  img.src = img.getAttribute('src');

  // Prepare BackgroundCheck
  BackgroundCheck.init({
    targets: '#navigation ul li a',
    images: img
  });

  revapi1.bind("revolution.slide.onchange", function(e) {
    BackgroundCheck.refresh();
  });
});

Any idea why it's not working correctly? Seems it's only finding the first slide. When I view the developer tool in Chrome it shows it's not affecting the other slides, so it's only refreshing for the first slide. Could that be because RevSlider adds that code through JS instead of HTML?

Checking background on an image that is not visible in the window

Hi guys

Awesome plugin you have here. I'm using it to check the background image of a slider I have and I change the color of the overlaying caption in relation to the image.

I'm having a weird issue though. When I scroll down (scroll past the slider), then background check has a problem checking the actual background the slider image. Seems like it's checking the background of whatever is visible in the image and not in the slideshow. Any guess on what this could all be about?

Uncaught TypeError: Cannot read property 'getBoundingClientRect' of null

I have been getting this javascript error. I addition to background check plugin, I also have a backstrech pluging for full background with slides.

   $.backstretch(homeGalleryImgs, {
        fade: 'slow',
        duration:5000
    });
    BackgroundCheck.init({
        threshold:30,
        targets: '.home-title',
        images: '.backstretch >img'
    })

EDIT: FIXED! I put the BackgroundCheck.init() inside the event of backstrech.after. And then backgroundCheck.refresh() after that. It works now.

  $(window).on("backstretch.after", function (e, instance, index) {
        BackgroundCheck.init({
            targets: '.home-title',
            images: '.backstretch >img'
        })
        BackgroundCheck.refresh();
    });

Demo drag and drop not working in Chrome

Just an FYI, the drag & drop functionality of the main demo doesn't seem to be working on Chrome ( Windows 8.1 ).

Chrome Version 33.0.1750.117 m

Other than that, great script!

Publish to npm registry

Since you have a package.json, you should probably publish your package to the registry, so browserify users can npm install your package and use it properly.

You should add a repository field (pointing to your github repo) and main field (pointing to the minified version of your script) in package.json.

Support for SVG Graphics

Would be great to add support for svg graphics, so the script is also looking at "image-tags".

<image xlink:href="path/to/img" src="path/to/fallback/img"></image>

wordpress conflict?

Hi,
This script is awesome!

I am trying to use it just the same as your fixed-nav example but keep getting a conflict in Wordpress. I can't seem to pinpoint it but even tried to use a default template with no active plugins. I copied and pasted your code directly in the theme. Have you seen any issues specifically with WP? Thanks!

Slider count problem

Hi!

I´m having a problem with a slider and background-check. I´m using background check for a main navigation that is placed over a slider.

The plugin works really great adding the handler classes to manage the styles for each case/image/slide. But for some reason it stops working after the 5th slide. It looks like that the plugin has some difficulties after this slide. Is there some limitation in this sense?

I have tried to modify the threshold, maxDuration & minComplexity props. in case some of them could be the problem, but they are not. The same images that don´t fire the classes after the 5th slide are working perfectly when I set them at first place within the slider.

The slider in use is Royal Slider and I´m using the BackgroundCheck.refresh(); method after each slide is loaded. As I say, it is working perfectly, but after the fifth slide the plugin stops firing the classes.

Hope you can send some light about this! Really, this is a very nice plugin!!

Thank you very much for your attention,
Beat.

Check for multiple selectors with 'images' attribute

The default option for 'images' is for any img tag on the page. If I want to check against a background image, I need to set 'images' to the class of the elements that have a background image (or any images with that class).

Is there a way to tell BackgroundCheck to check against all img tags AND a certain class for background images?

One solution is to attribute a class for both img tags and elements with background images I want to check, but It would be better (cleaner) to use multiple selectors.

Uncaught Unknown property - windowEvents

Hi,
thank you for the great plugin. I just wanted to mention that it is not possible to set windowEvents to false without having countless JS errors. I have been trying to deactivate your plugins resize and scroll detection because I do not need it. Maybe I am doing something wrong?

Support for AngularJS

Hi,
I'm attempting to use your plugin within an Angular application. It seems that no matter what I try, I am unable to instantiate your plugin without first wrapping it with an Angular $timeout (without the $timeout, I receive this error: Elements not found <ul ob-background-check="" class="ob-nav e2e-ob-nav ng-scope">).

I am instantiating your plugin inside a directive using the "link" method. This should mean that the DOM is ready. However, I still must use a $timeout to avoid the error above.

Any suggestions?

Thank you.

The script breaks if it fails working with an element

I've got the following message:

Uncaught Element is not an but does not have a background-image

That doesn't necessarily had to make the script break, because there were other elements on the page with that class for background-check to check.

Owl Carousel combined with Background-Check: BackgroundCheck isn't initialised.

Hi i've already read the issue about Flexslider and the hassle to get sliders working with Flexslider. Therefor i tried to follow the rough direction you've taken for Flexslider to give things a try with Owl Carousel (http://owlgraphic.com/owlcarousel/) as well. I think i've adhered more or less every step but in the end the console shows on "jQuery().BackgroundCheck" an "undefined" in return. i've used the following jQuery lines before:

$(document).ready(function() {
    $("#about-imp").owlCarousel({
        navigation:true,
        slideSpeed:300,
        paginationSpeed: 400,
        singleItem:true,
        afterInit: function(){
            BackgroundCheck.init({
              targets: '.owl-buttons div',
              images: '.owl-carousel img'
          });
        },
        afterUpdate: function() {
            BackgroundCheck.refresh();
        }
    });
});

AfterInit seems the only viable callback but no luck. So i wonder is the problem on the Owl Carousel side, or the BackgroundCheck side or is it just my configuration? I've thrown together a stripped down test case, but i've used codekit for concatenation ( https://dl.dropboxusercontent.com/u/8578/bkgrdCheck.zip ). Best regards Ralf

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.