Search code examples
jquerydrawimagetodataurl

Set img src from data-src attribute


i'm trying to set img src attribute from data-src attribute for multiple images using jquery but the code does not work. Img src does not change.

Here's a link to see my code in action.

jQuery(document).ready(function($){
    $('.container figure.images').each(function(index, element){
  var thisImage = $(this);
  var canvas = thisImage.find("canvas").get(0);
  var ctx = canvas.getContext("2d");
  ctx.rect(298, 0, 984, 329);
  ctx.rect(0, 329, 1280, 514);
  ctx.clip();
  img = new Image();
  img.onload = function () {
    ctx.drawImage(this, 0, 0, img.width, img.height);
    var imgNew = canvas.toDataURL("image/png");
    thisImage.find("img").attr('src', imgNew);
  };
  img.src = thisImage.find("img").attr('data-src');
});
});
.container figure img {
  width: 100%;
  height: auto;
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<section class="platform">
      <div class="container">

        <figure class="images">
          <canvas width="1280" height="843" style="display: none"></canvas>
          <img src="#" data-src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" alt="description" />
        </figure>

        <figure class="images">
          <canvas width="1280" height="843" style="display: none"></canvas>
          <img src="#" data-src="https://www.dropbox.com/s/bl5yz4itgbo1ggl/2.jpg" alt="description" />
        </figure>

        <figure class="images">
          <canvas width="1280" height="843" style="display: none"></canvas>
          <img src="#" data-src="https://www.dropbox.com/s/bl5yz4itgbo1ggl/2.jpg" alt="description" />
        </figure>

      </div>
    </section>

Thank to all and have a great day.


Solution

  • There appear to be two issues that I can see:

    Dropbox is redirecting your download so that the data you're getting back is not an image, but a Dropbox HTML page.

    Despite that, I wasn't able to get your canvas drawing to work (it may be possible, but it didn't work for me). I was able to refactor it to insert a new img tag with the src set from the data-src. This would probably be most effective if you set the data-src on the .images element and then just didn't have a default canvas or img tag. You could do the same if you really wanted the width and height attributes as well.

    $(document).ready(function() {
        $('.container figure.images').each(function(i, e) {
        var url = $('img', e).attr('data-src');
        $(e).append($('<img>', { 'src': url }));
      });
    });
    

    I also changed one of your data-src values to "https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" to see that the img does work, just not with the Dropbox version.

    HTH