Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3
Tags: html, css, javascript, development
Published: 2023-06-02 11:25:00

---
title: Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3
published: true
description: How to create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3
date: 2023-06-02 00:25:00 UTC
tags: html, css, javascript, development
canonical_url: https://www.ma-no.org/en/web-design/let-s-create-a-color-picker-from-scratch-with-html5-canvas-javascript-and-css3
cover_image: https://www.ma-no.org/cache/galleries/contents-731/960-400/selector-canvas-de-html5-t1-imppng.webp
# Use a ratio of 100:42 for best results.
# published_at: 2023-06-02 13:00 +0000
---

![Let's create a Color Picker from scratch with HTML5 Canvas, Javascript and CSS3](https://www.ma-no.org/cache/galleries/contents-731/960-400/selector-canvas-de-html5-t1-imppng.webp)


<p>HTML5 Canvas is a technology that allows developers to generate real-time graphics and animations using JavaScript. It provides a blank canvas on which graphical elements, such as lines, shapes, images and text, can be drawn and manipulated with great flexibility and control.
</p>
<p>Here are some key concepts about HTML5 Canvas:
</p>
<p>1. <strong>Canvas element</strong>: The 
  <code>&lt;canvas&gt;
  </code> element is the base of the canvas on which the graphics are drawn. It is defined by HTML tags and can be sized using the `width` and `height` attributes. All graphic elements are drawn within this canvas.
</p>
<p>2. <strong>Context: </strong>The context (`<em>context</em>`) is the object that provides methods and properties for drawing on the canvas. There are two types of context: <strong>2D</strong> and <strong>WebG</strong>L. For 2D graphics, the 2D context (`<em>context2d</em>`) is used, which is more common. To access the 2D context, you use the
  <code> getContext(&#39;2d&#39;)
  </code> method on the 
  <code>&lt;canvas&gt;
  </code> element.
</p>
<p>3. <strong>Coordinates and coordinate system</strong>: The Canvas canvas uses a coordinate system in which `(<em>0, 0</em>)` represents the upper left corner of the canvas and positive coordinates increase downwards and to the right. This means that the highest values of `x` are to the right and the highest values of `y` are to the bottom.
</p>
<p>4. <strong>Drawing methods</strong>: The 2D context provides a wide range of methods for drawing different graphical elements on the canvas, such as lines, rectangles, circles, curves, images and text. Some of the most common methods include 
  <code>fillRect()
  </code>, 
  <code>strokeRect()
  </code>, 
  <code>arc()
  </code>, 
  <code>drawImage()
  </code> y 
  <code>fillText()
  </code>.
</p>
<p>5. <strong>Styles and attributes</strong>: The 2D context also allows you to set styles and attributes for graphic elements. You can set stroke and fill colours, line thickness, typography and other attributes that affect the visual appearance of graphics.
</p>
<p>6. <strong>Animations</strong>: One of the advantages of HTML5 Canvas is its ability to create fluid and dynamic animations. This can be achieved by using techniques such as periodic updating of the canvas, the use of the 
  <code>requestAnimationFrame()
  </code> and the manipulation of the graphic elements in each frame.
</p>
<p>HTML5 Canvas offers a wide range of creative possibilities and is used in many areas, such as online games, data visualisations, interactive applications and generative graphics. It is a powerful tool for web development and gives developers complete control over the graphical representation in the browser.
</p>
<p>In this tutorial we are going to explain how to use the Canvas element to create a simple colour picker.
</p>
<p>We start with the basic HTML code of the page:
</p>
&nbsp;
<pre>
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot; /&gt;
&lt;title&gt;Colorpicker demo&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
</pre>
&nbsp;
<p>We go on to define some CSS styles for the elements on the page. Styles are set for the body, a header (h2) and a Google Fonts font called &quot;Open Sans&quot; is imported.
</p>
&nbsp;
<pre>
&lt;style&gt;
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
body {
margin: 0;
padding: 0;
background-color: #e6e6e6;
}
h2 {
background-color: #dbdbdb;
margin: 0;
margin-bottom: 15px;
padding: 10px;
font-family: &#39;Open Sans&#39;;
}
/* Additional CSS for page elements */
</pre>
&nbsp;
<p>We continue with our heading indicating the purpose of the colour picker.
</p>
&nbsp;
<pre>
&lt;h2&gt;Canvas Color Picker&lt;/h2&gt;
</pre>
&nbsp;
<p>Then we create the two elements that will display the selected colour in <strong>RGBA</strong> and <strong>HEX</strong> format: the identifiers <em>txtRgba</em> and <em>txtHex</em> will be used to update the values later from the JavaScript code.
</p>
<pre>
&lt;label for=&quot;color-input&quot; id=&quot;color-label&quot; style=&quot;background-color: red&quot;&gt;&lt;/label&gt;
&lt;input type=&quot;checkbox&quot; id=&quot;color-input&quot; checked&gt;&lt;/input&gt;
</pre>
&nbsp;
<p>Aqu&iacute; creamos una etiqueta 
  <code>&lt;label&gt;
  </code> con el identificador color-label. Esta etiqueta se utiliza como muestra visual del color seleccionado. Tambi&eacute;n hay un 
  <code>&lt;input&gt;
  </code> de tipo checkbox con el identificador <strong>color-input</strong>, que se utiliza para controlar la visibilidad del selector de color.
</p>
<p>Next we create a 
  <code>&lt;div&gt;
  </code> container with the <em>colour-picker</em> identifier, which contains two 
  <code>&lt;canvas&gt;
  </code> elements. The first 
  <code>&lt;canvas&gt;
  </code> with the colour-block identifier is used as the main canvas where the colour is selected. The second 
  <code>&lt;canvas&gt;
  </code> with the <em>colour-strip</em> identifier is used to display a colour strip to select the saturation component of the colour.
</p>
&nbsp;
<pre>
&lt;div id=&quot;color-picker&quot;&gt;
&lt;canvas id=&quot;color-block&quot; height=&quot;150&quot; width=&quot;150&quot;&gt;&lt;/canvas&gt;
&lt;canvas id=&quot;color-strip&quot; height=&quot;150&quot; width=&quot;30&quot;&gt;&lt;/canvas&gt;
&lt;/div&gt;
</pre>
&nbsp;
<p>Now the fun begins...
  <br />
  Let&#39;s see how our JavaScript works:
</p>
&nbsp;
<pre>
&lt;script type=&quot;text/javascript&quot;&gt;
// This is where the JavaScript code block begins
var colorBlock = document.getElementById(&#39;color-block&#39;);
var ctx1 = colorBlock.getContext(&#39;2d&#39;);
var width1 = colorBlock.width;
var height1 = colorBlock.height;
</pre>
&nbsp;
<p>
</p>
<p>These lines of code get the main canvas element with the identifier &quot;<em>colour-block</em>&quot; from the HTML document. Then, the 2d context of the canvas is fetched using 
  <code>getContext(&#39;2d&#39;)
  </code>. We also store the dimensions (width and height) of the canvas in the variables <em>width1</em> and <em>height1</em>. We continue:
</p>
&nbsp;
<pre>
var colorStrip = document.getElementById(&#39;color-strip&#39;);
var ctx2 = colorStrip.getContext(&#39;2d&#39;);
var width2 = colorStrip.width;
var height2 = colorStrip.height;
</pre>
&nbsp;
<p>As you can see, the code is similar to the previous one, but in this case they obtain the canvas element of the colour strip with the identifier &quot;<em>colour-strip</em>&quot;. The 2d context of the canvas is obtained and the dimensions are stored in the variables <em>width2</em> and <em>height2</em>.
</p>
<p>Now we have to get the HTML document elements with the identifiers &quot;<em>colour-labe</em>l&quot;, &quot;<em>txtRgba</em>&quot; and &quot;<em>txtHex</em>&quot; and we have to store them in corresponding variables. These elements are used to display and update the selected colour values.
</p>
&nbsp;
<pre>
var colorLabel = document.getElementById(&#39;color-label&#39;);
var txtRgba = document.getElementById(&#39;txtRgba&#39;);
var txtHex = document.getElementById(&#39;txtHex&#39;);
</pre>
&nbsp;
<p>Let&#39;s add the variables needed to track the position of the mouse on the canvas to control whether it is dragging or not: x and y store the mouse coordinates, drag indicates whether the mouse is dragging and rgbaColor stores the initial value of the colour in RGBA format (red, green, blue and transparency).
</p>
&nbsp;
<pre>
var x = 0;
var y = 0;
var drag = false;
var rgbaColor = &#39;rgba(255,0,0,1)&#39;;
</pre>
&nbsp;
<p>And now we define the colour gradients on the canvases. In the canvas <em>colourBlock</em>, we draw a rectangle that covers the whole canvas and then call the <em>fill</em> function
</p>
&nbsp;
<pre>
ctx1.rect(0, 0, width1, height1);
fillGradient();
ctx2.rect(0, 0, width2, height2);
var grd1 = ctx2.createLinearGradient(0, 0, 0, height1);
grd1.addColorStop(0, &#39;rgba(255, 0, 0, 1)&#39;);
grd1.addColorStop(0.17, &#39;rgba(255, 255, 0, 1)&#39;);
grd1.addColorStop(0.34, &#39;rgba(0, 255, 0, 1)&#39;);
grd1.addColorStop(0.51, &#39;rgba(0, 255, 255, 1)&#39;);
grd1.addColorStop(0.68, &#39;rgba(0, 0, 255, 1)&#39;);
grd1.addColorStop(0.85, &#39;rgba(255, 0, 255, 1)&#39;);
grd1.addColorStop(1, &#39;rgba(255, 0, 0, 1)&#39;);
ctx2.fillStyle = grd1;
ctx2.fill();
</pre>
&nbsp;
<p>We add the function that is executed when you click on the colour strip canvas (<em>colourStrip</em>) with the following characteristics: when you click, you have to get the coordinates (<em>offsetX and offsetY</em>) of the point where you clicked. Then, the pixel colour corresponding to those coordinates is obtained using 
  <code>getImageData()
  </code>. The result is stored in imageData, which is an object containing information about the RGBA components of the pixel. An rgbaColor string is constructed using these values and the 
  <code>fillGradient()
  </code> function is called to update the colour in the main canvas.
</p>
&nbsp;
<pre>
function click(e) {
x = e.offsetX;
y = e.offsetY;
var imageData = ctx2.getImageData(x, y, 1, 1).data;
rgbaColor = &#39;rgba(&#39; + imageData[0] + &#39;,&#39; + imageData[1] + &#39;,&#39; + imageData[2] + &#39;,1)&#39;;
fillGradient();
}
</pre>
&nbsp;
<p>We create the function 
  <code>fillGradient()
  </code> which draws the gradients on the main canvas (<em>colourBlock</em>) to represent the selected colour. First, the fill colour is set to ctx1 with the value of rgbaColor and a rectangle is drawn covering the whole canvas. Then, two linear gradients, grdWhite and grdBlack, are created using the canvas context of the colour strip (<em>ctx2</em>). These gradients are used to create a gradient effect on the main canvas, providing areas of black and white to adjust the brightness and contrast of the selected colour.
</p>
&nbsp;
<pre>
function fillGradient() {
ctx1.fillStyle = rgbaColor;
ctx1.fillRect(0, 0, width1, height1);
var grdWhite = ctx2.createLinearGradient(0, 0, width1, 0);
grdWhite.addColorStop(0, &#39;rgba(255,255,255,1)&#39;);
grdWhite.addColorStop(1, &#39;rgba(255,255,255,0)&#39;);
ctx1.fillStyle = grdWhite;
ctx1.fillRect(0, 0, width1, height1);
var grdBlack = ctx2.createLinearGradient(0, 0, 0, height1);
grdBlack.addColorStop(0, &#39;rgba(0,0,0,0)&#39;);
grdBlack.addColorStop(1, &#39;rgba(0,0,0,1)&#39;);
ctx1.fillStyle = grdBlack;
ctx1.fillRect(0, 0, width1, height1);
}
</pre>
&nbsp;
<p>The following functions are used to control the user&#39;s interaction with the main canvas (<strong>colourBlock</strong>). When the user presses the mouse button inside the canvas (<strong>mousedown</strong>), drag is set to true to indicate dragging. The 
  <code>changeColor()
  </code> function is called to update the selected colour.
</p>
<p>During mousemove, if drag is true, 
  <code>changeColor() 
  </code>is called to update the selected colour while dragging the mouse.
</p>
<p>When the mouse button is released inside the canvas (<strong>mouseup</strong>), drag is set to false to indicate that dragging is finished.
</p>
&nbsp;
<pre>
function mousedown(e) {
drag = true;
changeColor(e);
}
function mousemove(e) {
if (drag) {
changeColor(e);
}
}
function mouseup(e) {
drag = false;
}
</pre>
&nbsp;
<p>Let&#39;s go ahead with the code for the 
  <code>changeColor()
  </code> function used to update the selected colour when the user interacts with the main canvas. First, we get the coordinates of the point where the interaction occurred (<strong>offsetX and offsetY</strong>). Then, the corresponding pixel colour is obtained using 
  <code>getImageData() 
  </code>and the<em> rgbaColor</em> variable is updated.
</p>
<p>After that, the background colour of the colourLabel element is updated with the selected colour, the colour value is displayed in RGBA format in the txtRgba element and the colour is converted from RGBA to hexadecimal format using the 
  <code>rgbaToHex()
  </code> function. The result is displayed in the txtHex element and is also printed to the console.
</p>
&nbsp;
<pre>
function changeColor(e) {
x = e.offsetX;
y = e.offsetY;
var imageData = ctx1.getImageData(x, y, 1, 1).data;
rgbaColor = &#39;rgba(&#39; + imageData[0] + &#39;,&#39; + imageData[1] + &#39;,&#39; + imageData[2] + &#39;,1)&#39;;
colorLabel.style.backgroundColor = rgbaColor;
txtRgba.innerHTML = rgbaColor;
var hexColor = rgbaToHex(rgbaColor);
console.log(hexColor);
txtHex.innerHTML = hexColor;
}
</pre>
&nbsp;
<p>These next lines of code assign the event handlers to the canvas elements and the colour strip element. When the colour strip is clicked, the 
  <code>click()
  </code> function is executed. When the mouse is pressed, released or moved within the main canvas, the corresponding functions (
  <code>mousedown(), mouseup(), mousemove()
  </code>) are executed to control the interaction and update the selected colour.
</p>
<pre>
colorStrip.addEventListener(&quot;click&quot;, click, false);
colorBlock.addEventListener(&quot;mousedown&quot;, mousedown, false);
colorBlock.addEventListener(&quot;mouseup&quot;, mouseup, false);
colorBlock.addEventListener(&quot;mousemove&quot;, mousemove, false);
</pre>
&nbsp;
<p>The 
  <code>rgbaToHex() 
  </code>function converts a colour in <strong>RGBA</strong> format to hexadecimal format. First, the R, G, B and A component values of the RGBA colour are extracted using regular expressions. Then, the R, G and B values are converted to hexadecimal format using 
  <code>toString(16)
  </code> and 
  <code>padStart(2, &#39;0&#39;) 
  </code>to make sure they have two digits. Finally, the hexadecimal values are combined and the colour is returned in hexadecimal format.
</p>
&nbsp;
<pre>
function rgbaToHex(rgbaColor) {
var values = rgbaColor.match(/d+/g);
var r = parseInt(values[0]);
var g = parseInt(values[1]);
var b = parseInt(values[2]);
var a = parseFloat(values[3]);
var hexR = r.toString(16).padStart(2, &#39;0&#39;);
var hexG = g.toString(16).padStart(2, &#39;0&#39;);
var hexB = b.toString(16).padStart(2, &#39;0&#39;);
var hexColor = &#39;#&#39; + hexR + hexG + hexB;
return hexColor;
}
</pre>
&nbsp;
<p>Here is all the code:
</p>
&nbsp;
<pre>
&lt;!DOCTYPE html&gt;
&lt;html lang=&quot;en&quot;&gt;
&lt;head&gt;
&lt;meta charset=&quot;utf-8&quot; /&gt;
&lt;title&gt;Colorpicker demo&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;style&gt;
@import url(https://fonts.googleapis.com/css?family=Open+Sans);
body {
margin: 0;
padding: 0;
background-color: #e6e6e6;
}
h2 {
background-color: #dbdbdb;
margin: 0;
margin-bottom: 15px;
padding: 10px;
font-family: &#39;Open Sans&#39;;
}
#color-input {
display: none;
}
#color-label {
margin-left: 15px;
position: absolute;
height: 30px;
width: 50px;
} 
#color-input:checked ~ #color-picker {
opacity: 1;
}
#color-picker {
position: absolute;
left: 70px; 
background-color: white;
height: 150px;
width: 185px;
border: solid 1px #ccc;
opacity: 0;
padding: 5px;
}
canvas:hover {
cursor: crosshair;
}
&lt;/style&gt;
&lt;h2&gt;Canvas Color Picker&lt;/h2&gt;
&lt;div&gt;&lt;p&gt;Color in RGBA is: &lt;span id=&quot;txtRgba&quot;&gt;&lt;/span&gt; &lt;/p&gt;
&lt;div&gt;&lt;p&gt;Color in HEX is: &lt;span id=&quot;txtHex&quot;&gt;&lt;/span&gt; &lt;/p&gt;
&lt;/div&gt;
&lt;label for=&quot;color-input&quot; id=&quot;color-label&quot; style=&quot;background-color: red&quot;&gt;&lt;/label&gt;
&lt;input type=&quot;checkbox&quot; id=&quot;color-input&quot; checked&gt;&lt;/input&gt;
&lt;div id=&quot;color-picker&quot;&gt;
&lt;canvas id=&quot;color-block&quot; height=&quot;150&quot; width=&quot;150&quot;&gt;&lt;/canvas&gt;
&lt;canvas id=&quot;color-strip&quot; height=&quot;150&quot; width=&quot;30&quot;&gt;&lt;/canvas&gt;
&lt;/div&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
var colorBlock = document.getElementById(&#39;color-block&#39;);
var ctx1 = colorBlock.getContext(&#39;2d&#39;);
var width1 = colorBlock.width;
var height1 = colorBlock.height;
var colorStrip = document.getElementById(&#39;color-strip&#39;);
var ctx2 = colorStrip.getContext(&#39;2d&#39;);
var width2 = colorStrip.width;
var height2 = colorStrip.height;
var colorLabel = document.getElementById(&#39;color-label&#39;);
var txtRgba = document.getElementById(&#39;txtRgba&#39;);
var txtHex = document.getElementById(&#39;txtHex&#39;);
var x = 0;
var y = 0;
var drag = false;
var rgbaColor = &#39;rgba(255,0,0,1)&#39;;
ctx1.rect(0, 0, width1, height1);
fillGradient();
ctx2.rect(0, 0, width2, height2);
var grd1 = ctx2.createLinearGradient(0, 0, 0, height1);
grd1.addColorStop(0, &#39;rgba(255, 0, 0, 1)&#39;);
grd1.addColorStop(0.17, &#39;rgba(255, 255, 0, 1)&#39;);
grd1.addColorStop(0.34, &#39;rgba(0, 255, 0, 1)&#39;);
grd1.addColorStop(0.51, &#39;rgba(0, 255, 255, 1)&#39;);
grd1.addColorStop(0.68, &#39;rgba(0, 0, 255, 1)&#39;);
grd1.addColorStop(0.85, &#39;rgba(255, 0, 255, 1)&#39;);
grd1.addColorStop(1, &#39;rgba(255, 0, 0, 1)&#39;);
ctx2.fillStyle = grd1;
ctx2.fill();
function click(e) {
x = e.offsetX;
y = e.offsetY;
var imageData = ctx2.getImageData(x, y, 1, 1).data;
rgbaColor = &#39;rgba(&#39; + imageData[0] + &#39;,&#39; + imageData[1] + &#39;,&#39; + imageData[2] + &#39;,1)&#39;;
fillGradient();
}
function fillGradient() {
ctx1.fillStyle = rgbaColor;
ctx1.fillRect(0, 0, width1, height1);
var grdWhite = ctx2.createLinearGradient(0, 0, width1, 0);
grdWhite.addColorStop(0, &#39;rgba(255,255,255,1)&#39;);
grdWhite.addColorStop(1, &#39;rgba(255,255,255,0)&#39;);
ctx1.fillStyle = grdWhite;
ctx1.fillRect(0, 0, width1, height1);
var grdBlack = ctx2.createLinearGradient(0, 0, 0, height1);
grdBlack.addColorStop(0, &#39;rgba(0,0,0,0)&#39;);
grdBlack.addColorStop(1, &#39;rgba(0,0,0,1)&#39;);
ctx1.fillStyle = grdBlack;
ctx1.fillRect(0, 0, width1, height1);
}
function mousedown(e) {
drag = true;
changeColor(e);
}
function mousemove(e) {
if (drag) {
changeColor(e);
}
}
function mouseup(e) {
drag = false;
}
function changeColor(e) {
x = e.offsetX;
y = e.offsetY;
var imageData = ctx1.getImageData(x, y, 1, 1).data;
rgbaColor = &#39;rgba(&#39; + imageData[0] + &#39;,&#39; + imageData[1] + &#39;,&#39; + imageData[2] + &#39;,1)&#39;;
colorLabel.style.backgroundColor = rgbaColor;
txtRgba.innerHTML = rgbaColor;
var hexColor = rgbaToHex(rgbaColor);
console.log(hexColor);
txtHex.innerHTML = hexColor;
}
colorStrip.addEventListener(&quot;click&quot;, click, false);
colorBlock.addEventListener(&quot;mousedown&quot;, mousedown, false);
colorBlock.addEventListener(&quot;mouseup&quot;, mouseup, false);
colorBlock.addEventListener(&quot;mousemove&quot;, mousemove, false);
function rgbaToHex(rgbaColor) {
var values = rgbaColor.match(/d+/g);
var r = parseInt(values[0]);
var g = parseInt(values[1]);
var b = parseInt(values[2]);
var a = parseFloat(values[3]);
var hexR = r.toString(16).padStart(2, &#39;0&#39;);
var hexG = g.toString(16).padStart(2, &#39;0&#39;);
var hexB = b.toString(16).padStart(2, &#39;0&#39;);
var hexColor = &#39;#&#39; + hexR + hexG + hexB;
return hexColor;
}
&lt;/script&gt;
&lt;/body&gt;
&lt;/html&gt;
</pre>
&nbsp;
<p>I hope that this tutorial has demonstrated the great potential that exists in developing applications using Canvas. There are much more advanced applications, and even games are being developed using this technology. It is therefore a field worth exploring, as it offers the possibility to create amazing and surprising things.
</p>