freecoding.school100% FREE · NO SIGNUP
Input HarborISSUE #34 of 46

canvas · pixel manipulation

FormaVSCaptain Invalid Input
Forma saysCanvas can read and rewrite raw pixels with getImageData/putImageData — the basis of filters and effects.

Beyond drawing shapes, canvas exposes the actual pixels. getImageData(x,y,w,h) returns a flat array where every four numbers are one pixel's red, green, blue, alpha (0-255). Edit that array and putImageData writes it back.

This is how invert, grayscale, and threshold filters work: loop the array four values at a time and transform each channel. It's CPU work, so for big images or live video, push it to a Web Worker or WebGL.

Power-ups you unlock

Captain Invalid Input attacks — common mistakes

Boss battleDraw something, then invert every pixel (255 minus each RGB channel) with get/putImageData.

Example code

<!doctype html>
<html><head><meta charset="utf-8"></head>
<body style="background:#06040d;display:grid;place-items:center;height:100vh;margin:0;gap:10px">
  <canvas id="c" width="240" height="140" style="border:1px solid #2a1d4a"></canvas>
  <button id="b" style="font:inherit;color:#b388ff;background:none;border:1px solid #b388ff;padding:6px 12px;border-radius:3px">invert pixels</button>
  <script>
    const cv=document.getElementById('c'), x=cv.getContext('2d');
    x.fillStyle='#b388ff'; x.fillRect(0,0,240,140);
    x.fillStyle='#8aff9d'; x.beginPath(); x.arc(120,70,45,0,Math.PI*2); x.fill();
    document.getElementById('b').onclick = () => {
      const d = x.getImageData(0,0,240,140);
      for(let i=0;i<d.data.length;i+=4){ d.data[i]=255-d.data[i]; d.data[i+1]=255-d.data[i+1]; d.data[i+2]=255-d.data[i+2]; }
      x.putImageData(d,0,0);
    };
  </script>
</body></html>
▶ Open the interactive comic issue
‹ Websockets · Bidirectional ChannelPicture · Srcset · Sizes · Responsive Images ›