title: JavaScript getImageData Canvas
body: <pre><code>// Set colour of light bulb
  function set_bulb_colour(img_id, rgb_colour) {
    var img = new Image();
  
    img.onload = function() {
      var canvas = document.createElement('canvas');
  
      canvas.width = img.width;
      canvas.height = img.height;
  
      var ctx = canvas.getContext('2d');
      ctx.drawImage(img, 0, 0);
  
      var image_data = ctx.getImageData(0, 0, canvas.width, canvas.height);
      var data = image_data.data;
  
      for (var i = 0; i &lt; data.length; i += 4) {
        if (data[i + 3] == 0) {
          continue;
        }
  
        // If the pixel is yellow set it to the new colour
        if (data[i] &gt; 200 &amp;&amp; data[i + 2] &lt; 100) {
          data[i] = rgb_colour[0];
          data[i + 1] = rgb_colour[1];
          data[i + 2] = rgb_colour[2];
        }
      }
  
      ctx.putImageData(image_data, 0, 0);
  
      $('img#living_room_light_emoji').attr('src', canvas.toDataURL());
    }
  
    img.src = 'images/light_bulb.png';
  }
  </code></pre>
  
  <p>I have a question about the code i have above if anyone knows the answer. The code works. It changes all the yellow pixels in a light bulb image to a rgb colour passed in. I get an object from <code>getImageData</code>. I then get the data calling <code>.data</code> on that. I modify the pixels in the <code>data</code> variable. But when i redraw the image using <code>putImageData</code>, i put the object <code>image_data</code> back in instead of the ‘data’ that i was modifing. How does that work, does the <code>data</code> variable somehow point to the object in <code>image_data</code>?</p>
  
  <p>So what im asking is, by reading that code it looks like you take a copy of <code>image_data</code>’s <code>data</code> by calling <code>.data</code> and store it in a variable called <code>data</code>. To me modifiying <code>data</code> would not modify <code>image_data</code>. But it does. How does this work? When you use <code>image_data</code> to redraw it has the modified <code>data</code>. Does <code>data</code> point to <code>image_data</code>? I know how you could make this happen in C but didn't think it would work like this in javascript</p>