Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
50
rated 0 times [  51] [ 1]  / answers: 1 / hits: 24898  / 8 Years ago, wed, february 24, 2016, 12:00:00

I am attempting to resize an image's dimensions, whilst retaining it's aspect ratio. This seems like a very simple task, but I cannot find a rellevent answer anywhere.. (relating to JavaScript's Image() object). I'm probably missing something very obvious. Below is what I am trying to achieve:



var img = new window.Image();
img.src = imageDataUrl;
img.onload = function(){
if (img.width > 200){
img.width = 200;
img.height = (img.height*img.width)/img.width;
}
if (img.height > 200){
img.height = 200;
img.width = (img.width*img.height)/img.height;
}
};


This is to proportionally resize an image before being drawn onto a canvas like so: context.drawImage(img,0,0,canvas.width,canvas.height);.However it would appear I cannot directly change Image()dimensions, so how is it done? Thanks.



Edit: I haven't correctly solved the image proportions using cross-multiplication. @markE provides a neat method of obtaining the correct ratio. Below is my new (working) implementation:



var scale = Math.min((200/img.width),(200/img.height));
img.width = img.width*scale;
img.height = img.height*scale;
clearCanvas(); //clear canvas
context.drawImage(img,0,0,img.width,img.height);

More From » canvas

 Answers
27

Here's how to scale your image proportionally:



function scalePreserveAspectRatio(imgW,imgH,maxW,maxH){
return(Math.min((maxW/imgW),(maxH/imgH)));
}


Usage:





var canvas=document.getElementById(canvas);
var ctx=canvas.getContext(2d);

var img=new Image();
img.onload=start;
img.src=https://dl.dropboxusercontent.com/u/139992952/stackoverflow/balloon.png;
function start(){

canvas.width=100;
canvas.height=100;

var w=img.width;
var h=img.height;

// resize img to fit in the canvas
// You can alternately request img to fit into any specified width/height
var sizer=scalePreserveAspectRatio(w,h,canvas.width,canvas.height);

ctx.drawImage(img,0,0,w,h,0,0,w*sizer,h*sizer);

}

function scalePreserveAspectRatio(imgW,imgH,maxW,maxH){
return(Math.min((maxW/imgW),(maxH/imgH)));
}

body{ background-color: ivory; }
canvas{border:1px solid red;}

<h4>Original Balloon image resized to fit in 100x100 canvas</h4>
<canvas id=canvas width=100 height=100></canvas>




[#63175] Tuesday, February 23, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
aileent

Total Points: 556
Total Questions: 107
Total Answers: 101

Location: Croatia
Member since Fri, Sep 11, 2020
4 Years ago
;