Gradient colors

by Arjan Haverkamp

HTML

Calculate all colors in a gradient.

JavaScript

const getColors = (colorStops, amount) => {
	const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  
	canvas.width = amount
  canvas.height = 1
  
  const gradient = ctx.createLinearGradient(0, 0, amount, 1)
  
  colorStops.forEach((stop) => {
  	const split = stop.split(' ')
    const offset = parseFloat(split.pop()) / 100
    const color = split.join(' ')
    gradient.addColorStop(offset, color)
  })
  
  ctx.fillStyle = gradient
  ctx.fillRect(0, 0, amount, 1)
  
  const pixelData = Array.from(ctx.getImageData(0, 0, amount, 1).data)
  const colors = []
  
  for(let i = 0; i < amount; i++) {
  	const [r, g, b, a] = pixelData.splice(0, 4)
    colors.push(`rgba(${r}, ${g}, ${b}, ${a / 255})`)
  }
  
  return colors
}

const colors = getColors([
  "#f00 10%", 
  "rgba(255, 255, 255, 0.87) 31%", 
  "rgba(14, 206, 73, 1) 64%", 
  "hsl(180, 50%, 50%) 85%",
  "#00f 92%",
  "#000 100%"
], 199)

console.log(colors)