Skip to content

Instantly share code, notes, and snippets.

@ccurtin
Created December 17, 2020 19:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ccurtin/bebad027eca32d1280649628059f93bc to your computer and use it in GitHub Desktop.
Save ccurtin/bebad027eca32d1280649628059f93bc to your computer and use it in GitHub Desktop.
Animated Canvas Gradient Background
const animatedCanvasGradient = () => {
useEffect(() => {
animateCanvas('canvas')
}, [])
return (
<canvas
id="canvas"
width="26"
height="26"
style={{
width: '100%',
height: '100%',
position: 'absolute',
zIndex: 1,
}}
/>
)
}
const animateCanvas = (canvasId) => {
const canvasElement = document.getElementById(canvasId)
if (!canvasElement) {
return
}
const canvas = canvasElement.getContext('2d')
const col = (x, y, r, g, b) => {
canvas.fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')'
canvas.fillRect(x, y, 1, 1)
}
const R = (x, y, t) => {
return Math.floor(47 + 6 * Math.cos((x * x - y * y) / 200 + t))
}
const G = (x, y, t) => {
return Math.floor(
147 +
24 *
Math.sin((x * x * Math.cos(t / 0.6) + y * y * Math.sin(t / 3)) / 600)
)
}
const B = (x, y, t) => {
return Math.floor(
185 +
28 *
Math.sin(
6 * Math.sin(t / 3) +
((x - 100) * (x - 100) + (y - 100) * (y - 100)) / 2000
)
)
}
let time = 0
var start = () => {
for (let x = 0; x <= 100; x++) {
for (let y = 0; y <= 100; y++) {
col(x, y, R(x, y, time), G(x, y, time), B(x, y, time))
}
}
time = time + 0.038
window.requestAnimationFrame(start)
}
start()
}
const animateCanvas = (canvasId) => {
    const canvasElement = document.getElementById(canvasId)
    if (!canvasElement) {
      return
    }
    const canvas = canvasElement.getContext('2d')
    const col = (x, y, r, g, b) => {
      canvas.fillStyle = 'rgb(' + r + ',' + g + ',' + b + ')'
      canvas.fillRect(x, y, 1, 1)
    }
    const R = (x, y, t) => {
      return Math.floor(47 + 6 * Math.cos((x * x - y * y) / 200 + t))
    }
  
    const G = (x, y, t) => {
      return Math.floor(
        147 +
          24 *
            Math.sin((x * x * Math.cos(t / 0.6) + y * y * Math.sin(t / 3)) / 600)
      )
    }
  
    const B = (x, y, t) => {
      return Math.floor(
        185 +
          28 *
            Math.sin(
              6 * Math.sin(t / 3) +
                ((x - 100) * (x - 100) + (y - 100) * (y - 100)) / 2000
            )
      )
    }
  
    let time = 0
  
    var start = () => {
      for (let x = 0; x <= 100; x++) {
        for (let y = 0; y <= 100; y++) {
          col(x, y, R(x, y, time), G(x, y, time), B(x, y, time))
        }
      }
      time = time + 0.038
      window.requestAnimationFrame(start)
    }
  
    start()
  }
<canvas
  id="canvas"
  width="26"
  height="26"
  style={{
    width: '100%',
    height: '100%',
    position: 'absolute',
    zIndex: 1,
  }}
/>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment