Logo Dave LobosDave Lobos About

Crafting an RGB Color Picker with Vanilla JavaScript and HTML Canvas

This is an example of how to implement an RGB Color Picker on the browser using Vanilla JS, it demonstrates various fundamental concepts like element creation, event listening and basic canvas methods.

You can find the code for this widget on Codepen: https://codepen.io/davelobos/pen/qBozyXp

The HTML

There is not a lot of HTML, all we need is a div element (id="app") in which we will instert the different elements of the widget.

The CSS

We've set up a simple Grid layout for the elements of the widget, and we set the cursor property of the three (RGB) sliders to indicate that these can be dragged.

The JS

The JavaScript code is where everything happens. We add event listeners to the three sliders, each one of these represent one of the three color components: red, green and blue. When these sliders are dragged, the value for the corresponding color component will be set to a value between 0 and 255, depending on the position of the mouse pointer.