更改 Image() 对象尺寸(宽度和高度)
Change Image() object dimensions (width and height)
我正在尝试调整图像尺寸的大小,同时保留其纵横比。这似乎是一项非常简单的任务,但我在任何地方都找不到答案。(与 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()
尺寸,那么它是如何完成的呢?谢谢。
编辑:我没有使用交叉乘法正确解决图像比例。 @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);
以下是按比例缩放图像的方法:
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>
图像尺寸在构造函数中设置
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);
相关文章:
- electronic BrowserWindow的最小高度和宽度在hide()show()方法之后不起作用
- ExtJS——在展开/折叠时调整面板高度
- 分析高度属性时出现意外值{{specs.height}}.index.html
- 单击页面上的链接后高度发生变化
- Image赢得't隐藏在滚动jQuery上
- 不加载宽度和高度的角度pintura
- 查找元素高度,包括边距
- 如何自动调整标签的高度以适应内容
- Javascript高度问题
- 使用JavaScript根据窗口/视口的高度动态调整图像大小
- 如何计算每个元素's的高度,并将这些值用作函数中的变量
- 使用:new Image()控制加载html.src=html_URL
- 无法使用nodeJS在html中设置Image src
- Image.onload 函数为高度和宽度返回零
- 更改 Image() 对象尺寸(宽度和高度)
- Javascript Image()返回错误的宽度和高度
- Lightbox image max-height =用户屏幕高度
- Javascript Image()获得自然的宽度和高度
- 两者的区别是什么?高度vs image .style. Height
- Javascript Image() 对象有时会错误地将高度和宽度设置为 0