├── .gitignore ├── Gruntfile.js ├── LICENSE.md ├── README.md ├── examples ├── animate.html ├── grayscale.html └── iframe.html ├── gradientmaps.js ├── gradientmaps.min.js ├── package.json └── src ├── LICENSE.MD ├── csscolorparser.js └── gm-library.js /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | -------------------------------------------------------------------------------- /Gruntfile.js: -------------------------------------------------------------------------------- 1 | module.exports = function(grunt) { 2 | // Project configuration. 3 | 4 | var project = { 5 | files: ['src/gm-library.js', 'src/csscolorparser.js'] 6 | } 7 | 8 | grunt.initConfig({ 9 | pkg: grunt.file.readJSON('package.json'), 10 | uglify: { 11 | options: { 12 | banner: '/*! Copyright 2013 Adobe Systems Inc.;\n' + 13 | '* Licensed under the Apache License, Version 2.0 (the "License");\n' + 14 | '* you may not use this file except in compliance with the License.\n' + 15 | '* You may obtain a copy of the License at\n\n' + 16 | '* http://www.apache.org/licenses/LICENSE-2.0\n\n' + 17 | '* Unless required by applicable law or agreed to in writing, software\n' + 18 | '* distributed under the License is distributed on an "AS IS" BASIS,\n' + 19 | '* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n' + 20 | '* See the License for the specific language governing permissions and\n' + 21 | '* limitations under the License.\n'+ 22 | '*/\n\n' + 23 | '/*\n' + 24 | 'Gradient Maps support\n' + 25 | 'Author: Alan Greenblatt (blatt@adobe.com, @agreenblatt, blattchat.com)\n' + 26 | '*/\n' 27 | }, 28 | 29 | build: { 30 | src: '<%= concat.dist.dest %>', 31 | dest: '<%= pkg.name %>.min.js' 32 | } 33 | }, 34 | 35 | concat: { 36 | dist: { 37 | src: project.files, 38 | dest: '<%= pkg.name %>.js' 39 | } 40 | }, 41 | 42 | watch: { 43 | js: { 44 | files: project.files, 45 | tasks: ['concat', 'uglify'] 46 | } 47 | } 48 | 49 | }); 50 | 51 | grunt.loadNpmTasks('grunt-contrib-uglify'); 52 | grunt.loadNpmTasks('grunt-contrib-concat'); 53 | grunt.loadNpmTasks('grunt-contrib-watch'); 54 | 55 | grunt.registerTask('default', ['concat', 'uglify']); 56 | grunt.registerTask('build', ['concat', 'uglify']); 57 | }; 58 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Copyright 2013 Adobe Systems Incorporated. All rights reserved. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | 15 | Apache License 16 | Version 2.0, January 2004 17 | http://www.apache.org/licenses/ 18 | 19 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 20 | 21 | 1. Definitions. 22 | 23 | "License" shall mean the terms and conditions for use, reproduction, 24 | and distribution as defined by Sections 1 through 9 of this document. 25 | 26 | "Licensor" shall mean the copyright owner or entity authorized by 27 | the copyright owner that is granting the License. 28 | 29 | "Legal Entity" shall mean the union of the acting entity and all 30 | other entities that control, are controlled by, or are under common 31 | control with that entity. For the purposes of this definition, 32 | "control" means (i) the power, direct or indirect, to cause the 33 | direction or management of such entity, whether by contract or 34 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 35 | outstanding shares, or (iii) beneficial ownership of such entity. 36 | 37 | "You" (or "Your") shall mean an individual or Legal Entity 38 | exercising permissions granted by this License. 39 | 40 | "Source" form shall mean the preferred form for making modifications, 41 | including but not limited to software source code, documentation 42 | source, and configuration files. 43 | 44 | "Object" form shall mean any form resulting from mechanical 45 | transformation or translation of a Source form, including but 46 | not limited to compiled object code, generated documentation, 47 | and conversions to other media types. 48 | 49 | "Work" shall mean the work of authorship, whether in Source or 50 | Object form, made available under the License, as indicated by a 51 | copyright notice that is included in or attached to the work 52 | (an example is provided in the Appendix below). 53 | 54 | "Derivative Works" shall mean any work, whether in Source or Object 55 | form, that is based on (or derived from) the Work and for which the 56 | editorial revisions, annotations, elaborations, or other modifications 57 | represent, as a whole, an original work of authorship. For the purposes 58 | of this License, Derivative Works shall not include works that remain 59 | separable from, or merely link (or bind by name) to the interfaces of, 60 | the Work and Derivative Works thereof. 61 | 62 | "Contribution" shall mean any work of authorship, including 63 | the original version of the Work and any modifications or additions 64 | to that Work or Derivative Works thereof, that is intentionally 65 | submitted to Licensor for inclusion in the Work by the copyright owner 66 | or by an individual or Legal Entity authorized to submit on behalf of 67 | the copyright owner. For the purposes of this definition, "submitted" 68 | means any form of electronic, verbal, or written communication sent 69 | to the Licensor or its representatives, including but not limited to 70 | communication on electronic mailing lists, source code control systems, 71 | and issue tracking systems that are managed by, or on behalf of, the 72 | Licensor for the purpose of discussing and improving the Work, but 73 | excluding communication that is conspicuously marked or otherwise 74 | designated in writing by the copyright owner as "Not a Contribution." 75 | 76 | "Contributor" shall mean Licensor and any individual or Legal Entity 77 | on behalf of whom a Contribution has been received by Licensor and 78 | subsequently incorporated within the Work. 79 | 80 | 2. Grant of Copyright License. Subject to the terms and conditions of 81 | this License, each Contributor hereby grants to You a perpetual, 82 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 83 | copyright license to reproduce, prepare Derivative Works of, 84 | publicly display, publicly perform, sublicense, and distribute the 85 | Work and such Derivative Works in Source or Object form. 86 | 87 | 3. Grant of Patent License. Subject to the terms and conditions of 88 | this License, each Contributor hereby grants to You a perpetual, 89 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 90 | (except as stated in this section) patent license to make, have made, 91 | use, offer to sell, sell, import, and otherwise transfer the Work, 92 | where such license applies only to those patent claims licensable 93 | by such Contributor that are necessarily infringed by their 94 | Contribution(s) alone or by combination of their Contribution(s) 95 | with the Work to which such Contribution(s) was submitted. If You 96 | institute patent litigation against any entity (including a 97 | cross-claim or counterclaim in a lawsuit) alleging that the Work 98 | or a Contribution incorporated within the Work constitutes direct 99 | or contributory patent infringement, then any patent licenses 100 | granted to You under this License for that Work shall terminate 101 | as of the date such litigation is filed. 102 | 103 | 4. Redistribution. You may reproduce and distribute copies of the 104 | Work or Derivative Works thereof in any medium, with or without 105 | modifications, and in Source or Object form, provided that You 106 | meet the following conditions: 107 | 108 | (a) You must give any other recipients of the Work or 109 | Derivative Works a copy of this License; and 110 | 111 | (b) You must cause any modified files to carry prominent notices 112 | stating that You changed the files; and 113 | 114 | (c) You must retain, in the Source form of any Derivative Works 115 | that You distribute, all copyright, patent, trademark, and 116 | attribution notices from the Source form of the Work, 117 | excluding those notices that do not pertain to any part of 118 | the Derivative Works; and 119 | 120 | (d) If the Work includes a "NOTICE" text file as part of its 121 | distribution, then any Derivative Works that You distribute must 122 | include a readable copy of the attribution notices contained 123 | within such NOTICE file, excluding those notices that do not 124 | pertain to any part of the Derivative Works, in at least one 125 | of the following places: within a NOTICE text file distributed 126 | as part of the Derivative Works; within the Source form or 127 | documentation, if provided along with the Derivative Works; or, 128 | within a display generated by the Derivative Works, if and 129 | wherever such third-party notices normally appear. The contents 130 | of the NOTICE file are for informational purposes only and 131 | do not modify the License. You may add Your own attribution 132 | notices within Derivative Works that You distribute, alongside 133 | or as an addendum to the NOTICE text from the Work, provided 134 | that such additional attribution notices cannot be construed 135 | as modifying the License. 136 | 137 | You may add Your own copyright statement to Your modifications and 138 | may provide additional or different license terms and conditions 139 | for use, reproduction, or distribution of Your modifications, or 140 | for any such Derivative Works as a whole, provided Your use, 141 | reproduction, and distribution of the Work otherwise complies with 142 | the conditions stated in this License. 143 | 144 | 5. Submission of Contributions. Unless You explicitly state otherwise, 145 | any Contribution intentionally submitted for inclusion in the Work 146 | by You to the Licensor shall be under the terms and conditions of 147 | this License, without any additional terms or conditions. 148 | Notwithstanding the above, nothing herein shall supersede or modify 149 | the terms of any separate license agreement you may have executed 150 | with Licensor regarding such Contributions. 151 | 152 | 6. Trademarks. This License does not grant permission to use the trade 153 | names, trademarks, service marks, or product names of the Licensor, 154 | except as required for reasonable and customary use in describing the 155 | origin of the Work and reproducing the content of the NOTICE file. 156 | 157 | 7. Disclaimer of Warranty. Unless required by applicable law or 158 | agreed to in writing, Licensor provides the Work (and each 159 | Contributor provides its Contributions) on an "AS IS" BASIS, 160 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 161 | implied, including, without limitation, any warranties or conditions 162 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 163 | PARTICULAR PURPOSE. You are solely responsible for determining the 164 | appropriateness of using or redistributing the Work and assume any 165 | risks associated with Your exercise of permissions under this License. 166 | 167 | 8. Limitation of Liability. In no event and under no legal theory, 168 | whether in tort (including negligence), contract, or otherwise, 169 | unless required by applicable law (such as deliberate and grossly 170 | negligent acts) or agreed to in writing, shall any Contributor be 171 | liable to You for damages, including any direct, indirect, special, 172 | incidental, or consequential damages of any character arising as a 173 | result of this License or out of the use or inability to use the 174 | Work (including but not limited to damages for loss of goodwill, 175 | work stoppage, computer failure or malfunction, or any and all 176 | other commercial damages or losses), even if such Contributor 177 | has been advised of the possibility of such damages. 178 | 179 | 9. Accepting Warranty or Additional Liability. While redistributing 180 | the Work or Derivative Works thereof, You may choose to offer, 181 | and charge a fee for, acceptance of support, warranty, indemnity, 182 | or other liability obligations and/or rights consistent with this 183 | License. However, in accepting such obligations, You may act only 184 | on Your own behalf and on Your sole responsibility, not on behalf 185 | of any other Contributor, and only if You agree to indemnify, 186 | defend, and hold each Contributor harmless for any liability 187 | incurred by, or claims asserted against, such Contributor by reason 188 | of your accepting any such warranty or additional liability. 189 | 190 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Gradientmaps.js 2 | 3 | Javascript library that allows you to easily apply gradient maps to any HTML element on the page. 4 | 5 | Check out the blog post at: http://blogs.adobe.com/webplatform/2013/08/06/gradientmaps-js-gradient-maps-for-html/ 6 | 7 | ## Browser Support 8 | 9 | This functionality is currently supported on desktop Chrome and Firefox, and on iOS7 mobile Safari. 10 | 11 | ## What is a Gradient Map you ask? 12 | Traditionally, gradient maps are used in Photoshop. Think about taking an image and converting it to grayscale. Then, take a linear gradient and map that linear gradient to your image, where the left end of your gradient are the darkest values in your image, and the right end of your gradient maps to the brightest parts of your image. If you have a simple linear gradient from red to blue, the darkest parts of your image will get mapped to red, the brightest parts will get mapped to blue, and everything else will be some combination of red and blue, depending on how light or dark it is. 13 | 14 | ## Usage 15 | 16 | First, include the script in your page, most likely just before your closing <body> tag. 17 | 18 | ``` 19 | 20 | ``` 21 | 22 | Now, you can apply a gradient to any element on the page using the following Javascript: 23 | 24 | ``` 25 | GradientMaps.applyGradientMap(targetElement, linearGradient); 26 | ``` 27 | 28 | 29 | **linearGradient** uses the same format as [CSS linear gradients](http://docs.webplatform.org/wiki/css/functions/linear-gradient) without the initial angle, sides or corners. Instead you provide simply a list of comma-separated color-stops. 30 | 31 | Each color-stop consists of a color followed by an optional position. 32 | 33 | The color can be in any of the standard CSS color formats (rgb, rgba, hsl, hsla, named color or #hex-color). 34 | 35 | The position is either a percentage (e.g. 50%) or a fraction from 0.0 to 1.0. 36 | 37 | If the initial color-stop has no position, it is assumed to be 0% 38 | If the final color-stop has no position, it is assumed to be 100% 39 | If a color stop has no position, and it is not the first or last color-stop, it is positioned half way between the previous and next color-stop. 40 | If a color stop's position is less than the previous color-stop, it is repositioned to that of the previously positioned color-stop. 41 | 42 | ## Examples 43 | 44 | ``` 45 | 46 | ``` 47 | 48 | Convert to Black & White: 49 | ``` 50 | 51 | 57 | ``` 58 | 59 | Convert to Black & white, and darken the mid-tones a bit: 60 | ``` 61 | GradientMaps.applyGradientMap(target, "black, gray 60%, white"); 62 | ``` 63 | 64 | Map to a range of colors: 65 | ``` 66 | GradientMaps.applyGradientMap(target, "red, #00FF00, rgb(0, 0, 255), yellow"); 67 | ``` 68 | 69 | ## Contributing 70 | 71 | **DO NOT directly modify the `gradientmaps.js` or `gradientmaps.min.js` files in the project root.** These files are automatically built from components located under the `src/` directory. 72 | 73 | The project uses [Grunt](http://gruntjs.com) to automate the build process. 74 | 75 | 76 | Grunt depends on [Node.js](http://nodejs.org/) and [npm](https://npmjs.org/). 77 | 78 | 79 | **Install Grunt** 80 | ``` 81 | npm install -g grunt 82 | ``` 83 | 84 | Tell Grunt to watch for changes and automatically build `gradientmaps.js` and `gradientmaps.min.js`: 85 | ``` 86 | grunt watch 87 | ``` 88 | 89 | While `grunt watch` is running, every time you make changes to components under `src/` the main files, `cssregions.js` and `cssregions.min.js`, are built and written to the project root. 90 | 91 | To do a one-time build run: 92 | ``` 93 | grunt build 94 | ``` 95 | 96 | ## Testing 97 | 98 | ** Currently there are no tests ** 99 | 100 | I know, lame. 101 | 102 | ### Requirements 103 | 104 | 105 | ## License information 106 | 107 | The code in this repository implies and respects different licenses. This is a quick overview. For details check each folder's corresponding LICENSE.md file. 108 | 109 | - Adobe Apache 2 for Gradientmaps 110 | - MIT for csscolorparser 111 | - Public Domain for tests, demos and docs 112 | - Third party assets under their own licenses 113 | 114 | See LICENSE.md for details. 115 | -------------------------------------------------------------------------------- /examples/animate.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 11 | 12 | 13 | 14 |
By Kadellar (Own work) [CC-BY-SA-3.0], via Wikimedia Commons
15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 63 | 64 | 65 | -------------------------------------------------------------------------------- /examples/grayscale.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 19 | 20 | 21 |
22 | 23 |
24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 | 32 | 39 | 40 | 41 | -------------------------------------------------------------------------------- /examples/iframe.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 39 | 40 | 41 | 42 |

Try experimenting with your own gradient maps or your own website.

43 | 44 | 45 | 46 | 69 | 82 | 83 |
47 |

Sample gradients:

48 |
    49 |
  • 50 |
  • 51 |
  • 52 |
  • 53 |
  • 54 |
  • 55 |
  • 56 |
  • 57 |
58 | 59 | 60 | 61 |
62 |
63 |
64 | 65 |
66 | 67 |
68 |
70 |
71 | 72 | 73 | 74 |
75 | 76 | 77 | 78 |
79 | *Unfortunately, not all URLs will work with this demo due to IFrame security concerns. 80 |
81 |
84 | 85 | 86 | 87 | 131 | 132 | 133 | -------------------------------------------------------------------------------- /gradientmaps.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2013 Adobe Systems Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and limitations under the License. 14 | */ 15 | 16 | /* 17 | Gradient Maps support 18 | Author: Alan Greenblatt (blatt@adobe.com, @agreenblatt, blattchat.com) 19 | */ 20 | 21 | window.GradientMaps = function(scope) { 22 | function GradientMaps() { 23 | this.init(); 24 | } 25 | 26 | GradientMaps.prototype = { 27 | init: function() { 28 | }, 29 | 30 | generateID: function() { 31 | this.previousID = this.previousID + 1 || 0; 32 | return this.previousID; 33 | }, 34 | 35 | calcStopsArray: function(stopsDecl) { 36 | /* 37 | * Each stop consists of a color and an optional percentage or length 38 | * stops: [, ] 39 | * : color [ | ]? 40 | * 41 | * If the first color-stop does not have a length or percentage, it defaults to 0% 42 | * If the last color-stop does not have a length or percentage, it defaults to 100% 43 | * If a color-stop, other than the first or last, does not have a length or percentage, it is assigned the position half way between the previous and the next stop. 44 | * If a color-stop, other than the first or last, has a specified position less than the previous stop, its position is changed to be equal to the largest specified position of any prior color-stop. 45 | */ 46 | 47 | var matches = stopsDecl.match(/(((rgb|hsl)a?\(\d{1,3},\s*\d{1,3},\s*\d{1,3}(?:,\s*0?\.?\d+)?\)|\w+|#[0-9a-fA-F]{1,6})(\s+(0?\.\d+|\d{1,3}%))?)/g); 48 | 49 | var stopsDeclArr = stopsDecl.split(','); 50 | var stops = []; 51 | 52 | matches.forEach(function(colorStop) { 53 | var colorStopMatches = colorStop.match(/(?:((rgb|hsl)a?\(\d{1,3},\s*\d{1,3},\s*\d{1,3}(?:,\s*0?\.?\d+)?\)|\w+|#[0-9a-fA-F]{1,6})(\s+(?:0?\.\d+|\d{1,3}%))?)/); 54 | if (colorStopMatches && colorStopMatches.length >= 4) { 55 | var posMatch = colorStopMatches[3]; 56 | stops.push({ 57 | color: parseCSSColor(colorStopMatches[1]), 58 | pos: posMatch ? parse_css_float(posMatch) * 100 : null 59 | }) 60 | } 61 | }); 62 | 63 | /* 64 | * Need to calculate the positions where they aren't specified. 65 | * In the case of the first and last stop, we may even have to add a new stop. 66 | * 67 | * Go through the array of stops, finding ones where the position is not specified. 68 | * Then, find the next specified position or terminate on the last stop. 69 | * Finally, evenly distribute the unspecified positions, with the first stop at 0 70 | * and the last stop at 100. 71 | */ 72 | 73 | if (stops.length >= 1) { 74 | // If the first stop's position is not specified, set it to 0. 75 | var stop = stops[0]; 76 | if (!stop.pos) 77 | stop.pos = 0; 78 | else 79 | stop.pos = Math.min(100, Math.max(0, stop.pos)); 80 | 81 | var currentPos = stop.pos; 82 | 83 | // If the last stop's position is not specified, set it to 100. 84 | stop = stops[stops.length-1]; 85 | if (!stop.pos) 86 | stop.pos = 100; 87 | else 88 | stop.pos = Math.min(100, Math.max(0, stop.pos)); 89 | 90 | // Make sure that all positions are in ascending order 91 | for (var i = 1; i < stops.length-1; i++) { 92 | stop = stops[i]; 93 | if (stop.pos && stop.pos < currentPos) 94 | stop.pos = currentPos; 95 | if (stop.pos > 100) stop.pos = 100; 96 | currentPos = stop.pos; 97 | } 98 | 99 | // Find any runs of unpositioned stops and calculate them 100 | var i = 1; 101 | while (i < (stops.length-1)) { 102 | if (!stops[i].pos) { 103 | // Find the next positioned stop. You'll always have at least the 104 | // last stop at 100. 105 | for (var j = i+1; j < stops.length; j++) { 106 | if (stops[j].pos) 107 | break; 108 | } 109 | 110 | var startPos = stops[i-1].pos; 111 | var endPos = stops[j].pos; 112 | var nStops = j - 1 + 1; 113 | 114 | var delta = Math.round((endPos - startPos) / nStops); 115 | while (i < j) { 116 | stops[i].pos = stops[i-1].pos + delta; 117 | i++; 118 | } 119 | } 120 | 121 | i++; 122 | } 123 | 124 | if (stops[0].pos != 0) { 125 | stops.unshift({ 126 | color: stops[0].color, 127 | pos: 0 128 | }); 129 | } 130 | 131 | if (stops[stops.length-1].pos != 100) { 132 | stops.push({ 133 | color: stops[stops.length-1].color, 134 | pos: 100 135 | }) 136 | } 137 | } 138 | 139 | return stops; 140 | }, 141 | 142 | findMatchingDistributedNSegs: function(stops) { 143 | var maxNumSegs = 100; 144 | var matched = false; 145 | for (var nSegs = 1; !matched && nSegs <= maxNumSegs; nSegs++) { 146 | var segSize = maxNumSegs / nSegs; 147 | matched = true; 148 | for (var i = 1; i < stops.length-1; i++) { 149 | var pos = stops[i].pos; 150 | if (pos < segSize) { 151 | matched = false; 152 | break; 153 | } 154 | var rem = pos % segSize; 155 | var maxDiff = 1.0; 156 | if (!(rem < maxDiff || (segSize - rem) < maxDiff)) { 157 | matched = false; 158 | break; 159 | } 160 | } 161 | 162 | if (matched) 163 | return nSegs; 164 | } 165 | 166 | return nSegs; 167 | }, 168 | 169 | calcDistributedColors: function(stops, nSegs) { 170 | var colors = [stops[0].color]; 171 | 172 | var segSize = 100 / nSegs; 173 | for (var i = 1; i < stops.length-1; i++) { 174 | var stop = stops[i]; 175 | var n = Math.round(stop.pos / segSize); 176 | colors[n] = stop.color; 177 | } 178 | 179 | colors[nSegs] = stops[stops.length-1].color; 180 | 181 | var i = 1; 182 | while (i < colors.length) { 183 | if (!colors[i]) { 184 | for (var j = i+1; j < colors.length; j++) { 185 | if (colors[j]) 186 | break; 187 | } 188 | 189 | // Need to evenly distribute colors stops from svgStop[i-1] to svgStop[j] 190 | 191 | var startColor = colors[i-1]; 192 | var r = startColor[0]; 193 | var g = startColor[1]; 194 | var b = startColor[2]; 195 | var a = startColor[3]; 196 | 197 | var endColor = colors[j]; 198 | 199 | var nSegs = j - i + 1; 200 | var dr = (endColor[0] - r) / nSegs; 201 | var dg = (endColor[1] - g) / nSegs; 202 | var db = (endColor[2] - b) / nSegs; 203 | var da = (endColor[3] - a) / nSegs; 204 | 205 | while (i < j) { 206 | r += dr; 207 | g += dg; 208 | b += db; 209 | a += da; 210 | colors[i] = [r, g, b, a]; 211 | i++; 212 | } 213 | } 214 | i++; 215 | } 216 | 217 | return colors; 218 | }, 219 | 220 | addElement: function(doc, parent, tagname, ns, attributes) { 221 | var elem = ns ? doc.createElementNS(ns, tagname) : doc.createElement(tagname); 222 | if (attributes) { 223 | Object.keys(attributes).forEach(function(key, index, keys) { 224 | elem.setAttribute(key, attributes[key]); 225 | }); 226 | //elem.setAttribute(attr.name, attr.value); 227 | } 228 | 229 | if (parent) parent.appendChild(elem); 230 | return elem; 231 | }, 232 | 233 | addSVGComponentTransferFilter: function(elem, colors) { 234 | var filter = null; 235 | var svg = null; 236 | var svgns = 'http://www.w3.org/2000/svg'; 237 | var filterID = elem.getAttribute('data-gradientmap-filter'); 238 | 239 | var svgIsNew = false; 240 | 241 | var doc = elem.ownerDocument; 242 | 243 | if (filterID) { 244 | filter = doc.getElementById(filterID); 245 | if (filter) { 246 | // Remove old component transfer function 247 | var componentTransfers = filter.getElementsByTagNameNS(svgns, 'feComponentTransfer'); 248 | if (componentTransfers) { 249 | for (var i = componentTransfers.length-1; i >= 0; --i) 250 | filter.removeChild(componentTransfers[i]); 251 | 252 | svg = filter.parentElement; 253 | } 254 | } 255 | } 256 | 257 | // The last thing to be set previously is 'svg'. If that is still null, that will handle any errors 258 | if (!svg) { 259 | var svg = this.addElement(doc, null, 'svg', svgns, { 260 | 'version': '1.1', 261 | 'width': 0, 262 | 'height': 0 263 | }); 264 | 265 | filterID = 'filter-' + this.generateID(); 266 | filter = this.addElement(doc, svg, 'filter', svgns, {'id': filterID}); 267 | elem.setAttribute('data-gradientmap-filter', filterID); 268 | 269 | // First, apply a color matrix to turn the source into a grayscale 270 | var colorMatrix = this.addElement(doc, filter, 'feColorMatrix', svgns, { 271 | 'type': 'matrix', 272 | 'values': '0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0', 273 | 'result': 'gray' 274 | }); 275 | 276 | svgIsNew = true; 277 | } 278 | 279 | // Now apply a component transfer to remap the colors 280 | var componentTransfer = this.addElement(doc, filter, 'feComponentTransfer', svgns, {'color-interpolation-filters': 'sRGB'}); 281 | 282 | var redTableValues = ""; 283 | var greenTableValues = ""; 284 | var blueTableValues = ""; 285 | var alphaTableValues = ""; 286 | 287 | colors.forEach(function(color, index, colors) { 288 | redTableValues += (color[0] / 255.0 + " "); 289 | greenTableValues += (color[1] / 255.0 + " "); 290 | blueTableValues += (color[2] / 255.0 + " "); 291 | alphaTableValues += (color[3] + " "); 292 | }); 293 | 294 | this.addElement(doc, componentTransfer, 'feFuncR', svgns, {'type': 'table', 'tableValues': redTableValues.trim()}); 295 | this.addElement(doc, componentTransfer, 'feFuncG', svgns, {'type': 'table', 'tableValues': greenTableValues.trim()}); 296 | this.addElement(doc, componentTransfer, 'feFuncB', svgns, {'type': 'table', 'tableValues': blueTableValues.trim()}); 297 | this.addElement(doc, componentTransfer, 'feFuncA', svgns, {'type': 'table', 'tableValues': alphaTableValues.trim()}); 298 | 299 | if (svgIsNew) 300 | elem.parentElement.insertBefore(svg, elem); 301 | 302 | var filterDecl = 'url(#' + filterID + ')'; 303 | elem.style['-webkit-filter'] = filterDecl; 304 | elem.style['filter'] = filterDecl; 305 | 306 | //elem.setAttribute('style', '-webkit-filter: url(#' + filterID + '); filter: url(#' + filterID + ')'); 307 | }, 308 | 309 | applyGradientMap: function(elem, gradient) { 310 | var stops = this.calcStopsArray(gradient); 311 | var nSegs = this.findMatchingDistributedNSegs(stops); 312 | var colors = this.calcDistributedColors(stops, nSegs); 313 | 314 | this.addSVGComponentTransferFilter(elem, colors); 315 | }, 316 | 317 | removeGradientMap: function(elem) { 318 | var filterID = elem.getAttribute('data-gradientmap-filter'); 319 | if (filterID) { 320 | var doc = elem.ownerDocument; 321 | var filter = doc.getElementById(filterID); 322 | if (filter) { 323 | var svg = filter.parentElement; 324 | svg.removeChild(filter); 325 | if (svg.childNodes.length <= 0) { 326 | var parent = svg.parentElement; 327 | parent.removeChild(svg); 328 | } 329 | } 330 | elem.removeAttribute('data-gradientmap-filter'); 331 | elem.style['-webkit-filter'] = ''; 332 | elem.style['filter'] = ''; 333 | } 334 | }, 335 | } 336 | 337 | return new GradientMaps(); 338 | }(window); 339 | 340 | // (c) Dean McNamee , 2012. 341 | // 342 | // https://github.com/deanm/css-color-parser-js 343 | // 344 | // Permission is hereby granted, free of charge, to any person obtaining a copy 345 | // of this software and associated documentation files (the "Software"), to 346 | // deal in the Software without restriction, including without limitation the 347 | // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 348 | // sell copies of the Software, and to permit persons to whom the Software is 349 | // furnished to do so, subject to the following conditions: 350 | // 351 | // The above copyright notice and this permission notice shall be included in 352 | // all copies or substantial portions of the Software. 353 | // 354 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 355 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 356 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 357 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 358 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 359 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 360 | // IN THE SOFTWARE. 361 | 362 | // http://www.w3.org/TR/css3-color/ 363 | var kCSSColorTable = { 364 | "transparent": [0,0,0,0], "aliceblue": [240,248,255,1], 365 | "antiquewhite": [250,235,215,1], "aqua": [0,255,255,1], 366 | "aquamarine": [127,255,212,1], "azure": [240,255,255,1], 367 | "beige": [245,245,220,1], "bisque": [255,228,196,1], 368 | "black": [0,0,0,1], "blanchedalmond": [255,235,205,1], 369 | "blue": [0,0,255,1], "blueviolet": [138,43,226,1], 370 | "brown": [165,42,42,1], "burlywood": [222,184,135,1], 371 | "cadetblue": [95,158,160,1], "chartreuse": [127,255,0,1], 372 | "chocolate": [210,105,30,1], "coral": [255,127,80,1], 373 | "cornflowerblue": [100,149,237,1], "cornsilk": [255,248,220,1], 374 | "crimson": [220,20,60,1], "cyan": [0,255,255,1], 375 | "darkblue": [0,0,139,1], "darkcyan": [0,139,139,1], 376 | "darkgoldenrod": [184,134,11,1], "darkgray": [169,169,169,1], 377 | "darkgreen": [0,100,0,1], "darkgrey": [169,169,169,1], 378 | "darkkhaki": [189,183,107,1], "darkmagenta": [139,0,139,1], 379 | "darkolivegreen": [85,107,47,1], "darkorange": [255,140,0,1], 380 | "darkorchid": [153,50,204,1], "darkred": [139,0,0,1], 381 | "darksalmon": [233,150,122,1], "darkseagreen": [143,188,143,1], 382 | "darkslateblue": [72,61,139,1], "darkslategray": [47,79,79,1], 383 | "darkslategrey": [47,79,79,1], "darkturquoise": [0,206,209,1], 384 | "darkviolet": [148,0,211,1], "deeppink": [255,20,147,1], 385 | "deepskyblue": [0,191,255,1], "dimgray": [105,105,105,1], 386 | "dimgrey": [105,105,105,1], "dodgerblue": [30,144,255,1], 387 | "firebrick": [178,34,34,1], "floralwhite": [255,250,240,1], 388 | "forestgreen": [34,139,34,1], "fuchsia": [255,0,255,1], 389 | "gainsboro": [220,220,220,1], "ghostwhite": [248,248,255,1], 390 | "gold": [255,215,0,1], "goldenrod": [218,165,32,1], 391 | "gray": [128,128,128,1], "green": [0,128,0,1], 392 | "greenyellow": [173,255,47,1], "grey": [128,128,128,1], 393 | "honeydew": [240,255,240,1], "hotpink": [255,105,180,1], 394 | "indianred": [205,92,92,1], "indigo": [75,0,130,1], 395 | "ivory": [255,255,240,1], "khaki": [240,230,140,1], 396 | "lavender": [230,230,250,1], "lavenderblush": [255,240,245,1], 397 | "lawngreen": [124,252,0,1], "lemonchiffon": [255,250,205,1], 398 | "lightblue": [173,216,230,1], "lightcoral": [240,128,128,1], 399 | "lightcyan": [224,255,255,1], "lightgoldenrodyellow": [250,250,210,1], 400 | "lightgray": [211,211,211,1], "lightgreen": [144,238,144,1], 401 | "lightgrey": [211,211,211,1], "lightpink": [255,182,193,1], 402 | "lightsalmon": [255,160,122,1], "lightseagreen": [32,178,170,1], 403 | "lightskyblue": [135,206,250,1], "lightslategray": [119,136,153,1], 404 | "lightslategrey": [119,136,153,1], "lightsteelblue": [176,196,222,1], 405 | "lightyellow": [255,255,224,1], "lime": [0,255,0,1], 406 | "limegreen": [50,205,50,1], "linen": [250,240,230,1], 407 | "magenta": [255,0,255,1], "maroon": [128,0,0,1], 408 | "mediumaquamarine": [102,205,170,1], "mediumblue": [0,0,205,1], 409 | "mediumorchid": [186,85,211,1], "mediumpurple": [147,112,219,1], 410 | "mediumseagreen": [60,179,113,1], "mediumslateblue": [123,104,238,1], 411 | "mediumspringgreen": [0,250,154,1], "mediumturquoise": [72,209,204,1], 412 | "mediumvioletred": [199,21,133,1], "midnightblue": [25,25,112,1], 413 | "mintcream": [245,255,250,1], "mistyrose": [255,228,225,1], 414 | "moccasin": [255,228,181,1], "navajowhite": [255,222,173,1], 415 | "navy": [0,0,128,1], "oldlace": [253,245,230,1], 416 | "olive": [128,128,0,1], "olivedrab": [107,142,35,1], 417 | "orange": [255,165,0,1], "orangered": [255,69,0,1], 418 | "orchid": [218,112,214,1], "palegoldenrod": [238,232,170,1], 419 | "palegreen": [152,251,152,1], "paleturquoise": [175,238,238,1], 420 | "palevioletred": [219,112,147,1], "papayawhip": [255,239,213,1], 421 | "peachpuff": [255,218,185,1], "peru": [205,133,63,1], 422 | "pink": [255,192,203,1], "plum": [221,160,221,1], 423 | "powderblue": [176,224,230,1], "purple": [128,0,128,1], 424 | "red": [255,0,0,1], "rosybrown": [188,143,143,1], 425 | "royalblue": [65,105,225,1], "saddlebrown": [139,69,19,1], 426 | "salmon": [250,128,114,1], "sandybrown": [244,164,96,1], 427 | "seagreen": [46,139,87,1], "seashell": [255,245,238,1], 428 | "sienna": [160,82,45,1], "silver": [192,192,192,1], 429 | "skyblue": [135,206,235,1], "slateblue": [106,90,205,1], 430 | "slategray": [112,128,144,1], "slategrey": [112,128,144,1], 431 | "snow": [255,250,250,1], "springgreen": [0,255,127,1], 432 | "steelblue": [70,130,180,1], "tan": [210,180,140,1], 433 | "teal": [0,128,128,1], "thistle": [216,191,216,1], 434 | "tomato": [255,99,71,1], "turquoise": [64,224,208,1], 435 | "violet": [238,130,238,1], "wheat": [245,222,179,1], 436 | "white": [255,255,255,1], "whitesmoke": [245,245,245,1], 437 | "yellow": [255,255,0,1], "yellowgreen": [154,205,50,1]} 438 | 439 | function clamp_css_byte(i) { // Clamp to integer 0 .. 255. 440 | i = Math.round(i); // Seems to be what Chrome does (vs truncation). 441 | return i < 0 ? 0 : i > 255 ? 255 : i; 442 | } 443 | 444 | function clamp_css_float(f) { // Clamp to float 0.0 .. 1.0. 445 | return f < 0 ? 0 : f > 1 ? 1 : f; 446 | } 447 | 448 | function parse_css_int(str) { // int or percentage. 449 | if (str[str.length - 1] === '%') 450 | return clamp_css_byte(parseFloat(str) / 100 * 255); 451 | return clamp_css_byte(parseInt(str)); 452 | } 453 | 454 | function parse_css_float(str) { // float or percentage. 455 | if (str[str.length - 1] === '%') 456 | return clamp_css_float(parseFloat(str) / 100); 457 | return clamp_css_float(parseFloat(str)); 458 | } 459 | 460 | function css_hue_to_rgb(m1, m2, h) { 461 | if (h < 0) h += 1; 462 | else if (h > 1) h -= 1; 463 | 464 | if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; 465 | if (h * 2 < 1) return m2; 466 | if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6; 467 | return m1; 468 | } 469 | 470 | function parseCSSColor(css_str) { 471 | // Remove all whitespace, not compliant, but should just be more accepting. 472 | var str = css_str.replace(/ /g, '').toLowerCase(); 473 | 474 | // Color keywords (and transparent) lookup. 475 | if (str in kCSSColorTable) return kCSSColorTable[str].slice(); // dup. 476 | 477 | // #abc and #abc123 syntax. 478 | if (str[0] === '#') { 479 | if (str.length === 4) { 480 | var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. 481 | if (!(iv >= 0 && iv <= 0xfff)) return null; // Covers NaN. 482 | return [((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8), 483 | (iv & 0xf0) | ((iv & 0xf0) >> 4), 484 | (iv & 0xf) | ((iv & 0xf) << 4), 485 | 1]; 486 | } else if (str.length === 7) { 487 | var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. 488 | if (!(iv >= 0 && iv <= 0xffffff)) return null; // Covers NaN. 489 | return [(iv & 0xff0000) >> 16, 490 | (iv & 0xff00) >> 8, 491 | iv & 0xff, 492 | 1]; 493 | } 494 | 495 | return null; 496 | } 497 | 498 | var op = str.indexOf('('), ep = str.indexOf(')'); 499 | if (op !== -1 && ep + 1 === str.length) { 500 | var fname = str.substr(0, op); 501 | var params = str.substr(op+1, ep-(op+1)).split(','); 502 | var alpha = 1; // To allow case fallthrough. 503 | switch (fname) { 504 | case 'rgba': 505 | if (params.length !== 4) return null; 506 | alpha = parse_css_float(params.pop()); 507 | // Fall through. 508 | case 'rgb': 509 | if (params.length !== 3) return null; 510 | return [parse_css_int(params[0]), 511 | parse_css_int(params[1]), 512 | parse_css_int(params[2]), 513 | alpha]; 514 | case 'hsla': 515 | if (params.length !== 4) return null; 516 | alpha = parse_css_float(params.pop()); 517 | // Fall through. 518 | case 'hsl': 519 | if (params.length !== 3) return null; 520 | var h = (((parseFloat(params[0]) % 360) + 360) % 360) / 360; // 0 .. 1 521 | // NOTE(deanm): According to the CSS spec s/l should only be 522 | // percentages, but we don't bother and let float or percentage. 523 | var s = parse_css_float(params[1]); 524 | var l = parse_css_float(params[2]); 525 | var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; 526 | var m1 = l * 2 - m2; 527 | return [clamp_css_byte(css_hue_to_rgb(m1, m2, h+1/3) * 255), 528 | clamp_css_byte(css_hue_to_rgb(m1, m2, h) * 255), 529 | clamp_css_byte(css_hue_to_rgb(m1, m2, h-1/3) * 255), 530 | alpha]; 531 | default: 532 | return null; 533 | } 534 | } 535 | 536 | return null; 537 | } 538 | 539 | try { exports.parseCSSColor = parseCSSColor } catch(e) { } 540 | -------------------------------------------------------------------------------- /gradientmaps.min.js: -------------------------------------------------------------------------------- 1 | /*! Copyright 2013 Adobe Systems Inc.; 2 | * Licensed under the Apache License, Version 2.0 (the "License"); 3 | * you may not use this file except in compliance with the License. 4 | * You may obtain a copy of the License at 5 | 6 | * http://www.apache.org/licenses/LICENSE-2.0 7 | 8 | * Unless required by applicable law or agreed to in writing, software 9 | * distributed under the License is distributed on an "AS IS" BASIS, 10 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 | * See the License for the specific language governing permissions and 12 | * limitations under the License. 13 | */ 14 | 15 | /* 16 | Gradient Maps support 17 | Author: Alan Greenblatt (blatt@adobe.com, @agreenblatt, blattchat.com) 18 | */ 19 | function clamp_css_byte(a){return a=Math.round(a),0>a?0:a>255?255:a}function clamp_css_float(a){return 0>a?0:a>1?1:a}function parse_css_int(a){return clamp_css_byte("%"===a[a.length-1]?parseFloat(a)/100*255:parseInt(a))}function parse_css_float(a){return clamp_css_float("%"===a[a.length-1]?parseFloat(a)/100:parseFloat(a))}function css_hue_to_rgb(a,b,c){return 0>c?c+=1:c>1&&(c-=1),1>6*c?a+(b-a)*c*6:1>2*c?b:2>3*c?a+(b-a)*(2/3-c)*6:a}function parseCSSColor(a){var b=a.replace(/ /g,"").toLowerCase();if(b in kCSSColorTable)return kCSSColorTable[b].slice();if("#"===b[0]){if(4===b.length){var c=parseInt(b.substr(1),16);return c>=0&&4095>=c?[(3840&c)>>4|(3840&c)>>8,240&c|(240&c)>>4,15&c|(15&c)<<4,1]:null}if(7===b.length){var c=parseInt(b.substr(1),16);return c>=0&&16777215>=c?[(16711680&c)>>16,(65280&c)>>8,255&c,1]:null}return null}var d=b.indexOf("("),e=b.indexOf(")");if(-1!==d&&e+1===b.length){var f=b.substr(0,d),g=b.substr(d+1,e-(d+1)).split(","),h=1;switch(f){case"rgba":if(4!==g.length)return null;h=parse_css_float(g.pop());case"rgb":return 3!==g.length?null:[parse_css_int(g[0]),parse_css_int(g[1]),parse_css_int(g[2]),h];case"hsla":if(4!==g.length)return null;h=parse_css_float(g.pop());case"hsl":if(3!==g.length)return null;var i=(parseFloat(g[0])%360+360)%360/360,j=parse_css_float(g[1]),k=parse_css_float(g[2]),l=.5>=k?k*(j+1):k+j-k*j,m=2*k-l;return[clamp_css_byte(255*css_hue_to_rgb(m,l,i+1/3)),clamp_css_byte(255*css_hue_to_rgb(m,l,i)),clamp_css_byte(255*css_hue_to_rgb(m,l,i-1/3)),h];default:return null}}return null}window.GradientMaps=function(a){function b(){this.init()}return b.prototype={init:function(){},generateID:function(){return this.previousID=this.previousID+1||0,this.previousID},calcStopsArray:function(a){var b=a.match(/(((rgb|hsl)a?\(\d{1,3},\s*\d{1,3},\s*\d{1,3}(?:,\s*0?\.?\d+)?\)|\w+|#[0-9a-fA-F]{1,6})(\s+(0?\.\d+|\d{1,3}%))?)/g),c=(a.split(","),[]);if(b.forEach(function(a){var b=a.match(/(?:((rgb|hsl)a?\(\d{1,3},\s*\d{1,3},\s*\d{1,3}(?:,\s*0?\.?\d+)?\)|\w+|#[0-9a-fA-F]{1,6})(\s+(?:0?\.\d+|\d{1,3}%))?)/);b&&b.length>=4&&(posMatch=b[3],c.push({color:parseCSSColor(b[1]),pos:posMatch?100*parse_css_float(posMatch):null}))}),c.length>=1){var d=c[0];d.pos?d.pos=Math.min(100,Math.max(0,d.pos)):d.pos=0;var e=d.pos;d=c[c.length-1],d.pos?d.pos=Math.min(100,Math.max(0,d.pos)):d.pos=100;for(var f=1;f100&&(d.pos=100),e=d.pos;for(var f=1;ff;)c[f].pos=c[f-1].pos+k,f++}f++}0!=c[0].pos&&c.unshift({color:c[0].color,pos:0}),100!=c[c.length-1].pos&&c.push({color:c[c.length-1].color,pos:100})}return c},findMatchingDistributedNSegs:function(a){for(var b=100,c=!1,d=1;!c&&b>=d;d++){var e=b/d;c=!0;for(var f=1;fg){c=!1;break}var h=g%e,i=1;if(!(i>h||i>e-h)){c=!1;break}}if(c)return d}return d},calcDistributedColors:function(a,b){for(var c=[a[0].color],d=100/b,e=1;ee;)j+=o,k+=p,l+=q,m+=r,c[e]=[j,k,l,m],e++}e++}return c},addElement:function(a,b,c,d,e){var f=d?a.createElementNS(d,c):a.createElement(c);return e&&Object.keys(e).forEach(function(a,b,c){f.setAttribute(a,e[a])}),b&&b.appendChild(f),f},addSVGComponentTransferFilter:function(a,b){var c=null,d=null,e="http://www.w3.org/2000/svg",f=a.getAttribute("data-gradientmap-filter"),g=!1,h=a.ownerDocument;if(f&&(c=h.getElementById(f))){var i=c.getElementsByTagNameNS(e,"feComponentTransfer");if(i){for(var j=i.length-1;j>=0;--j)c.removeChild(i[j]);d=c.parentElement}}if(!d){var d=this.addElement(h,null,"svg",e,{version:"1.1",width:0,height:0});f="filter-"+this.generateID(),c=this.addElement(h,d,"filter",e,{id:f}),a.setAttribute("data-gradientmap-filter",f);this.addElement(h,c,"feColorMatrix",e,{type:"matrix",values:"0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0",result:"gray"});g=!0}var k=this.addElement(h,c,"feComponentTransfer",e,{"color-interpolation-filters":"sRGB"}),l="",m="",n="",o="";b.forEach(function(a,b,c){l+=a[0]/255+" ",m+=a[1]/255+" ",n+=a[2]/255+" ",o+=a[3]+" "}),this.addElement(h,k,"feFuncR",e,{type:"table",tableValues:l.trim()}),this.addElement(h,k,"feFuncG",e,{type:"table",tableValues:m.trim()}),this.addElement(h,k,"feFuncB",e,{type:"table",tableValues:n.trim()}),this.addElement(h,k,"feFuncA",e,{type:"table",tableValues:o.trim()}),g&&a.parentElement.insertBefore(d,a);var p="url(#"+f+")";a.style["-webkit-filter"]=p,a.style.filter=p},applyGradientMap:function(a,b){var c=this.calcStopsArray(b),d=this.findMatchingDistributedNSegs(c),e=this.calcDistributedColors(c,d);this.addSVGComponentTransferFilter(a,e)},removeGradientMap:function(a){var b=a.getAttribute("data-gradientmap-filter");if(b){var c=a.ownerDocument,d=c.getElementById(b);if(d){var e=d.parentElement;if(e.removeChild(d),e.childNodes.length<=0){var f=e.parentElement;f.removeChild(e)}}a.removeAttribute("data-gradientmap-filter"),a.style["-webkit-filter"]="",a.style.filter=""}}},new b}(window);var kCSSColorTable={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};try{exports.parseCSSColor=parseCSSColor}catch(e){} -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "gradientmaps", 3 | "title": "Gradientmaps.js", 4 | "version": "0.1.0", 5 | "author": { 6 | "name": "Adobe Systems Inc." 7 | }, 8 | "contributors": [ 9 | "Alan Greenblatt (http://blattchat.com)" 10 | ], 11 | "licenses": [ 12 | { 13 | "type": "Apache License 2.0" 14 | } 15 | ], 16 | "devDependencies": { 17 | "grunt": "~0.4.1", 18 | "grunt-contrib-jshint": "~0.6.0", 19 | "grunt-contrib-nodeunit": "~0.2.0", 20 | "grunt-contrib-uglify": "~0.2.2", 21 | "grunt-contrib-concat": "~0.3.0", 22 | "grunt-contrib-watch": "~0.4.4" 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/LICENSE.MD: -------------------------------------------------------------------------------- 1 | Copyright [year] Adobe Systems Incorporated. All rights reserved. 2 | 3 | Licensed under the Apache License, Version 2.0 (the "License"); 4 | you may not use this file except in compliance with the License. 5 | You may obtain a copy of the License at 6 | 7 | http://www.apache.org/licenses/LICENSE-2.0 8 | 9 | Unless required by applicable law or agreed to in writing, software 10 | distributed under the License is distributed on an "AS IS" BASIS, 11 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 | See the License for the specific language governing permissions and 13 | limitations under the License. 14 | 15 | Apache License 16 | Version 2.0, January 2004 17 | http://www.apache.org/licenses/ 18 | 19 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 20 | 21 | 1. Definitions. 22 | 23 | "License" shall mean the terms and conditions for use, reproduction, 24 | and distribution as defined by Sections 1 through 9 of this document. 25 | 26 | "Licensor" shall mean the copyright owner or entity authorized by 27 | the copyright owner that is granting the License. 28 | 29 | "Legal Entity" shall mean the union of the acting entity and all 30 | other entities that control, are controlled by, or are under common 31 | control with that entity. For the purposes of this definition, 32 | "control" means (i) the power, direct or indirect, to cause the 33 | direction or management of such entity, whether by contract or 34 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 35 | outstanding shares, or (iii) beneficial ownership of such entity. 36 | 37 | "You" (or "Your") shall mean an individual or Legal Entity 38 | exercising permissions granted by this License. 39 | 40 | "Source" form shall mean the preferred form for making modifications, 41 | including but not limited to software source code, documentation 42 | source, and configuration files. 43 | 44 | "Object" form shall mean any form resulting from mechanical 45 | transformation or translation of a Source form, including but 46 | not limited to compiled object code, generated documentation, 47 | and conversions to other media types. 48 | 49 | "Work" shall mean the work of authorship, whether in Source or 50 | Object form, made available under the License, as indicated by a 51 | copyright notice that is included in or attached to the work 52 | (an example is provided in the Appendix below). 53 | 54 | "Derivative Works" shall mean any work, whether in Source or Object 55 | form, that is based on (or derived from) the Work and for which the 56 | editorial revisions, annotations, elaborations, or other modifications 57 | represent, as a whole, an original work of authorship. For the purposes 58 | of this License, Derivative Works shall not include works that remain 59 | separable from, or merely link (or bind by name) to the interfaces of, 60 | the Work and Derivative Works thereof. 61 | 62 | "Contribution" shall mean any work of authorship, including 63 | the original version of the Work and any modifications or additions 64 | to that Work or Derivative Works thereof, that is intentionally 65 | submitted to Licensor for inclusion in the Work by the copyright owner 66 | or by an individual or Legal Entity authorized to submit on behalf of 67 | the copyright owner. For the purposes of this definition, "submitted" 68 | means any form of electronic, verbal, or written communication sent 69 | to the Licensor or its representatives, including but not limited to 70 | communication on electronic mailing lists, source code control systems, 71 | and issue tracking systems that are managed by, or on behalf of, the 72 | Licensor for the purpose of discussing and improving the Work, but 73 | excluding communication that is conspicuously marked or otherwise 74 | designated in writing by the copyright owner as "Not a Contribution." 75 | 76 | "Contributor" shall mean Licensor and any individual or Legal Entity 77 | on behalf of whom a Contribution has been received by Licensor and 78 | subsequently incorporated within the Work. 79 | 80 | 2. Grant of Copyright License. Subject to the terms and conditions of 81 | this License, each Contributor hereby grants to You a perpetual, 82 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 83 | copyright license to reproduce, prepare Derivative Works of, 84 | publicly display, publicly perform, sublicense, and distribute the 85 | Work and such Derivative Works in Source or Object form. 86 | 87 | 3. Grant of Patent License. Subject to the terms and conditions of 88 | this License, each Contributor hereby grants to You a perpetual, 89 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 90 | (except as stated in this section) patent license to make, have made, 91 | use, offer to sell, sell, import, and otherwise transfer the Work, 92 | where such license applies only to those patent claims licensable 93 | by such Contributor that are necessarily infringed by their 94 | Contribution(s) alone or by combination of their Contribution(s) 95 | with the Work to which such Contribution(s) was submitted. If You 96 | institute patent litigation against any entity (including a 97 | cross-claim or counterclaim in a lawsuit) alleging that the Work 98 | or a Contribution incorporated within the Work constitutes direct 99 | or contributory patent infringement, then any patent licenses 100 | granted to You under this License for that Work shall terminate 101 | as of the date such litigation is filed. 102 | 103 | 4. Redistribution. You may reproduce and distribute copies of the 104 | Work or Derivative Works thereof in any medium, with or without 105 | modifications, and in Source or Object form, provided that You 106 | meet the following conditions: 107 | 108 | (a) You must give any other recipients of the Work or 109 | Derivative Works a copy of this License; and 110 | 111 | (b) You must cause any modified files to carry prominent notices 112 | stating that You changed the files; and 113 | 114 | (c) You must retain, in the Source form of any Derivative Works 115 | that You distribute, all copyright, patent, trademark, and 116 | attribution notices from the Source form of the Work, 117 | excluding those notices that do not pertain to any part of 118 | the Derivative Works; and 119 | 120 | (d) If the Work includes a "NOTICE" text file as part of its 121 | distribution, then any Derivative Works that You distribute must 122 | include a readable copy of the attribution notices contained 123 | within such NOTICE file, excluding those notices that do not 124 | pertain to any part of the Derivative Works, in at least one 125 | of the following places: within a NOTICE text file distributed 126 | as part of the Derivative Works; within the Source form or 127 | documentation, if provided along with the Derivative Works; or, 128 | within a display generated by the Derivative Works, if and 129 | wherever such third-party notices normally appear. The contents 130 | of the NOTICE file are for informational purposes only and 131 | do not modify the License. You may add Your own attribution 132 | notices within Derivative Works that You distribute, alongside 133 | or as an addendum to the NOTICE text from the Work, provided 134 | that such additional attribution notices cannot be construed 135 | as modifying the License. 136 | 137 | You may add Your own copyright statement to Your modifications and 138 | may provide additional or different license terms and conditions 139 | for use, reproduction, or distribution of Your modifications, or 140 | for any such Derivative Works as a whole, provided Your use, 141 | reproduction, and distribution of the Work otherwise complies with 142 | the conditions stated in this License. 143 | 144 | 5. Submission of Contributions. Unless You explicitly state otherwise, 145 | any Contribution intentionally submitted for inclusion in the Work 146 | by You to the Licensor shall be under the terms and conditions of 147 | this License, without any additional terms or conditions. 148 | Notwithstanding the above, nothing herein shall supersede or modify 149 | the terms of any separate license agreement you may have executed 150 | with Licensor regarding such Contributions. 151 | 152 | 6. Trademarks. This License does not grant permission to use the trade 153 | names, trademarks, service marks, or product names of the Licensor, 154 | except as required for reasonable and customary use in describing the 155 | origin of the Work and reproducing the content of the NOTICE file. 156 | 157 | 7. Disclaimer of Warranty. Unless required by applicable law or 158 | agreed to in writing, Licensor provides the Work (and each 159 | Contributor provides its Contributions) on an "AS IS" BASIS, 160 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 161 | implied, including, without limitation, any warranties or conditions 162 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 163 | PARTICULAR PURPOSE. You are solely responsible for determining the 164 | appropriateness of using or redistributing the Work and assume any 165 | risks associated with Your exercise of permissions under this License. 166 | 167 | 8. Limitation of Liability. In no event and under no legal theory, 168 | whether in tort (including negligence), contract, or otherwise, 169 | unless required by applicable law (such as deliberate and grossly 170 | negligent acts) or agreed to in writing, shall any Contributor be 171 | liable to You for damages, including any direct, indirect, special, 172 | incidental, or consequential damages of any character arising as a 173 | result of this License or out of the use or inability to use the 174 | Work (including but not limited to damages for loss of goodwill, 175 | work stoppage, computer failure or malfunction, or any and all 176 | other commercial damages or losses), even if such Contributor 177 | has been advised of the possibility of such damages. 178 | 179 | 9. Accepting Warranty or Additional Liability. While redistributing 180 | the Work or Derivative Works thereof, You may choose to offer, 181 | and charge a fee for, acceptance of support, warranty, indemnity, 182 | or other liability obligations and/or rights consistent with this 183 | License. However, in accepting such obligations, You may act only 184 | on Your own behalf and on Your sole responsibility, not on behalf 185 | of any other Contributor, and only if You agree to indemnify, 186 | defend, and hold each Contributor harmless for any liability 187 | incurred by, or claims asserted against, such Contributor by reason 188 | of your accepting any such warranty or additional liability. 189 | 190 | END OF TERMS AND CONDITIONS -------------------------------------------------------------------------------- /src/csscolorparser.js: -------------------------------------------------------------------------------- 1 | // (c) Dean McNamee , 2012. 2 | // 3 | // https://github.com/deanm/css-color-parser-js 4 | // 5 | // Permission is hereby granted, free of charge, to any person obtaining a copy 6 | // of this software and associated documentation files (the "Software"), to 7 | // deal in the Software without restriction, including without limitation the 8 | // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or 9 | // sell copies of the Software, and to permit persons to whom the Software is 10 | // furnished to do so, subject to the following conditions: 11 | // 12 | // The above copyright notice and this permission notice shall be included in 13 | // all copies or substantial portions of the Software. 14 | // 15 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING 20 | // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS 21 | // IN THE SOFTWARE. 22 | 23 | // http://www.w3.org/TR/css3-color/ 24 | var kCSSColorTable = { 25 | "transparent": [0,0,0,0], "aliceblue": [240,248,255,1], 26 | "antiquewhite": [250,235,215,1], "aqua": [0,255,255,1], 27 | "aquamarine": [127,255,212,1], "azure": [240,255,255,1], 28 | "beige": [245,245,220,1], "bisque": [255,228,196,1], 29 | "black": [0,0,0,1], "blanchedalmond": [255,235,205,1], 30 | "blue": [0,0,255,1], "blueviolet": [138,43,226,1], 31 | "brown": [165,42,42,1], "burlywood": [222,184,135,1], 32 | "cadetblue": [95,158,160,1], "chartreuse": [127,255,0,1], 33 | "chocolate": [210,105,30,1], "coral": [255,127,80,1], 34 | "cornflowerblue": [100,149,237,1], "cornsilk": [255,248,220,1], 35 | "crimson": [220,20,60,1], "cyan": [0,255,255,1], 36 | "darkblue": [0,0,139,1], "darkcyan": [0,139,139,1], 37 | "darkgoldenrod": [184,134,11,1], "darkgray": [169,169,169,1], 38 | "darkgreen": [0,100,0,1], "darkgrey": [169,169,169,1], 39 | "darkkhaki": [189,183,107,1], "darkmagenta": [139,0,139,1], 40 | "darkolivegreen": [85,107,47,1], "darkorange": [255,140,0,1], 41 | "darkorchid": [153,50,204,1], "darkred": [139,0,0,1], 42 | "darksalmon": [233,150,122,1], "darkseagreen": [143,188,143,1], 43 | "darkslateblue": [72,61,139,1], "darkslategray": [47,79,79,1], 44 | "darkslategrey": [47,79,79,1], "darkturquoise": [0,206,209,1], 45 | "darkviolet": [148,0,211,1], "deeppink": [255,20,147,1], 46 | "deepskyblue": [0,191,255,1], "dimgray": [105,105,105,1], 47 | "dimgrey": [105,105,105,1], "dodgerblue": [30,144,255,1], 48 | "firebrick": [178,34,34,1], "floralwhite": [255,250,240,1], 49 | "forestgreen": [34,139,34,1], "fuchsia": [255,0,255,1], 50 | "gainsboro": [220,220,220,1], "ghostwhite": [248,248,255,1], 51 | "gold": [255,215,0,1], "goldenrod": [218,165,32,1], 52 | "gray": [128,128,128,1], "green": [0,128,0,1], 53 | "greenyellow": [173,255,47,1], "grey": [128,128,128,1], 54 | "honeydew": [240,255,240,1], "hotpink": [255,105,180,1], 55 | "indianred": [205,92,92,1], "indigo": [75,0,130,1], 56 | "ivory": [255,255,240,1], "khaki": [240,230,140,1], 57 | "lavender": [230,230,250,1], "lavenderblush": [255,240,245,1], 58 | "lawngreen": [124,252,0,1], "lemonchiffon": [255,250,205,1], 59 | "lightblue": [173,216,230,1], "lightcoral": [240,128,128,1], 60 | "lightcyan": [224,255,255,1], "lightgoldenrodyellow": [250,250,210,1], 61 | "lightgray": [211,211,211,1], "lightgreen": [144,238,144,1], 62 | "lightgrey": [211,211,211,1], "lightpink": [255,182,193,1], 63 | "lightsalmon": [255,160,122,1], "lightseagreen": [32,178,170,1], 64 | "lightskyblue": [135,206,250,1], "lightslategray": [119,136,153,1], 65 | "lightslategrey": [119,136,153,1], "lightsteelblue": [176,196,222,1], 66 | "lightyellow": [255,255,224,1], "lime": [0,255,0,1], 67 | "limegreen": [50,205,50,1], "linen": [250,240,230,1], 68 | "magenta": [255,0,255,1], "maroon": [128,0,0,1], 69 | "mediumaquamarine": [102,205,170,1], "mediumblue": [0,0,205,1], 70 | "mediumorchid": [186,85,211,1], "mediumpurple": [147,112,219,1], 71 | "mediumseagreen": [60,179,113,1], "mediumslateblue": [123,104,238,1], 72 | "mediumspringgreen": [0,250,154,1], "mediumturquoise": [72,209,204,1], 73 | "mediumvioletred": [199,21,133,1], "midnightblue": [25,25,112,1], 74 | "mintcream": [245,255,250,1], "mistyrose": [255,228,225,1], 75 | "moccasin": [255,228,181,1], "navajowhite": [255,222,173,1], 76 | "navy": [0,0,128,1], "oldlace": [253,245,230,1], 77 | "olive": [128,128,0,1], "olivedrab": [107,142,35,1], 78 | "orange": [255,165,0,1], "orangered": [255,69,0,1], 79 | "orchid": [218,112,214,1], "palegoldenrod": [238,232,170,1], 80 | "palegreen": [152,251,152,1], "paleturquoise": [175,238,238,1], 81 | "palevioletred": [219,112,147,1], "papayawhip": [255,239,213,1], 82 | "peachpuff": [255,218,185,1], "peru": [205,133,63,1], 83 | "pink": [255,192,203,1], "plum": [221,160,221,1], 84 | "powderblue": [176,224,230,1], "purple": [128,0,128,1], 85 | "red": [255,0,0,1], "rosybrown": [188,143,143,1], 86 | "royalblue": [65,105,225,1], "saddlebrown": [139,69,19,1], 87 | "salmon": [250,128,114,1], "sandybrown": [244,164,96,1], 88 | "seagreen": [46,139,87,1], "seashell": [255,245,238,1], 89 | "sienna": [160,82,45,1], "silver": [192,192,192,1], 90 | "skyblue": [135,206,235,1], "slateblue": [106,90,205,1], 91 | "slategray": [112,128,144,1], "slategrey": [112,128,144,1], 92 | "snow": [255,250,250,1], "springgreen": [0,255,127,1], 93 | "steelblue": [70,130,180,1], "tan": [210,180,140,1], 94 | "teal": [0,128,128,1], "thistle": [216,191,216,1], 95 | "tomato": [255,99,71,1], "turquoise": [64,224,208,1], 96 | "violet": [238,130,238,1], "wheat": [245,222,179,1], 97 | "white": [255,255,255,1], "whitesmoke": [245,245,245,1], 98 | "yellow": [255,255,0,1], "yellowgreen": [154,205,50,1]} 99 | 100 | function clamp_css_byte(i) { // Clamp to integer 0 .. 255. 101 | i = Math.round(i); // Seems to be what Chrome does (vs truncation). 102 | return i < 0 ? 0 : i > 255 ? 255 : i; 103 | } 104 | 105 | function clamp_css_float(f) { // Clamp to float 0.0 .. 1.0. 106 | return f < 0 ? 0 : f > 1 ? 1 : f; 107 | } 108 | 109 | function parse_css_int(str) { // int or percentage. 110 | if (str[str.length - 1] === '%') 111 | return clamp_css_byte(parseFloat(str) / 100 * 255); 112 | return clamp_css_byte(parseInt(str)); 113 | } 114 | 115 | function parse_css_float(str) { // float or percentage. 116 | if (str[str.length - 1] === '%') 117 | return clamp_css_float(parseFloat(str) / 100); 118 | return clamp_css_float(parseFloat(str)); 119 | } 120 | 121 | function css_hue_to_rgb(m1, m2, h) { 122 | if (h < 0) h += 1; 123 | else if (h > 1) h -= 1; 124 | 125 | if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; 126 | if (h * 2 < 1) return m2; 127 | if (h * 3 < 2) return m1 + (m2 - m1) * (2/3 - h) * 6; 128 | return m1; 129 | } 130 | 131 | function parseCSSColor(css_str) { 132 | // Remove all whitespace, not compliant, but should just be more accepting. 133 | var str = css_str.replace(/ /g, '').toLowerCase(); 134 | 135 | // Color keywords (and transparent) lookup. 136 | if (str in kCSSColorTable) return kCSSColorTable[str].slice(); // dup. 137 | 138 | // #abc and #abc123 syntax. 139 | if (str[0] === '#') { 140 | if (str.length === 4) { 141 | var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. 142 | if (!(iv >= 0 && iv <= 0xfff)) return null; // Covers NaN. 143 | return [((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8), 144 | (iv & 0xf0) | ((iv & 0xf0) >> 4), 145 | (iv & 0xf) | ((iv & 0xf) << 4), 146 | 1]; 147 | } else if (str.length === 7) { 148 | var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. 149 | if (!(iv >= 0 && iv <= 0xffffff)) return null; // Covers NaN. 150 | return [(iv & 0xff0000) >> 16, 151 | (iv & 0xff00) >> 8, 152 | iv & 0xff, 153 | 1]; 154 | } 155 | 156 | return null; 157 | } 158 | 159 | var op = str.indexOf('('), ep = str.indexOf(')'); 160 | if (op !== -1 && ep + 1 === str.length) { 161 | var fname = str.substr(0, op); 162 | var params = str.substr(op+1, ep-(op+1)).split(','); 163 | var alpha = 1; // To allow case fallthrough. 164 | switch (fname) { 165 | case 'rgba': 166 | if (params.length !== 4) return null; 167 | alpha = parse_css_float(params.pop()); 168 | // Fall through. 169 | case 'rgb': 170 | if (params.length !== 3) return null; 171 | return [parse_css_int(params[0]), 172 | parse_css_int(params[1]), 173 | parse_css_int(params[2]), 174 | alpha]; 175 | case 'hsla': 176 | if (params.length !== 4) return null; 177 | alpha = parse_css_float(params.pop()); 178 | // Fall through. 179 | case 'hsl': 180 | if (params.length !== 3) return null; 181 | var h = (((parseFloat(params[0]) % 360) + 360) % 360) / 360; // 0 .. 1 182 | // NOTE(deanm): According to the CSS spec s/l should only be 183 | // percentages, but we don't bother and let float or percentage. 184 | var s = parse_css_float(params[1]); 185 | var l = parse_css_float(params[2]); 186 | var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; 187 | var m1 = l * 2 - m2; 188 | return [clamp_css_byte(css_hue_to_rgb(m1, m2, h+1/3) * 255), 189 | clamp_css_byte(css_hue_to_rgb(m1, m2, h) * 255), 190 | clamp_css_byte(css_hue_to_rgb(m1, m2, h-1/3) * 255), 191 | alpha]; 192 | default: 193 | return null; 194 | } 195 | } 196 | 197 | return null; 198 | } 199 | 200 | try { exports.parseCSSColor = parseCSSColor } catch(e) { } 201 | -------------------------------------------------------------------------------- /src/gm-library.js: -------------------------------------------------------------------------------- 1 | /* 2 | Copyright 2013 Adobe Systems Inc. 3 | 4 | Licensed under the Apache License, Version 2.0 (the "License"); 5 | you may not use this file except in compliance with the License. 6 | You may obtain a copy of the License at 7 | 8 | http://www.apache.org/licenses/LICENSE-2.0 9 | 10 | Unless required by applicable law or agreed to in writing, software 11 | distributed under the License is distributed on an "AS IS" BASIS, 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | See the License for the specific language governing permissions and limitations under the License. 14 | */ 15 | 16 | /* 17 | Gradient Maps support 18 | Author: Alan Greenblatt (blatt@adobe.com, @agreenblatt, blattchat.com) 19 | */ 20 | 21 | window.GradientMaps = function(scope) { 22 | function GradientMaps() { 23 | this.init(); 24 | } 25 | 26 | GradientMaps.prototype = { 27 | init: function() { 28 | }, 29 | 30 | generateID: function() { 31 | this.previousID = this.previousID + 1 || 0; 32 | return this.previousID; 33 | }, 34 | 35 | calcStopsArray: function(stopsDecl) { 36 | /* 37 | * Each stop consists of a color and an optional percentage or length 38 | * stops: [, ] 39 | * : color [ | ]? 40 | * 41 | * If the first color-stop does not have a length or percentage, it defaults to 0% 42 | * If the last color-stop does not have a length or percentage, it defaults to 100% 43 | * If a color-stop, other than the first or last, does not have a length or percentage, it is assigned the position half way between the previous and the next stop. 44 | * If a color-stop, other than the first or last, has a specified position less than the previous stop, its position is changed to be equal to the largest specified position of any prior color-stop. 45 | */ 46 | 47 | var matches = stopsDecl.match(/(((rgb|hsl)a?\(\d{1,3},\s*\d{1,3},\s*\d{1,3}(?:,\s*0?\.?\d+)?\)|\w+|#[0-9a-fA-F]{1,6})(\s+(0?\.\d+|\d{1,3}%))?)/g); 48 | 49 | var stopsDeclArr = stopsDecl.split(','); 50 | var stops = []; 51 | 52 | matches.forEach(function(colorStop) { 53 | var colorStopMatches = colorStop.match(/(?:((rgb|hsl)a?\(\d{1,3},\s*\d{1,3},\s*\d{1,3}(?:,\s*0?\.?\d+)?\)|\w+|#[0-9a-fA-F]{1,6})(\s+(?:0?\.\d+|\d{1,3}%))?)/); 54 | if (colorStopMatches && colorStopMatches.length >= 4) { 55 | posMatch = colorStopMatches[3]; 56 | stops.push({ 57 | color: parseCSSColor(colorStopMatches[1]), 58 | pos: posMatch ? parse_css_float(posMatch) * 100 : null 59 | }) 60 | } 61 | }); 62 | 63 | /* 64 | * Need to calculate the positions where they aren't specified. 65 | * In the case of the first and last stop, we may even have to add a new stop. 66 | * 67 | * Go through the array of stops, finding ones where the position is not specified. 68 | * Then, find the next specified position or terminate on the last stop. 69 | * Finally, evenly distribute the unspecified positions, with the first stop at 0 70 | * and the last stop at 100. 71 | */ 72 | 73 | if (stops.length >= 1) { 74 | // If the first stop's position is not specified, set it to 0. 75 | var stop = stops[0]; 76 | if (!stop.pos) 77 | stop.pos = 0; 78 | else 79 | stop.pos = Math.min(100, Math.max(0, stop.pos)); 80 | 81 | var currentPos = stop.pos; 82 | 83 | // If the last stop's position is not specified, set it to 100. 84 | stop = stops[stops.length-1]; 85 | if (!stop.pos) 86 | stop.pos = 100; 87 | else 88 | stop.pos = Math.min(100, Math.max(0, stop.pos)); 89 | 90 | // Make sure that all positions are in ascending order 91 | for (var i = 1; i < stops.length-1; i++) { 92 | stop = stops[i]; 93 | if (stop.pos && stop.pos < currentPos) 94 | stop.pos = currentPos; 95 | if (stop.pos > 100) stop.pos = 100; 96 | currentPos = stop.pos; 97 | } 98 | 99 | // Find any runs of unpositioned stops and calculate them 100 | var i = 1; 101 | while (i < (stops.length-1)) { 102 | if (!stops[i].pos) { 103 | // Find the next positioned stop. You'll always have at least the 104 | // last stop at 100. 105 | for (var j = i+1; j < stops.length; j++) { 106 | if (stops[j].pos) 107 | break; 108 | } 109 | 110 | var startPos = stops[i-1].pos; 111 | var endPos = stops[j].pos; 112 | var nStops = j - 1 + 1; 113 | 114 | var delta = Math.round((endPos - startPos) / nStops); 115 | while (i < j) { 116 | stops[i].pos = stops[i-1].pos + delta; 117 | i++; 118 | } 119 | } 120 | 121 | i++; 122 | } 123 | 124 | if (stops[0].pos != 0) { 125 | stops.unshift({ 126 | color: stops[0].color, 127 | pos: 0 128 | }); 129 | } 130 | 131 | if (stops[stops.length-1].pos != 100) { 132 | stops.push({ 133 | color: stops[stops.length-1].color, 134 | pos: 100 135 | }) 136 | } 137 | } 138 | 139 | return stops; 140 | }, 141 | 142 | findMatchingDistributedNSegs: function(stops) { 143 | var maxNumSegs = 100; 144 | var matched = false; 145 | for (var nSegs = 1; !matched && nSegs <= maxNumSegs; nSegs++) { 146 | var segSize = maxNumSegs / nSegs; 147 | matched = true; 148 | for (var i = 1; i < stops.length-1; i++) { 149 | var pos = stops[i].pos; 150 | if (pos < segSize) { 151 | matched = false; 152 | break; 153 | } 154 | var rem = pos % segSize; 155 | var maxDiff = 1.0; 156 | if (!(rem < maxDiff || (segSize - rem) < maxDiff)) { 157 | matched = false; 158 | break; 159 | } 160 | } 161 | 162 | if (matched) 163 | return nSegs; 164 | } 165 | 166 | return nSegs; 167 | }, 168 | 169 | calcDistributedColors: function(stops, nSegs) { 170 | var colors = [stops[0].color]; 171 | 172 | var segSize = 100 / nSegs; 173 | for (var i = 1; i < stops.length-1; i++) { 174 | var stop = stops[i]; 175 | var n = Math.round(stop.pos / segSize); 176 | colors[n] = stop.color; 177 | } 178 | 179 | colors[nSegs] = stops[stops.length-1].color; 180 | 181 | var i = 1; 182 | while (i < colors.length) { 183 | if (!colors[i]) { 184 | for (var j = i+1; j < colors.length; j++) { 185 | if (colors[j]) 186 | break; 187 | } 188 | 189 | // Need to evenly distribute colors stops from svgStop[i-1] to svgStop[j] 190 | 191 | var startColor = colors[i-1]; 192 | var r = startColor[0]; 193 | var g = startColor[1]; 194 | var b = startColor[2]; 195 | var a = startColor[3]; 196 | 197 | var endColor = colors[j]; 198 | 199 | var nSegs = j - i + 1; 200 | var dr = (endColor[0] - r) / nSegs; 201 | var dg = (endColor[1] - g) / nSegs; 202 | var db = (endColor[2] - b) / nSegs; 203 | var da = (endColor[3] - a) / nSegs; 204 | 205 | while (i < j) { 206 | r += dr; 207 | g += dg; 208 | b += db; 209 | a += da; 210 | colors[i] = [r, g, b, a]; 211 | i++; 212 | } 213 | } 214 | i++; 215 | } 216 | 217 | return colors; 218 | }, 219 | 220 | addElement: function(doc, parent, tagname, ns, attributes) { 221 | var elem = ns ? doc.createElementNS(ns, tagname) : doc.createElement(tagname); 222 | if (attributes) { 223 | Object.keys(attributes).forEach(function(key, index, keys) { 224 | elem.setAttribute(key, attributes[key]); 225 | }); 226 | //elem.setAttribute(attr.name, attr.value); 227 | } 228 | 229 | if (parent) parent.appendChild(elem); 230 | return elem; 231 | }, 232 | 233 | addSVGComponentTransferFilter: function(elem, colors) { 234 | var filter = null; 235 | var svg = null; 236 | var svgns = 'http://www.w3.org/2000/svg'; 237 | var filterID = elem.getAttribute('data-gradientmap-filter'); 238 | 239 | var svgIsNew = false; 240 | 241 | var doc = elem.ownerDocument; 242 | 243 | if (filterID) { 244 | filter = doc.getElementById(filterID); 245 | if (filter) { 246 | // Remove old component transfer function 247 | var componentTransfers = filter.getElementsByTagNameNS(svgns, 'feComponentTransfer'); 248 | if (componentTransfers) { 249 | for (var i = componentTransfers.length-1; i >= 0; --i) 250 | filter.removeChild(componentTransfers[i]); 251 | 252 | svg = filter.parentElement; 253 | } 254 | } 255 | } 256 | 257 | // The last thing to be set previously is 'svg'. If that is still null, that will handle any errors 258 | if (!svg) { 259 | var svg = this.addElement(doc, null, 'svg', svgns, { 260 | 'version': '1.1', 261 | 'width': 0, 262 | 'height': 0 263 | }); 264 | 265 | filterID = 'filter-' + this.generateID(); 266 | filter = this.addElement(doc, svg, 'filter', svgns, {'id': filterID}); 267 | elem.setAttribute('data-gradientmap-filter', filterID); 268 | 269 | // First, apply a color matrix to turn the source into a grayscale 270 | var colorMatrix = this.addElement(doc, filter, 'feColorMatrix', svgns, { 271 | 'type': 'matrix', 272 | 'values': '0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0', 273 | 'result': 'gray' 274 | }); 275 | 276 | svgIsNew = true; 277 | } 278 | 279 | // Now apply a component transfer to remap the colors 280 | var componentTransfer = this.addElement(doc, filter, 'feComponentTransfer', svgns, {'color-interpolation-filters': 'sRGB'}); 281 | 282 | var redTableValues = ""; 283 | var greenTableValues = ""; 284 | var blueTableValues = ""; 285 | var alphaTableValues = ""; 286 | 287 | colors.forEach(function(color, index, colors) { 288 | redTableValues += (color[0] / 255.0 + " "); 289 | greenTableValues += (color[1] / 255.0 + " "); 290 | blueTableValues += (color[2] / 255.0 + " "); 291 | alphaTableValues += (color[3] + " "); 292 | }); 293 | 294 | this.addElement(doc, componentTransfer, 'feFuncR', svgns, {'type': 'table', 'tableValues': redTableValues.trim()}); 295 | this.addElement(doc, componentTransfer, 'feFuncG', svgns, {'type': 'table', 'tableValues': greenTableValues.trim()}); 296 | this.addElement(doc, componentTransfer, 'feFuncB', svgns, {'type': 'table', 'tableValues': blueTableValues.trim()}); 297 | this.addElement(doc, componentTransfer, 'feFuncA', svgns, {'type': 'table', 'tableValues': alphaTableValues.trim()}); 298 | 299 | if (svgIsNew) 300 | elem.parentElement.insertBefore(svg, elem); 301 | 302 | var filterDecl = 'url(#' + filterID + ')'; 303 | elem.style['-webkit-filter'] = filterDecl; 304 | elem.style['filter'] = filterDecl; 305 | 306 | //elem.setAttribute('style', '-webkit-filter: url(#' + filterID + '); filter: url(#' + filterID + ')'); 307 | }, 308 | 309 | applyGradientMap: function(elem, gradient) { 310 | var stops = this.calcStopsArray(gradient); 311 | var nSegs = this.findMatchingDistributedNSegs(stops); 312 | var colors = this.calcDistributedColors(stops, nSegs); 313 | 314 | this.addSVGComponentTransferFilter(elem, colors); 315 | }, 316 | 317 | removeGradientMap: function(elem) { 318 | var filterID = elem.getAttribute('data-gradientmap-filter'); 319 | if (filterID) { 320 | var doc = elem.ownerDocument; 321 | var filter = doc.getElementById(filterID); 322 | if (filter) { 323 | var svg = filter.parentElement; 324 | svg.removeChild(filter); 325 | if (svg.childNodes.length <= 0) { 326 | var parent = svg.parentElement; 327 | parent.removeChild(svg); 328 | } 329 | } 330 | elem.removeAttribute('data-gradientmap-filter'); 331 | elem.style['-webkit-filter'] = ''; 332 | elem.style['filter'] = ''; 333 | } 334 | }, 335 | } 336 | 337 | return new GradientMaps(); 338 | }(window); 339 | --------------------------------------------------------------------------------