简体   繁体   中英

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'> 

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'> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM