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.
var canvas = document.createElement("canvas"); var ctx = canvas.getContext("2d"); var height, width; if (this.height>this.width) { height = 50; width = 30; } else if (this.height<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(); Is there any way we can calculate it dynamically or any other way to preserve aspect ratio for icons.
Working Example can be found on https://codepen.io/imjaydeep/pen/ewBZRK
It will be fine if some space will be left on x-y axis.


