const ctx = canvas.getContext('2d');
const imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
const pixels = imageData.data;
// Uint8ClampedArray: [R, G, B, A, R, G, B, A, ...]
console.log("Total values:", pixels.length);
// width * height * 4
console.log("First pixel RGB:", pixels[0], pixels[1], pixels[2]);
for (let i = 0; i < pixels.length; i += 4) {
const r = pixels[i];
const g = pixels[i + 1];
const b = pixels[i + 2];
// Alpha (pixels[i + 3]) stays unchanged
const gray = Math.round((r + g + b) / 3);
pixels[i] = gray; // R
pixels[i + 1] = gray; // G
pixels[i + 2] = gray; // B
}
ctx.putImageData(imageData, 0, 0); // Write back to canvas
Clicking Grayscale → runs the filter → image turns grayscale!
Connect the loop to the button's click handler from Session 20.
console.time('grayscale');
// ... filter code ...
console.timeEnd('grayscale');
// "grayscale: 15ms" on a 1080p image
Try with different image sizes. How does the time scale?
Upload different images, apply grayscale, verify results look correct.
git switch -c feature/PIXELCRAFT-009-grayscale-filter
git add src/scripts/
git commit -m "Implement grayscale filter with pixel loop (PIXELCRAFT-009)"
git push origin feature/PIXELCRAFT-009-grayscale-filter
# PR → Review → Merge → Close ticket ✅
Time complexity O(n).
Your loop visits every pixel exactly once. For n pixels, it does n iterations — that's O(n), linear time.