Building an HSL Color Wheel with Two Canvas Rendering Techniques
To create an HSL-based color wheel using Canvas, we can leverage iether small filled arcs acting as color dots or radial lines. Both methods rely on covnerting hue values to radiens and mapping lightness to the distance from the wheel's center.
Arc-Based Color Wheel
function renderHslWheelArcs(canvasId) {
const canvas = document.getElementById(canvasId);
if (!canvas) return;
const ctx = canvas.getContext('2d');
const wheelCenterX = canvas.width / 2;
const wheelCenterY = canvas.height / 2;
const wheelRadius = Math.min(wheelCenterX, wheelCenterY);
const minLightness = 50;
const maxLightness = 100;
const dotRadius = wheelRadius / ((maxLightness - minLightness + 1);
const hueRange = 360;
for (let hueVal = 0; hueVal <= hueRange; hueVal++) {
const radianHue = hueVal * Math.PI / 180;
for (let lightVal = minLightness; lightVal <= maxLightness; lightVal++) {
const hslColor = `hsl(${hueVal}, 100%, ${lightVal}%)`;
const distanceFromEdge = (maxLightness - lightVal) * dotRadius;
const dotX = wheelCenterX + distanceFromEdge * Math.cos(radianHue);
const dotY = wheelCenterY + distanceFromEdge * Math.sin(radianHue);
ctx.beginPath();
ctx.fillStyle = hslColor;
ctx.arc(dotX, dotY, dotRadius, 0, 2 * Math.PI);
ctx.fill();
}
}
}
Line-Based Color Wheel
function renderHslWheelLines(targetCanvasId) {
const targetCanvas = document.getElementById(targetCanvasId);
if (!targetCanvas) return;
const drawCtx = targetCanvas.getContext('2d');
const wheelX = targetCanvas.width / 2;
const wheelY = targetCanvas.height / 2;
const wheelRad = Math.min(wheelX, wheelY);
const lightStart = 50;
const lightEnd = 100;
const lineThickness = wheelRad / (lightEnd - lightStart);
for (let currentLight = lightStart; currentLight <= lightEnd; currentLight++) {
const offsetScale = (lightEnd - currentLight) * lineThickness;
for (let currentHue = 0; currentHue <= 360; currentHue++) {
const hueRad = currentHue * (Math.PI / 180);
const xOffset = offsetScale * Math.cos(hueRad);
const yOffset = offsetScale * Math.sin(hueRad);
const innerX = wheelX + xOffset;
const innerY = wheelY + yOffset;
const finalColor = `hsl(${currentHue}, 100%, ${currentLight}%)`;
drawCtx.beginPath();
drawCtx.strokeStyle = finalColor;
drawCtx.lineWidth = lineThickness;
drawCtx.moveTo(innerX, innerY);
drawCtx.lineTo(wheelX, wheelY);
drawCtx.stroke();
}
}
}