title: Reduce the dimension of base64 image maintaining aspect ratio in javascript
body: <p>I have a base64 string for an image, which i have to display as an icon. If the dimension of an image are bigger i have to display icon maintaining aspect ratio.
  I have written a logic to identify if the image is landscape or portrait based on which height and width will be settled for canvas. But seems height and width of icons are not proper as i have hard coded it. </p>
  
  <pre><code>      var canvas = document.createElement("canvas");
        var ctx = canvas.getContext("2d");          
        var height, width;
        if (this.height&gt;this.width) {
              height = 50;
              width = 30;
        } else if (this.height&lt;this.width) {
              height = 30;
              width = 50;
        }
        canvas.width = width;
        canvas.height = height;
        ctx.drawImage(image,
              0, 0, this.width, this.height,
              0, 0, canvas.width, canvas.height
        );
        var scaledImage = new Image();
        scaledImage.src = canvas.toDataURL();
  </code></pre>
  
  <p>Is there any way we can calculate it dynamically or any other way to preserve aspect ratio for icons.</p>
  
  <p>Working Example can be found on <a href="https://codepen.io/imjaydeep/pen/ewBZRK" rel="nofollow noreferrer">https://codepen.io/imjaydeep/pen/ewBZRK</a></p>
  
  <p><a href="https://i.stack.imgur.com/fTp51.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fTp51.png" alt="enter image description here"></a></p>
  
  <p>It will be fine if some space will be left on x-y axis.</p>