Create Image Color Extractor Tool using HTML, CSS, JavaScript, and Vibrant.js

Faraz

By Faraz -

Master the art of color picking with Vibrant.js. This tutorial guides you through building a custom color extractor tool using HTML, CSS, and JavaScript.


Create Image Color Extractor Tool using HTML, CSS, JavaScript, and Vibrantjs.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

Welcome to the world of image color extraction! In this tutorial, we'll guide you through the process of creating a dynamic and customizable color palette generator using HTML, CSS, JavaScript, and the powerful Vibrant.js library.

Tools and Technologies

Before we dive in, ensure you have a code editor, a modern web browser, and a basic understanding of HTML, CSS, and JavaScript.

Setting Up the Project

Start by creating a new project folder. Set up your HTML, CSS, and JavaScript files. Link them together in your HTML file.

How to do it:

  1. Open your code editor.
  2. Create a new project folder.
  3. Add HTML, CSS, and JavaScript files.
  4. Link them in your HTML file using <link> and <script> tags.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our tool.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

Let's break down each part of the code:

1. <!DOCTYPE html>: This declaration specifies the HTML version being used, and in this case, it's HTML5.

2. <html lang="en">: The opening tag for the HTML document. The lang attribute is set to "en," indicating that the primary language is English.

3. <head>: Contains meta-information about the HTML document, such as character set, viewport settings, and links to external resources like stylesheets.

  • <meta charset="UTF-8">: Sets the character encoding to UTF-8, which is widely used for handling various characters and symbols.
  • <meta http-equiv="X-UA-Compatible" content="IE=edge">: Provides compatibility settings for Internet Explorer.
  • <meta name="viewport" content="width=device-width, initial-scale=1.0">: Configures the viewport settings for responsive design on various devices.
  • <title>Image Color Extractor</title>: Sets the title of the webpage, which is displayed in the browser's title bar or tab.
  • <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css">: Links to an external stylesheet (CSS) that resets default browser styles. It helps ensure consistent styling across different browsers.
  • <link rel="stylesheet" href="styles.css">: Links to another external stylesheet named "styles.css" for additional styling.

4. <body>: Contains the content of the HTML document, including the main structure and elements displayed on the webpage.

  • <div id="details">: A container for the main content of the webpage.
  • <h1>Vibrant Color Extractor</h1>: A heading indicating the purpose of the webpage.
  • <div id="image-upload-wrap">: A container for the image upload functionality.
  • <h3>Drag & drop your image here</h3>: A heading instructing users to drag and drop their image into the designated area.
  • <div class="file-upload-content">: A container for the content related to the uploaded image.
  • <div id="image"></div>: An empty container intended to display the uploaded image.
  • <div class="colors">: A container for displaying color information extracted from the image.
  • Color information is displayed in various <div> elements with class names such as colorVibrant, colorMuted, etc.
  • <button type="button" onclick="removeUpload()" class="remove-image">Try New Image</button>: A button triggering a JavaScript function (removeUpload()) to remove the uploaded image and allow the user to try a new one.

5. <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js'></script>: Links to the jQuery library, a JavaScript library that simplifies HTML document traversal and manipulation.

6. <script src='https://cdnjs.cloudflare.com/ajax/libs/vibrant.js/1.0.0/Vibrant.min.js'></script>: Links to the Vibrant.js library, a JavaScript library for extracting prominent colors from an image.

7. <script src="script.js"></script>: Links to an external JavaScript file named "script.js," containing custom JavaScript code for the webpage's functionality.

This is the basic structure of our Image color extractor tool using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the tool is in place, the next step is to add styling to the tool using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to style our tool.

1. Font Import:

  • The CSS code begins with an @import rule, which is used to import the "Open Sans" font from Google Fonts. This font is available in three weights: 400, 600, and 700. The imported font is intended for use in the later styling of the HTML elements.

2. Color Variables:

  • The :root selector is used to define global CSS variables that store various color values. These variables include primary, secondary, tertiary colors, card background color, and dark/light text colors. These color variables provide a centralized way to manage the color scheme of the entire stylesheet.

3. Body Styling:

  • The body selector is used to style the overall appearance of the webpage. It sets a linear gradient background and centers the content both horizontally and vertically. The 'Open Sans' font is specified as the default font family, and padding is applied to create spacing around the content.

4. Heading 1 Styling:

  • The h1 selector styles level 1 headings. It sets the font size, color, and margin. Additionally, it defines a bold font weight for these headings.

5. Image Upload Wrap Styling:

  • The #image-upload-wrap selector is used to style a container for image upload. It defines the font size, text alignment, border, and other styling attributes. The container is designed to have a dashed border with a certain color, and it changes its background color on hover.

