A way to modify specific regions is by following these steps:
var imageData = ctx.getImageData(x, y, width, height);
Once the modifications are done, place the modified image back in its original position:
ctx.putImageData(imageData, x, y);
If you want to work with a single pixel at coordinates x/y:
var imageData = ctx.getImageData(x, y, 1, 1);
/// convert the pixel to grayscale
var gray = data[0] * 0.2126 + data[1] * 0.7152 +data[2] * 0.0722;
imageData.data[0] = gray; /// r
imageData.data[1] = gray; /// g
imageData.data[2] = gray; /// b
imageData.data[3] = 255; /// alpha
/// put the modified pixel back
ctx.putImageData(imageData, x, y);
For simple color changes, utilizing fillRect()
, rect()
, and fill()
for multiple rectangles would suffice. However, for more intricate modifications (as assumed here), extracting and working on regions individually can be beneficial.