Skip to content

Instantly share code, notes, and snippets.

@LiamPerson
Last active November 4, 2022 05:53
Show Gist options
  • Save LiamPerson/0422e20138fd64830e3f52e6a78800f0 to your computer and use it in GitHub Desktop.
Save LiamPerson/0422e20138fd64830e3f52e6a78800f0 to your computer and use it in GitHub Desktop.
Generate a css striped background using javascript.
/**
* Generates a linear-gradient css function to use with the css background property to display a stripes.
* @param {String} col1 the first colour.
* @param {String} col2 the second colour.
* @param {String} angle what angle the chevron should appear at
* @param {Number} iterations how many stripes you want. 7 = 4 col1, 3 col2
* @returns {String}
* @example generateStripes("rgba(255, 255, 255, .2)", "white", "-45deg", 40) // returns "linear-gradient(-45deg,rgba(255, 255, 255, .2) 16.666666666666668%,rgba(255, 255, 255, .2) 16.666666666666668%, rgba(255, 255, 255, .2) 33.333333333333336% ,white 33.333333333333336%, white 50% ,rgba(255, 255, 255, .2) 50%, rgba(255, 255, 255, .2) 66.66666666666667% ,white 66.66666666666667%, white 83.33333333333334% ,rgba(255, 255, 255, .2) 83.33333333333334%, rgba(255, 255, 255, .2) 100% )"
*/
export const generateStripes = (col1, col2, angle, iterations) => {
iterations += 1
const percentageIncrements = 100 / iterations;
let gradientInterior = `${col1} ${percentageIncrements}%`;
for(let i = 1; i < iterations; i++) {
gradientInterior += `,${i % 2 ? col1 : col2} ${percentageIncrements * i}%, ${i % 2 ? col1 : col2} ${percentageIncrements * (i + 1)}% `;
}
return `linear-gradient(${angle},${gradientInterior})`;
}
@LiamPerson
Copy link
Author

Example of generateStripes("rgba(255, 255, 255, .2)", "white", "-45deg", 20)
image

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment