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

Overview

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.

Comments
  • This is just...broken

    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

    opened by danielfonda 10
  • Add the umd directory to files in package.json

    Add the umd directory to files in package.json

    @benhowdle89 great stuff!

    I changed the main entry point to the uncompiled version and added the dist file to files array in package. The dist file will become available on npmcdn.

    opened by hnqlv 5
  • Request: ability to get just colors

    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?

    opened by hellsan631 4
  • OSX Google Chrome - SecurityError

    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
    
    opened by MrSrsen 4
  • Flash of Unstyled DIVs

    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

    opened by vilav 3
  • Suggestion: Generate recommended text color

    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.

    opened by pentool 2
  • Working only with the saved images

    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

    opened by Kuldeep363 1
  • Canva tainted by cross-origin data on Chrome

    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

    opened by Barthoware 1
  • add localstorage capability

    add localstorage capability

    This pull request aims to cache the calculated color values with localStorage to skip processing on subsequent requests. This might also avoid flash of unstyled div mentioned in #8 after they have loaded initially.

    opened by lgraubner 1
  • [REQUEST] CDN

    [REQUEST] CDN

    Hi, it would be great to have your lib uploaded on a CDN.

    Here the free open source ones:

    • https://github.com/cdnjs/cdnjs
    • https://github.com/jsdelivr/jsdelivr

    Thanks

    opened by Naramsim 1
  • Not working in Safari

    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.

    opened by mrenty 1
  • I built a website for this awesome tool

    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

    opened by jwenjian 0
  • Work as a util server side.

    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.

    opened by tryggvigy 4
Algorithmically generated triangle art

Trianglify Trianglify is a library that I wrote to generate nice SVG background images like this one: Contents ?? Getting Trianglify ?? Quickstart ⚖️

Quinn Rohlf 10k Jan 1, 2023
procedurally generated fish drawings

fishdraw procedurally generated fish drawings. demo generates all sorts of weird fishes outputs polylines (supported format svg, json, csv, etc.) full

Lingdong Huang 2.1k Jan 3, 2023
Upload your webpack-generated assets to CDN, allowing renaming/rehashing.

webpack5-cdn-plugin For webpack4, please refer to webpack4-cdn-plugin. Docs Install npm i webpack5-cdn-plugin -D Usage const { Webpack5CDNPlugin } =

文蔺 4 Aug 22, 2022
Easily compose images together without messing around with canvas

merge-images Easily compose images together without messing around with canvas Canvas can be kind of a pain to work with sometimes, especially if you

Luke Childs 1.5k Dec 30, 2022
Java library for use with Chart.js javascript library

Chart.java Chart.java enables integration with the excellent Chart.js library from within a Java application. Usage example In Java: BarDataset datase

Marceau Dewilde 102 Dec 16, 2022
JavaScript 3D library.

three.js JavaScript 3D library The aim of the project is to create an easy to use, lightweight, cross-browser, general purpose 3D library. The current

Mr.doob 87.9k Jan 2, 2023
Javascript Canvas Library, SVG-to-Canvas (& canvas-to-SVG) Parser

Fabric.js Fabric.js is a framework that makes it easy to work with HTML5 canvas element. It is an interactive object model on top of canvas element. I

Fabric.js 23.6k Jan 3, 2023
The JavaScript library for modern SVG graphics.

Snap.svg · A JavaScript SVG library for the modern web. Learn more at snapsvg.io. Follow us on Twitter. Install Bower - bower install snap.svg npm - n

Adobe Web Platform 13.6k Dec 30, 2022
JavaScript Vector Library

Raphaël: Cross-browser vector graphics the easy way Visit the library website for more information: http://raphaeljs.com https://dmitrybaranovskiy.git

Dmitry Baranovskiy 11.2k Jan 3, 2023
A JavaScript library dedicated to graph drawing

sigma.js - v1.2.1 Sigma is a JavaScript library dedicated to graph drawing, mainly developed by @jacomyal and @Yomguithereal. Resources The website pr

Alexis Jacomy 10.3k Jan 3, 2023
JavaScript diagramming library for interactive flowcharts, org charts, design tools, planning tools, visual languages.

GoJS, a JavaScript Library for HTML Diagrams GoJS is a JavaScript and TypeScript library for creating and manipulating diagrams, charts, and graphs. S

Northwoods Software Corporation 6.6k Dec 30, 2022
mxGraph is a fully client side JavaScript diagramming library

NOTE 09.11.2020 : Development on mxGraph has now stopped, this repo is effectively end of life. Known forks: https://github.com/jsGraph/mxgraph https:

JGraph 6.5k Dec 30, 2022
🔥 JavaScript Library for HTML5 canvas based heatmaps

heatmap.js Dynamic Heatmaps for the Web. How to get started The fastest way to get started is to install heatmap.js with bower. Just run the following

Patrick Wied 5.9k Jan 2, 2023
Cubism.js: A JavaScript library for time series visualization.

Cubism.js Cubism.js is a D3 plugin for visualizing time series. Use Cubism to construct better realtime dashboards, pulling data from Graphite, Cube a

Square 4.9k Jan 3, 2023
A javascript library that extends D3.js to enable fast and beautiful visualizations.

d3plus D3plus is a JavaScript re-usable chart library that extends the popular D3.js to enable the easy creation of beautiful visualizations. Installi

D3plus 1.6k Dec 2, 2022
A plugin for the jQuery javascript library to generate small sparkline charts directly in the browser

jQuery Sparklines This jQuery plugin makes it easy to generate a number of different types of sparklines directly in the browser, using online a line

Gareth Watts 1.2k Jan 4, 2023
Ember Charts 3.5 2.3 L2 JavaScript A powerful and easy to use charting library for Ember.js

Ember Charts A charting library built with the Ember.js and d3.js frameworks. It includes time series, bar, pie, and scatter charts which are easy to

Addepar 793 Dec 7, 2022
A lightweight JavaScript graphics library with the intuitive API, based on SVG/VML technology.

GraphicsJS GraphicsJS is a lightweight JavaScript graphics library with the intuitive API, based on SVG/VML technology. Overview Quick Start Articles

AnyChart 973 Jan 3, 2023
Simple yet powerful JavaScript Charting library built using d3.js

uvCharts Simple, robust, extensible JavaScript charting library built using d3 designed to help developers embed, build charts in less than couple of

Imaginea 267 May 20, 2021