Resize image before uploading - jquery

I use this plugin to create image and gallery scaling, but I want to scale all the images according to the container (using the ratio algorithm).

Here is the relationship function:

function scaleSize(maxW, maxH, currW, currH){ var ratio = currH / currW; if(currW >= maxW && ratio <= 1){ currW = maxW; currH = currW * ratio; } else if(currH >= maxH){ currH = maxH; currW = currH / ratio; } return [currW, currH]; } 

And this is how the gallery uploads images:

  var img = $('<img>').load(function(){ img.appendTo(a); image_container.html(a); }).attr('src', src).addClass(opts.big_image_class); 

What I tried:

  var newSize = scaleSize(300, 320, $(".simpleLens-big-image").width(), $(".simpleLens-big-image").height()); var img = $('<img>').load(function(){ img.appendTo(a); image_container.html(a); }).attr('src', src).addClass(opts.big_image_class).width(newSize[0]).height(newSize[1]); 

But scaleSize does not work correctly, since the current width and height have not yet been determined (the image does not yet exist in dom).

Thanks for any pointers.

+6
source share
2 answers

I took a look at the plugin code and thought that you call your scaleSize() too early. The image with the simpleLens-big-image class exists first after setting up var img and addClass() is addClass() . Try the following:

 var img = $('<img>').load(function(){ img.appendTo(a); image_container.html(a); }).attr('src', src).addClass(opts.big_image_class); // at this point img should contain $(".simpleLens-big-image") so we can refer to img var newSize = scaleSize(300, 320, img[0].naturalWidth, img[0].naturalHeight()); img.width(newSize[0]).height(newSize[1]); 
0
source

Try something like this and call the onload method. This will ensure that the image is loaded in the DOM before resizing.

 var img = $('<img>'); img.src = src ; img.onload = function() { // Run onload code. } ; 
0
source

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


All Articles