grayscale image in canvas

Solutions on MaxInterview for grayscale image in canvas by the best coders in the world

showing results for - "grayscale image in canvas"
Payton
09 Jan 2021
1window.onload = function() {
2let canvas = document.getElementById("c");
3
4	  let ctx = canvas.getContext("2d");
5    canvas.width=50;
6    canvas.height=50;
7
8		let srcImg = document.getElementById("sof");
9		ctx.drawImage(srcImg, 0, 0, ctx.canvas.width, ctx.canvas.height);
10		let imgData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
11		let pixels = imgData.data;
12		for (var i = 0; i < pixels.length; i += 4) {
13		  
14		let lightness = parseInt((pixels[i] + pixels[i + 1] + pixels[i + 2])/3);
15    
16		  pixels[i] = lightness; 
17		  pixels[i + 1] = lightness; 
18		  pixels[i + 2] = lightness; 
19		}
20		ctx.putImageData(imgData, 0, 0);
21	  }