Canvas drawImage scaling Canvas drawImage scaling javascript javascript

Canvas drawImage scaling


context.drawImage(imageObj, 0, 0, 100, 100 * imageObj.height / imageObj.width)


solution of @TechMaze is quite good.

here is the code after some correctness and introduction of image.onload event. image.onload is too much essential in order to abstain from any kind of distortion.

function draw_canvas_image() {var canvas = document.getElementById("image-holder-canvas");var context = canvas.getContext("2d");var imageObj = document.getElementById("myImageToDisplayOnCanvas");imageObj.onload = function() {  var imgWidth = imageObj.naturalWidth;  var screenWidth  = canvas.width;  var scaleX = 1;  if (imgWidth > screenWidth)      scaleX = screenWidth/imgWidth;  var imgHeight = imageObj.naturalHeight;  var screenHeight = canvas.height;  var scaleY = 1;  if (imgHeight > screenHeight)      scaleY = screenHeight/imgHeight;  var scale = scaleY;  if(scaleX < scaleY)      scale = scaleX;  if(scale < 1){      imgHeight = imgHeight*scale;      imgWidth = imgWidth*scale;            }  canvas.height = imgHeight;  canvas.width = imgWidth;  context.drawImage(imageObj, 0, 0, imageObj.naturalWidth, imageObj.naturalHeight, 0,0, imgWidth, imgHeight);}}


And if you want to properly scale the picture as per screen size, here is the math you can do:IF YOU ARE NOT USING JQUERY, REPLACE $(window).width with appropriate equivalent option.

var imgWidth = imageObj.naturalWidth;var screenWidth  = $(window).width() - 20; var scaleX = 1;if (imageWdith > screenWdith)    scaleX = screenWidth/imgWidth;var imgHeight = imageObj.naturalHeight;var screenHeight = $(window).height() - canvas.offsetTop-10;var scaleY = 1;if (imgHeight > screenHeight)    scaleY = screenHeight/imgHeight;var scale = scaleY;if(scaleX < scaleY)    scale = scaleX;if(scale < 1){    imgHeight = imgHeight*scale;    imgWidth = imgWidth*scale;          }canvas.height = imgHeight;canvas.width = imgWidth;ctx.drawImage(imageObj, 0, 0, imageObj.naturalWidth, imageObj.naturalHeight, 0,0, imgWidth, imgHeight);