6. Heading 3 Styling:

  • The h3 selector styles level 3 headings. It sets the margin, font weight, and creates additional spacing.

7. Button Styling:

  • The button selector is used to style button elements. It sets various properties such as padding, border radius, transition effects, font weight, and text styling. The button has a transparent background with a colored border, and it changes its background and text color on hover.

8. Image Styling:

  • The img selector styles all images on the webpage. It sets a maximum width of 55% to ensure responsive sizing.

9. Details Container Styling:

  • The #details selector styles a container named "details." It sets the background color, width, maximum width, padding, border-radius, and box-shadow to give it a card-like appearance. This container is intended for holding additional details on the webpage.

10. File Upload Input Styling:

  • The .file-upload-input class styles a hidden input element used for file uploads. It sets the position, width, height, opacity, and cursor properties to create a custom-styled file input.

11. Color Section Styling:

  • The .colors class styles a container for color swatches. It uses flexbox to arrange the color swatches in a row with space between them.

12. Individual Color Styling:

  • The .colors > div selector styles each individual color swatch. It sets the font size, font weight, text transform, and color for the text inside each swatch.

13. Color Hex Styling:

  • The .colorHex class styles the hex code associated with each color swatch. It defines the font size, text transform, letter spacing, and font weight.

14. Swatch Styling:

  • The .swatch class styles each color swatch individually. It sets the width, aspect ratio, border-radius, and margin to create a circular appearance.

15. Image Inside #image Container Styling:

  • The #image img selector styles images inside the container with the ID "image." It ensures the image takes up 100% width, maintains its aspect ratio, and has a border-radius for a rounded appearance.

16. File Upload Content Styling:

  • The .file-upload-content class styles a container for file upload content. It adjusts padding and uses flexbox to arrange the content in a column layout.

This will give our Image color extractor tool an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

@import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap');

:root {
    --color-primary: #1256CE;
    --color-secondary: #F8FAFF;
    --color-tertiary: #5388E8;
    --color-card: #fff;
    --color-text-dark: #404040;
    --color-text-light: #fff;
}

body {
  background: linear-gradient(to right, #8BC6EC 0%, #9599E2 100%);
	height: 100%;
  position: relative;
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: 'Open Sans', sans-serif;
	padding: 64px 0;
}

h1 {
    font-size: 24px;
    color: var(--color-text-dark);
    margin: 0 0 18px;
	font-weight: 700;
}

#image-upload-wrap {
    font-size: 14px;
    text-align: center;
    border: 2px dashed var(--color-tertiary);
    position: relative;
    border-radius: 12px;
    display: flex;
    flex-direction: column;
    align-items: center;
    color: var(--color-text-dark);
}
h3 {
/*    margin: 0 0 18px;*/
    margin: 48px 0;
	font-weight: 700;
    
}

#image-upload-wrap:hover {
    background-color: var(--color-secondary);
    cursor: pointer;
}

#image-upload-wrap:hover > button,
button:hover {
    background-color: var(--color-primary);
    color: var(--color-text-light);
    cursor: pointer;
}

button {
    padding: 16px 24px;
    border-radius: 8px;
    transition: all .2s ease;
    font-weight: 700;
    letter-spacing: 1px;
    text-transform: uppercase;
    outline: none;
    margin: 0;
    color: var(--color-primary);
    font-size: 14px;
    background: none;
    border: 2px solid var(--color-primary);
}

img {
    width: 55%;
}

#image {
    margin-bottom: 20px;
}

#details {
    background-color: var(--color-card);
    width: 80%;
    max-width: 600px;
    padding: 48px 48px 54px;
    height: auto;
    border-radius: 16px;
    box-shadow:
        0 2.8px 2.2px rgba(0, 0, 0, 0.034),
        0 6.7px 5.3px rgba(0, 0, 0, 0.048),
        0 12.5px 10px rgba(0, 0, 0, 0.06),
        0 22.3px 17.9px rgba(0, 0, 0, 0.072),
        0 41.8px 33.4px rgba(0, 0, 0, 0.086),
        0 100px 80px rgba(0, 0, 0, 0.12);
/*     margin: 48px 0; */
}

.file-upload-input {
    position: absolute;
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
    outline: none;
    opacity: 0;
    cursor: pointer;
}

.colors {
    width: 100%;
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    margin: 24px 0 48px;
}

.colors > div {
    display: flex;
    flex-direction: column;
    font-size: 12px;
    font-weight: 700;
    text-transform: uppercase;
    align-items: center;
    flex: 1;
    color: var(--color-text-dark);
    text-align: center;
}


.colorHex {
    font-size: 14px;
    text-transform: uppercase;
    letter-spacing: 1px;
    display: flex;
    flex-direction: column;
    font-weight: 700;
}

