Created
April 1, 2023 11:42
-
-
Save emnh/b0d4108681f6a0cdffd813e769b4671d to your computer and use it in GitHub Desktop.
Concentric Rainbow Canvas
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
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>Concentric Rainbow Canvas</title> | |
<style> | |
canvas { | |
border: 1px solid black; | |
} | |
</style> | |
</head> | |
<body> | |
<canvas id="rainbowCanvas"></canvas> | |
<script> | |
document.body.style.overflow = 'hidden'; | |
const canvas = document.getElementById('rainbowCanvas'); | |
const context = canvas.getContext('2d'); | |
// Define the rainbow colors | |
const rainbowColors = [ | |
'#000000', // White | |
'#FF0000', // Red | |
'#FF7F00', // Orange | |
'#FFFF00', // Yellow | |
'#00FF00', // Green | |
'#0000FF', // Blue | |
'#4B0082', // Indigo | |
'#9400D3', // Violet | |
]; | |
// Set the canvas dimensions | |
canvas.width = window.innerWidth; | |
canvas.height = window.innerHeight; | |
context.fillStyle = "black"; // set the fill color to blue | |
context.fillRect(0, 0, canvas.width, canvas.height); // draw a rectangle covering the entire canvas | |
// Create a radial gradient that interpolates between the rainbow colors | |
const gradient = context.createRadialGradient( | |
canvas.width / 2, canvas.height / 2, 0, | |
canvas.width / 2, canvas.height / 2, canvas.height / 2 | |
); | |
const step = 1 / rainbowColors.length; | |
for (let i = 0; i < rainbowColors.length; i++) { | |
gradient.addColorStop(i * step, rainbowColors[i]); | |
} | |
// Draw the concentric half-circles with the gradient fill | |
const halfCircleRadius = canvas.height / rainbowColors.length; | |
const centerX = canvas.width / 2; | |
const centerY = canvas.height / 1; | |
for (let i = rainbowColors.length - 1; i >= 0; i--) { | |
const irev = rainbowColors.length - i - 1; | |
const start = 45 * irev; | |
const radius = halfCircleRadius * (i + 1) + start; | |
const startAngle = Math.PI; | |
const endAngle = 2 * Math.PI; | |
context.beginPath(); | |
context.arc(centerX, centerY, radius, startAngle, endAngle); | |
const gradientClone = context.createRadialGradient( | |
centerX, centerY, halfCircleRadius * i + start, | |
centerX, centerY, halfCircleRadius * (i + 1) + start | |
); | |
for (let j = 0; j <= 1; j++) { | |
const colorStop = j; // * step; | |
gradientClone.addColorStop(colorStop, rainbowColors[(i + j) % rainbowColors.length]); | |
} | |
context.fillStyle = gradientClone; | |
context.fill(); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment