Do you also want to give your images a black and white effect using just JavaScript? So i will show you how to do that using a simple <canvas> and some beginner-level JavaScript . No libraries , no fancy tools justpure basic thing.
How to Convert an Image to Grayscale Using JavaScript.
We are going to make a tiny web application that loads an image onto canvas and then reads the pixel colors and then turns the image into black and white (Grayscale).
In JavaScript , we can use a <canvas> element to draw and edit images. Every image made of tiny dots called pixels. Each pixel is red,green,blue (RGB). To make an pixel grey we will set it to an average number which will remove all colors and give a black-and-white look.
HTML setup:-
<canvas id="myCanvas" width="300" height="300"></canvas>
Load and Draw the Image:-
<script> const canvas = document.getElementById("myCanvas"); const ctx = canvas.getContext("2d"); const img = new Image(); img.src = "photo.jpg"; img.onload = function() { ctx.drawImage(img, 0, 0, canvas.width, canvas.height); convertToGrayscale(); }; </script>
This code draws the image on the canvas.
Convert to Grayscale:-
<script> function convertToGrayscale() { const d = ctx.getImageData(0, 0, canvas.width, canvas.height); const p = d.data; for (let i = 0; i < p.length; i += 4) { let avg = (p[i] + p[i+1] + p[i+2]) / 3; p[i] = p[i+1] = p[i+2] = avg; } ctx.putImageData(d, 0, 0); } </script>
We set all three color channels to the same average , The result is a grayscale image.
Converting an image is really that easy just you should know about pixels and JavaScript and turning RBG values into average numbers.