Coder Social home page Coder Social logo

benhowdle89 / grade Goto Github PK

View Code? Open in Web Editor NEW
3.8K 54.0 146.0 458 KB

This JavaScript library produces complementary gradients generated from the top 2 dominant colours in supplied images.

Home Page: https://benhowdle89.github.io/grade/

JavaScript 100.00%

grade's Introduction

Grade

Demo

Check it out

Install

Download this repo and grab the grade.js file from the /docs/dist folder.

Or install from npm: npm install grade-js

Use the CDN link:

https://unpkg.com/grade-js/docs/dist/grade.js

Usage

Recommended HTML structure:

<!--the gradients will be applied to these outer divs, as background-images-->
<div class="gradient-wrap">
    <img src="./samples/finding-dory.jpg" alt="" />
</div>
<div class="gradient-wrap">
    <img src="./samples/good-dinosaur.jpg" alt="" />
</div>

If you have the grade.js in your project, you can include it with a script tag and initialise it like so:

<script src="path/to/grade.js"></script>
<script type="text/javascript">
    window.addEventListener('load', function(){
        /*
            A NodeList of all your image containers (Or a single Node).
            The library will locate an <img /> within each
            container to create the gradient from.
         */
        Grade(document.querySelectorAll('.gradient-wrap'))
    })
</script>

If you pass in a 3rd parameter and it's a function, the HTML element(s) you passed in as the 1st parameter will not be manipulated, but an array will be returned to you, for you to do as you please with, ie.

Grade(document.querySelectorAll('.gradient-wrap'), null, function(gradientData){
    // sample contents of `gradientData` can be inspected here https://jsonblob.com/57c4601ee4b0dc55a4f180f1
})

If you've installed from npm, you can use the library like so:

import Grade from 'grade-js'
// initialise as above

The module this imports will be using ES2015 syntax, so it will need to be transpiled by a build tool, like Babel, and if you are importing the module in this fashion (and using npm), I imagine you're already using a bundling tool, like Webpack or Browserify!

Running locally

If you want to run this locally, just to test it, you need to serve index.html via a webserver, not just by opening it in a browser, else the browser will throw a security error. I would recommend either live-server (requires Node.js installed on your machine) or if you have Python installed, just run python -m SimpleHTTPServer inside the project root. If you're on Windows, I believe WAMP/Apache is the best way to go.

Remote images

This plugin utilises 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.

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

License

MIT License

Copyright (c) 2016 Ben Howdle

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

grade's People

Contributors

amilajack avatar benhowdle89 avatar conghai avatar filipecovas avatar hnqlv avatar lgraubner avatar npmcdn-to-unpkg-bot avatar peterdavehello avatar requestingmark 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

grade's Issues

Request: ability to get just colors

Really like the concept, what would you think about having a method that stops before rendering out the wrapper, and just gets the 2 dominant colours in the image?

Not working in Safari

First of all very nice stuff!
But sadly it isn't working in Safari (Version 9.1.2 (10601.7.7)).
I think because you aren't passing any percentages for the gradient.
Maybe this can be solved by just setting the two colours of the gradient as data-attributes and then read them via CSS so you have less inline styles and better cross-browser implementation.

Work as a util server side.

Awesome tool!
It would be very useful if Grade could work with node as well.

Example usecase:

  • Process user profile photos in a background job and extract gradients
  • Save the gradients to a database
  • Serve gradients as placeholders until actual profile pic loads.

For some applications it could be too expensive to calculate the gradients on the client.

This is just...broken

Cannot get the darn thing to work for the life of me. Just generates an error..specifically this: "Uncaught ReferenceError: module is not defined" line 103

Working only with the saved images

I loved grade js and i worked too many times with this but one day when I was working with an API, images loaded from the link of an image provided in API, but grade js shows exception and doesn't work.

Exception looks like:

Uncaught DOMException: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
at Grade.getImageData (http://127.0.0.1:5500/cars/static/cars/js/grade.js:41:38)
at Grade.render (http://127.0.0.1:5500/cars/static/cars/js/grade.js:177:18)
at Grade.readImage (http://127.0.0.1:5500/cars/static/cars/js/grade.js:36:18)
at new Grade (http://127.0.0.1:5500/cars/static/cars/js/grade.js:28:14)
at init (http://127.0.0.1:5500/cars/static/cars/js/grade.js:187:21)
at http://127.0.0.1:5500/cars/static/cars/js/grade.js:198:16
at Array.map ()
at module.exports (http://127.0.0.1:5500/cars/static/cars/js/grade.js:197:90)
at http://127.0.0.1:5500/cars/templates/cars/try.html:49:13
getImageData @ grade.js:41
render @ grade.js:177
readImage @ grade.js:36
Grade @ grade.js:28
init @ grade.js:187
(anonymous) @ grade.js:198
module.exports @ grade.js:197
(anonymous) @ try.html:49
load (async)
(anonymous) @ try.html:48

Flash of Unstyled DIVs

Hi there

Thanks for the plugin! love the simplicity. I understand that the images load up first and that the colors are derived from the images. But is there an ideal time to look out for. Seems to take 1-2s before the DIV colors fill in. Is that the normal performance of the div? Is there a way to work with an IMGIX api to reduce this time taken for the gradient to appear? Would love to get your thoughts.

Cheers

gradientData Array Empty on different webserver

Hi.

Love you Code - got it to work on local small footprint lighttpd webserver. I use the following code to get gradient data and apply it to dom background:

<script src="grade.js"></script> <script> document.addEventListener("DOMContentLoaded", function(event) { Grade(document.querySelectorAll('.grade'), null, function(gradientData){ console.log(gradientData); var r1 = gradientData[0].gradientData[0].rgba[0]; var g1 = gradientData[0].gradientData[0].rgba[1]; var b1 = gradientData[0].gradientData[0].rgba[2]; var a1 = gradientData[0].gradientData[0].rgba[3] * 0.05; var r2 = gradientData[0].gradientData[1].rgba[0]; var g2 = gradientData[0].gradientData[1].rgba[1]; var b2 = gradientData[0].gradientData[1].rgba[2]; var a2 = gradientData[0].gradientData[1].rgba[3] * 0.05; document.body.style.background = "linear-gradient(10deg, rgba("+r1+","+g1+","+b1+","+a1+") 0%, rgba("+r2+","+g2+","+b2+","+a2+") 50%, rgba(255,255,255,1) 100%)"; document.getElementsByClassName('grade')[0].style.display = 'none'; }); }); </script>

It works great, but if I copy the exact same files (all of it - the dirs are identical) to my espasyncwebserver the code somehow returns a correctly structured, but empty array for "gradientData":

lighttpd:
[{…}]0: element: div.gradegradientData: Array(2)0: {rgba: Array(4), occurs: 1, brightness: 180.117}brightness: 180.117occurs: 1rgba: (4) ['128', '223', '96', '8']0: "128"1: "223"2: "96"3: "8"length: 4[[Prototype]]: Array(0)[[Prototype]]: Object1: {rgba: Array(4), occurs: 1, brightness: 148.502}brightness: 148.502occurs: 1rgba: (4) ['77', '179', '179', '10'][[Prototype]]: Objectlength: 2[[Prototype]]: Array(0)[[Prototype]]: Objectlength: 1[[Prototype]]: Array(0)

espasyncwebserver:
[{…}]0: element: div.gradegradientData: Array(2)0: null1: nulllength: 2[[Prototype]]: Array(0)[[Prototype]]: Objectlength: 1[[Prototype]]: Array(0)

There are no error messages in console on both servers - so it seems the code is working fine, but I cannot figure out why on one server the array returnes empty and on the other not.

Maybe it has to do with some async/slow response from espasyncwebserver, but I am too little of a java-async expert (yet) to analyse this sort of problem. Maybe somebody has an idea on how to fix this?

Any help is appreciated.

I built a website for this awesome tool

Thanks for the awesome tool!

I built a website [gradex] for this, it allows user to upload an image then update background image thanks to this tool.

Then user can download the background image or copy the html code.

Screenshots in below:
image

Hope the website helps anybody.

❤️

BR

OSX Google Chrome - SecurityError

I'am getting this error in sample (Chrome osx). I did not change anything:
"grade.js:38 Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data."

Full error object:

grade.js:38 Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.
    getImageData @ grade.js:38
    render @ grade.js:111
    readImage @ grade.js:33
    Grade @ grade.js:25
    (anonymous function) @ grade.js:121
    module.exports @ grade.js:120
    (anonymous function) @ index.html:109

Suggestion: Generate recommended text color

This looks promising! The only suggestion I have is to somehow generate/suggest text color (either black or white) based on the generated gradient.

Chances are you might want to have text under/above the image(s). If the resulting gradient is dark, you can't use dark text. If the gradient ends up being light, you can't use light text.

But it might be hard to know (especially if you get the images from a service) whether the gradient will end up being light or dark. So, depending on the gradient, somehow it would also "return" either black or white for text color, depending on which would be best readable on the gradient itself.

Of course if the black level of the gradient would end up being around 50% gray, then that's a tough one.

Canva tainted by cross-origin data on Chrome

Hi !
I downloaded Grade to try it out and when I opened /docs/index.html on Chrome, the backgrounds behind the images are staying white. On the console I got this error :

grade.js:39 Uncaught SecurityError: Failed to execute 'getImageData' on 'CanvasRenderingContext2D': The canvas has been tainted by cross-origin data.

My Chrome version is 52.0.2743.116 m

This is however working fine on Firefox 44.0.2

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.