Created
February 21, 2019 20:45
-
-
Save codedust/e1e4cd1f880ba30a464efc4c07c5ed6a to your computer and use it in GitHub Desktop.
Small demo to create a color gradient using javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<meta charset="utf-8"> | |
<script> | |
// convert decimal values to rgb hex color toRGBstring(255, 0, 0) => '#ff0000') | |
function toRGBstring(r, g, b) { | |
return '#' + (r<16?'0':'') + r.toString(16) + (g<16?'0':'') + g.toString(16) + (b<16?'0':'') + b.toString(16); | |
} | |
// convert rgb hex color to decimal values (e.g. parseRBGstring('#ff0000') => [255, 0, 0]) | |
function parseRBGstring(color) { | |
return [parseInt(color.substr(1,2), 16), parseInt(color.substr(3,2), 16), parseInt(color.substr(5,2), 16)]; | |
} | |
// create a color gradient between color1 and color2 | |
// usage: createColorGradient('#ff0000', '#00ff00', 7) | |
function createColorGradient(color1, color2, steps) { | |
color1 = parseRBGstring(color1); | |
color2 = parseRBGstring(color2); | |
var colors = []; | |
for (var i = 0; i < steps; i++) { | |
var clampedR = Math.round(color1[0] + (color2[0] - color1[0]) * i / (steps - 1)); | |
var clampedG = Math.round(color1[1] + (color2[1] - color1[1]) * i / (steps - 1)); | |
var clampedB = Math.round(color1[2] + (color2[2] - color1[2]) * i / (steps - 1)); | |
colors.push(toRGBstring(clampedR, clampedG, clampedB)); | |
} | |
return colors; | |
} | |
console.log('http://colorpeek.com/' + createColorGradient('#BEF954', '#FF5553', 7).join(',')); | |
</script> | |
see console (F12) | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment