Created
January 8, 2023 02:10
-
-
Save ethndotsh/dbf854e18449be0b99957127b68ad915 to your computer and use it in GitHub Desktop.
Generate a random gradient - using Vercel OG
This file contains 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
import { ImageResponse } from "@vercel/og"; | |
import random from "random-seed"; | |
export const config = { | |
runtime: "edge", | |
}; | |
function hslToHex(h, s, l) { | |
l /= 100; | |
const a = (s * Math.min(l, 1 - l)) / 100; | |
const f = (n) => { | |
const k = (n + h / 30) % 12; | |
const color = l - a * Math.max(Math.min(k - 3, 9 - k, 1), -1); | |
return Math.round(255 * color) | |
.toString(16) | |
.padStart(2, "0"); // convert to Hex and prefix "0" if needed | |
}; | |
return `#${f(0)}${f(8)}${f(4)}`; | |
} | |
function splitString(string) { | |
const middle = Math.ceil(string.length / 2); | |
const s1 = string.slice(0, middle); | |
const s2 = string.slice(middle); | |
return [s1, s2]; | |
} | |
const randomColor = (seed = "aa") => { | |
const generator = random.create(seed); | |
const randomInt = (min, max) => { | |
return Math.floor(generator.random() * (max - min + 1)) + min; | |
}; | |
const h = randomInt(0, 360); | |
const s = randomInt(42, 98); | |
const l = randomInt(40, 80); | |
return hslToHex(h, s, l); | |
// return `hsl(${h},${s}%,${l}%)`; | |
}; | |
const sampleFromSeed = (array, seed = "aa") => { | |
const generator = random.create(seed); | |
return array[Math.floor(generator.random() * array.length)]; | |
}; | |
export default function handler(req) { | |
try { | |
const { searchParams } = new URL(req.url); | |
const hasSeed = searchParams.has("seed"); | |
const seed = hasSeed ? searchParams.get("seed")?.slice(0, 100) : "mother"; // idk it looks pretty | |
const [firstHalf, secondHalf] = splitString(seed); | |
const color1 = randomColor(firstHalf); | |
const color2 = randomColor(secondHalf); | |
return new ImageResponse( | |
( | |
<div | |
style={{ | |
backgroundImage: `linear-gradient(135deg, ${color1}, ${color2})`, | |
width: "100%", | |
height: "100%", | |
display: "flex", | |
textAlign: "center", | |
alignItems: "center", | |
justifyContent: "center", | |
}} | |
></div> | |
), | |
{ | |
width: 250, | |
height: 250, | |
} | |
); | |
} catch (error) { | |
console.log(`${e.message}`); | |
return new Response(`Failed to generate the image`, { | |
status: 500, | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment