vendredi 13 avril 2018

Javascript - ReactJS - Returning a let [duplicate]

This question already has an answer here:

I have the following function(s) that get the height and width of an image and calculate whether the image is in portrait, landscape or even mode.

However I am struggling to return the orientation outside of the IF statements. Inside the IF the imgSrc and orientation are logged perfectly, however the last console.log is empty.

How can I return the orientation if I call

getOrientation(src)

?

Expected output for a wide image:

landscape

My code

const getOrientation = imgSrc => {
  let newImg = new Image()
  let orientation = ''

    newImg.onload = () => {
      let width = newImg.naturalWidth || imgSrc.width;
      let height = newImg.naturalHeight || imgSrc.height;

      console.log("height: " + height + " width: " + width)

      if (width > height) {
        orientation = 'landscape',
        console.log(imgSrc + " == " + orientation)
      } 
      else if (width < height) {
        orientation = 'portrait',
        console.log(imgSrc + " == " + orientation)
      } 
      else {
        orientation = 'even',
        console.log(imgSrc + " == " + orientation)
      }

    }

  console.log(orientation)

  newImg.src = imgSrc

} 

Aucun commentaire:

Enregistrer un commentaire