I'm in the process of developing a filter for canvas that will generate a monochrome version of an image. The approach involves drawing the image, then going through its pixel data to convert the RGB values to shades of gray before placing it back on the canvas. I could use some guidance on how to achieve the conversion from RGB to grayscale. A JavaScript solution would be ideal.
Here's my current code:
function toGray(vals) {
var r = vals[0]
var g = vals[1]
var b = vals[2]
// Implement logic to return gray shade
}
function filter() {
var c = document.getElementById("canvas1");
var ctx = c.getContext("2d");
var img = document.createElement('img')
img.src = 'shaq.png'
img.onload = function() {
ctx.drawImage(img, 0, 0, c.width, c.height);
var imgData = ctx.getImageData(0, 0, c.width, c.height);
var i;
for (i = 0; i < imgData.data.length; i += 4) {
var rgblist = [imgData.data[i], imgData.data[i+1], imgData.data[i+2]]
var filtered = toGray(rgblist)
imgData.data[i] = filtered[0]
imgData.data[i+1] = filtered[1]
imgData.data[i+2] = filtered[2]
}
ctx.putImageData(imgData, 0, 0);
}
}
canvas {
position: absolute;
bottom: 10px;
left: 0;
width: 100vw;
height: 100vh;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>filter</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<canvas id="canvas1"></canvas>
<script src="codes.js"></script>
<script src="filter.js"></script>
<script src="script.js"></script>
</body>
</html>