Rob Kwasowski
Rob Kwasowski

Reputation: 2780

JS: Canvas loop not working

I'm trying to enlarge two images with a loop but keep them pixelated by putting them onto a canvas. I'm doing this because on Edge there's no way to render images as pixelated and I wanted to make my website compatible with Edge. But it's not working. Can anyone see where I'm going wrong?

$('img.zoom').each(function(e){
      var canvas = document.getElementById('c1');
      var entry = $('img.zoom').eq(e);

      var width = entry[0].clientWidth;
      var height = entry[0].clientHeight;

      $('#c1').attr({'width': width, 'height': height});
      context = canvas.getContext('2d');
      base_image = new Image();
      context.imageSmoothingEnabled = false;
      base_image.src = entry[0].src;
      base_image.onload = function() {
        context.drawImage(base_image, 0, 0, width, height);
        entry[0].src = canvas.toDataURL();
      }
    });
#c1 {display:none}

#a, #b {
  width: 100px;
  height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="c1"></canvas>
<img id='a' src='https://i.imgur.com/cANXGWL.jpg' class='zoom'>
<img id='b' src='https://i.imgur.com/j6sXsVe.jpg' class='zoom'>

Upvotes: 1

Views: 79

Answers (1)

Kavian K.
Kavian K.

Reputation: 1370

Do this:

$( '.zoom' ).each( function() {
    var canvas = document.getElementById( 'c1' ),
        entry = $( this ),
        width = entry.width(),
        height = entry.height();

    $( '#c1' ).attr( { 'width': width, 'height': height } );
    context = canvas.getContext( '2d' );
    var base_image = new Image();
    base_image.crossOrigin = '';
    context.imageSmoothingEnabled = false;
    base_image.src = entry.attr( 'src' );
    base_image.onload = function() {
        context.drawImage( base_image, 0, 0, width, height );
        entry.attr( 'src', canvas.toDataURL() )
    }
})
#c1 {
    display: none
}
#a, #b {
    width: 100px;
    height: 100px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<canvas id="c1"></canvas>
<img id='a' src='https://i.imgur.com/cANXGWL.jpg' class='zoom'>
<img id='b' src='https://i.imgur.com/j6sXsVe.jpg' class='zoom'>

Upvotes: 2

Related Questions