Javascript color picker. How can I display all 255x255x255 RGB values without making the browser crash?

So I'm not talking about the HTML element I want to make a JS color picker.

So far I created a HTML Canvas and added each RGB value possible and that failled since, well printing all 24bits is quite intensive.But I am confused how do I create an RGBA color picker in JS?

Surley all examples I've seen are not displaying all the RGB spectrum, how do they work? Is the an algorithm or way to display a RGB spectrum picker and be light on the browser?

Thanks.

2

1 Answer

Here's something to play with. A few things to note.

  1. I've leveraged the browser's ability to understand the hsl colour system to avoid writing a conversion between it and rgb.
  2. It's one-way. something-in --> rgb-out. You can't convert rgb to hsl so conveniently.
  3. redrawing on mousemove isn't what you'd want. You'd want to handle clicks on each canvas.
  4. I just used 360x100 since there are 360 deg in a circle and 100x100 since it avoid computing a percentage. Recalling that you need an input in the range of 0-360 and two inputs in the range 0-100..
"use strict";
window.addEventListener('load', onLoaded, false);
function onLoaded(evt)
{ let can = document.querySelector('canvas'); let ctx = can.getContext('2d'); for (let x=0; x<360; x++) { ctx.fillStyle = `hsl(${x}deg, 100%, 50%)`; ctx.fillRect(x,0,1,can.height); } can.addEventListener('mousemove', onMouseMove, false);
}
function onMouseMove(evt)
{ let can = this; let xPos = evt.offsetX; let yPos = evt.offsetY; let ctx = this.getContext('2d'); let imgData = ctx.getImageData(xPos,yPos,1,1); let r = imgData.data[0]; let g = imgData.data[1]; let b = imgData.data[2]; let tgt = document.getElementById('hovCol'); tgt.style.backgroundColor = `rgb(${r},${g},${b})`; drawSatLumCanvas(xPos);
}
function drawSatLumCanvas(hueDegrees)
{ let can = document.querySelectorAll('canvas')[1]; let ctx = can.getContext('2d'); for (var y=0; y<100; y++) { for (var x=0; x<100; x++) { ctx.fillStyle = `hsl(${hueDegrees}deg, ${x}%, ${100-y}%)`; ctx.fillRect(x,y,1,1); } }
}
.swatch
{ display: inline-block; height: 1em; width: 1em; border: solid 1px #888;
}
<body> <canvas width=360 height=100></canvas><br> Hovered: <span class='swatch' id='hovCol'></span><br> <canvas width=100 height=100 id='slCol'><canvas>
</body>

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like