title: Changing Image colour through Javascript
body: <p>I have been looking to change the colour of an image when a click event is used. </p>
  
  <p>I Came across this post, which the first and main response with the Mug works really well.</p>
  
  <p>However, I need to use class, rather than ID, as I need to change the colour of more than one image. When I change the code to getElementsByClassName, instead of byID, it no longer works.</p>
  
  <p>I of course change the ID=mug to class=mug.</p>
  
  <p>I can't see anywhere else in the code that would cause a problem, so any help would be appreciated. </p>
  
  <p>I can't post on the original so adding here. Original link is:
  <a href="https://stackoverflow.com/questions/9303757/how-to-change-color-of-an-image-using-jquery">How to change color of an image using jquery</a></p>
  
  <p>This is the code:</p>
  
  <pre><code>&lt;img src="mug.png" id="mug" width="25%" height="25%" onload="getPixels(this)" /&gt;
  &lt;input type="text" id="color" value="#6491ee" /&gt;
  &lt;input type="button" value="change color" onclick="changeColor()"&gt;
  
  &lt;script type="text/javascript"&gt;
      var mug = document.getElementById("mug");
      var canvas = document.createElement("canvas");
      var ctx = canvas.getContext("2d");
      var originalPixels = null;
      var currentPixels = null;
  
      function HexToRGB(Hex)
      {
          var Long = parseInt(Hex.replace(/^#/, ""), 16);
          return {
              R: (Long &gt;&gt;&gt; 16) &amp; 0xff,
              G: (Long &gt;&gt;&gt; 8) &amp; 0xff,
              B: Long &amp; 0xff
          };
      }
  
      function changeColor()
      {
          if(!originalPixels) return; // Check if image has loaded
          var newColor = HexToRGB(document.getElementById("color").value);
  
          for(var I = 0, L = originalPixels.data.length; I &lt; L; I += 4)
          {
              if(currentPixels.data[I + 3] &gt; 0)
              {
                  currentPixels.data[I] = originalPixels.data[I] / 255 * newColor.R;
                  currentPixels.data[I + 1] = originalPixels.data[I + 1] / 255 * newColor.G;
                  currentPixels.data[I + 2] = originalPixels.data[I + 2] / 255 * newColor.B;
              }
          }
  
          ctx.putImageData(currentPixels, 0, 0);
          mug.src = canvas.toDataURL("image/png");
      }
  
      function getPixels(img)
      {
          canvas.width = img.width;
          canvas.height = img.height;
  
          ctx.drawImage(img, 0, 0, img.naturalWidth, img.naturalHeight, 0, 0, img.width, img.height);
          originalPixels = ctx.getImageData(0, 0, img.width, img.height);
          currentPixels = ctx.getImageData(0, 0, img.width, img.height);
  
          img.onload = null;
      }
  &lt;/script&gt;
  </code></pre>
  
  <p>Thanks</p>