更改Image()对象尺寸(宽度和高度)

时间:2016-02-24 21:44:42

标签: javascript canvas aspect-ratio

我正在尝试调整图像的尺寸,同时保持其纵横比。这似乎是一个非常简单的任务,但我找不到任何地方的相关答案..(与JavaScript的Image()对象有关)。我可能错过了一些非常明显的东西。以下是我想要实现的目标:

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;
    }
};

这是按比例调整图像大小,然后将其绘制到画布上:context.drawImage(img,0,0,canvas.width,canvas.height);。但是看起来我不能直接更改Image()尺寸,那么它是如何完成的?感谢。

修改:我没有使用交叉乘法正确解决图像proportions。 @markE提供了一种获得正确比率的简洁方法。以下是我的新(工作)实现:

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);

2 个答案:

答案 0 :(得分:10)

以下是按比例缩放图片的方法:

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

用法:



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>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

图像尺寸在构造函数

中设置
new Image(width, height)
// for proportionally consistent resizing use new Image(width, "auto")

the context.drawImage() 

参数如下:

context.drawImage(image source, x-coordinate of upper left portion of image,
y-coordinate of upper left portion of image,image width,image height);  

只需使用前两个数字坐标定位图像,然后用最后两个(宽度,高度)手动调整大小

//ex.
var x = 0;
var y = 0;
var img = new Image (200, "auto");
    img.src = "xxx.png";
context.drawImage(img,x,y,img.width,img.height);