title: JS - How to turn Image object into grayscale and display it
body: <p>Basically, when a button is clicked, it'll tell the mobile device to go to the camera. Once the camera takes a picture, it'll give me the image data (is it called the data URL?). This is my code to handle it:</p>
  
  <pre><code>var imagesrc = "data:image/jpeg;base64," + imageData;
  
  var myimage = new Image(500, 500);
  myimage.src = imagesrc;            &lt;---- to populate the object with the colored image
  myimage.src = grayscale(myimage);  &lt;---- here I set it to the grayscale image
  </code></pre>
  
  <p>I want to call a method called <code>grayscale()</code> and make it return the image that's been turned into grayscale. I tried this:</p>
  
  <pre><code>function grayscale(image){
      var canvasContext = canvas.getContext('2d');
      var imgW = image.width;
      var imgH = image.height;
      canvas.width = imgW;
      canvas.height = imgH;
  
      canvasContext.drawImage(image, 0, 0);
  
      var imgPixels = canvasContext.getImageData(0, 0, imgW, imgH);
  
  
      for(&gt;var y = 0; y &lt; imgPixels.height; y++){
          for(&gt;var x = 0; x &lt; imgPixels.width; x++){
            var i = (y * 4) * imgPixels.width + x * 4;
            var avg = (imgPixels.data[i] + imgPixels.data[i + 1] + imgPixels.data[i + 2]) / 3;
            imgPixels.data[i] = avg;
            imgPixels.data[i + 1] = avg;
            imgPixels.data[i + 2] = avg;
          }
      }
  
      canvasContext.putImageData(imgPixels, 0, 0, 0, 0, imgPixels.width, imgPixels.height);
  
      dataurl = canvas.toDataURL();
      var newimg = "data:image/jpeg;base64," + dataurl;
      return newimg;
  }
  </code></pre>
  
  <p>But for some reason it doesn't work. It just doesn't display the grayscale image. I got the for loop code online and tweaked it.</p>