.swatch {
    width: 60%;
    aspect-ratio: 1/1;
    border-radius: 50%;
    margin: 12px 0;
}

#image img {
    width: 100%;
    height: auto;
    display: block;
	border-radius: 12px;
}

.file-upload-content {
    padding: 0;
    display: flex;
    flex-direction: column;
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript.

Let's break down the code:

1. Initialization Function:

  • The code begins with an immediately-invoked function expression (IIFE).
  • Inside the IIFE, the "ready!" message is logged to the console.
  • The content of elements with the class "file-upload-content" is hidden.

2. Variable Declarations:

  • Variables for dropZone, handleDragOver, and handleFileSelect are declared.
  • dropZone is assigned the DOM element with the ID "image-upload-wrap."

3. File Selection and Processing:

  • The handleFileSelect function is defined, which handles file selection and processing.
  • It prevents the default drag-and-drop behavior and retrieves the selected file.
  • A FileReader is used to read the file, and the progress function is defined to handle the file processing.
  • The processed image is displayed, and color information is extracted using the Vibrant library.
  • The extracted color information is applied to elements with specific classes for display.

4. Event Listeners:

  • Event listeners are added to the dropZone element for "dragover" and "drop" events, calling the corresponding functions (handleDragOver and handleFileSelect).

5. File Removal Function:

  • The removeUpload function is defined to reset the file input element and hide the file upload content.
  • It replaces the file input element with a cloned version, effectively clearing the selected file.
  • The display is updated to show the original image upload wrap.

6. Event Binding for Dragging Effects:

  • Event handlers are bound to the "dragover" and "dragleave" events on the element with the ID "image-upload-wrap."
  • These handlers add and remove a class, "image-dropping," to provide visual feedback during dragging.

Create a JavaScript file with the name script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

(function () {
	console.log("ready!");
	$(".file-upload-content").hide();

	var dropZone, handleDragOver, handleFileSelect;

	dropZone = document.getElementById("image-upload-wrap");
	handleFileSelect = function (event) {
		var data, f, files, parseFile, progress, reader;
		event.stopPropagation();
		event.preventDefault();
		files = event.dataTransfer.files;
		f = files[0];
		reader = new FileReader();

		progress = function (event) {
			var image, results;
			image = new Image();
			image.src = event.target.result;
			document.getElementById("image").innerHTML =
				"<img src='" + event.target.result + "' />";
			image.onload = function () {
				$(".file-upload-content").show();
				$("#image-upload-wrap").hide();
				var el, el1, swatch, swatches, vibrant, contrasting;
				vibrant = new Vibrant(image, 256, 1);
				swatches = vibrant.swatches();
				results = [];
				for (swatch in swatches) {
					if (swatches.hasOwnProperty(swatch) && swatches[swatch]) {
						results.push(
							(function () {
								var i, len, ref, ref1, results1;
								ref = document.querySelectorAll(".color" + swatch);
								ref1 = document.querySelectorAll(".hex" + swatch);
								results1 = [];
								for (i = 0, len = ref.length; i < len; i++) {
									el = ref[i];
									results1.push((el.style.backgroundColor = swatches[swatch].getHex()));
								}
								for (i = 0, len = ref1.length; i < len; i++) {
									el1 = ref1[i];
									results1.push((el1.innerHTML = swatches[swatch].getHex()));
								}
								return results1;
							})()
						);
					} else {
						results.push(void 0);
					}
				}
			};
			return results;
		};
		parseFile = function (theFile) {
			return progress;
		};
		reader.onload = parseFile(f);
		return (data = reader.readAsDataURL(f));
	};

	handleDragOver = function (event) {
		event.stopPropagation();
		event.preventDefault();
		return (event.dataTransfer.dropEffect = "copy");
	};

	dropZone.addEventListener("dragover", handleDragOver, false);
	dropZone.addEventListener("drop", handleFileSelect, false);
}.call(this));

function removeUpload() {
	$(".file-upload-input").replaceWith($(".file-upload-input").clone());
	$(".file-upload-content").hide();
	$("#image-upload-wrap").show();
}
$("#image-upload-wrap").bind("dragover", function () {
	$("#image-upload-wrap").addClass("image-dropping");
});
$("#image-upload-wrap").bind("dragleave", function () {
	$("#image-upload-wrap").removeClass("image-dropping");
});

Final Output:

Create Image Color Extractor Tool using HTML, CSS, JavaScript, and Vibrantjs.gif

Conclusion:

Congratulations! You've successfully created an image color extractor tool using HTML, CSS, JavaScript, and Vibrant.js. Explore further customization and integration possibilities to enhance your web development skills. Happy coding!

Code by: Jackie Zen

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