title: Dynamically adjust text color based on background image
body: <p>I am working on a product that outputs images from users and the image information is overlayed on top of the aforementioned images. As you might imagine, the images require different text colors due to lightness/darkness. Is there a way to achieve this with JavaScript?</p>
  
  <p>EDIT: I found a similar question to mine and there was a solution given in a jsfiddle (<a href="http://jsfiddle.net/xLF38/818">http://jsfiddle.net/xLF38/818</a>). I am using jQuery for my site though. How would I convert the vanilla JavaScript to jQuery?</p>
  
  <pre><code>var rgb = getAverageRGB(document.getElementById('i'));
  document.body.style.backgroundColor = 'rgb(' + rgb.r + ',' + rgb.g + ',' + rgb.b + ')';
  
  function getAverageRGB(imgEl) {
  
      var blockSize = 5, // only visit every 5 pixels
          defaultRGB = {
              r: 0,
              g: 0,
              b: 0
          }, // for non-supporting envs
          canvas = document.createElement('canvas'),
          context = canvas.getContext &amp;&amp; canvas.getContext('2d'),
          data, width, height,
          i = -4,
          length,
          rgb = {
              r: 0,
              g: 0,
              b: 0
          },
          count = 0;
  
      if (!context) {
          return defaultRGB;
      }
  
      height = canvas.height = imgEl.naturalHeight || imgEl.offsetHeight || imgEl.height;
      width = canvas.width = imgEl.naturalWidth || imgEl.offsetWidth || imgEl.width;
  
      context.drawImage(imgEl, 0, 0);
  
      try {
          data = context.getImageData(0, 0, width, height);
      } catch (e) {
          /* security error, img on diff domain */
          alert('x');
          return defaultRGB;
      }
  
      length = data.data.length;
  
      while ((i += blockSize * 4) &lt; length) {
          ++count;
          rgb.r += data.data[i];
          rgb.g += data.data[i + 1];
          rgb.b += data.data[i + 2];
      }
  
      // ~~ used to floor values
      rgb.r = ~~ (rgb.r / count);
      rgb.g = ~~ (rgb.g / count);
      rgb.b = ~~ (rgb.b / count);
  
      return rgb;
  
  }
  </code></pre>