Images are not uploaded to the website

The problem is that when loading a page, sometimes all images are displayed, and sometimes only two images, and sometimes all. I do not know why this is happening.

Any ideas?

$('#banners .box img').each(function(index){ var randval = (index+1)*100; var _this = $(this) setTimeout(function(){ _this.attr('id' , 'banner' + index); to_canvas('banner' + index, 300, 223); }, randval) }); 

to_canvas:

  function to_canvas(im,w,h){ var canvas; var imageBottom; var im_w = w; var im_h = h; var imgData; var pix; var pixcount = 0; var paintrow = 0; var multiplyColor = [70, 116, 145]; var x_offset = Math.floor(($('#'+im).attr('width') - im_w)/2); var y_offset = Math.floor(($('#'+im).attr('height') - im_h)/2); imageBottom = document.getElementById(im); canvas = document.createElement('canvas'); canvas.width = im_w; canvas.height = im_h; imageBottom.parentNode.insertBefore(canvas, imageBottom); ctx = canvas.getContext('2d'); ctx.drawImage(imageBottom, -x_offset , -y_offset); imgData = ctx.getImageData(0, 0, canvas.width, canvas.height); pix = imgData.data; for (var i = 0 ; i < pix.length; i += 4) { if(pixcount > im_w - (im_h - paintrow) ){ pix[i ] = multiply(multiplyColor[0], pix[i ]); pix[i+1] = multiply(multiplyColor[1], pix[i+1]); pix[i+2] = multiply(multiplyColor[2], pix[i+2]); } if(pixcount < im_w-1){ pixcount++; }else{ paintrow++; pixcount = 0; } } ctx.putImageData(imgData, 0, 0); $('#'+im).remove(); } function multiply(topValue, bottomValue){ return topValue * bottomValue / 255; } 

I use the canvas function to add a triangle with a multiplication effect (like Photoshop).

+6
source share
2 answers

Make sure the images are uploaded:

 $('#banners .box img').each(function(index, elem){ var randval = (index+1)*100, self = this, img = new Image(); // create image object img.onload = function() { // wait until it loaded setTimeout(function(){ self.id = 'banner' + index; to_canvas('banner' + index, 300, 223); }, randval) } img.src = elem.src; // set source to same as elem }); 
+1
source

Wrap all of this in this code to make sure the images are loaded before you execute your script. When you initially load your page, it caches images (saves them in temporary memory), but not earlier than all your elements are displayed. When you reboot, it reads images from the cache, which is much faster than re-displaying images from the server, and therefore downloading images at about the same time does the rest. This results in visible images.

As I said, for your page to work, make sure everything is loaded, and then run the script.

 $(window).load(function(){ ...your scripts(you can exclude functions definitions from this scope) } 
0
source

Source: https://habr.com/ru/post/944883/


All Articles