image to canvas greyscale code example

Example: grayscale image in canvas

window.onload = function() {
let canvas = document.getElementById("c");

	  let ctx = canvas.getContext("2d");
    canvas.width=50;
    canvas.height=50;

		let srcImg = document.getElementById("sof");
		ctx.drawImage(srcImg, 0, 0, ctx.canvas.width, ctx.canvas.height);
		let imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
		let pixels = imgData.data;
		for (var i = 0; i < pixels.length; i += 4) {
		  
		let lightness = parseInt((pixels[i] + pixels[i + 1] + pixels[i + 2])/3);
    
		  pixels[i] = lightness; 
		  pixels[i + 1] = lightness; 
		  pixels[i + 2] = lightness; 
		}
		ctx.putImageData(imgData, 0, 0);
	  }