![](/img/trans.png)
[英]How to resize <canvas> based on window width/height and maintain aspect ratio?
[英]Adjusting height & width of pop up window on resize to maintain the aspect ratio
我正在使用window.open
函數打開一個彈出窗口
window.open('some_page.htm','','width=950,height=500');
現在我想要的是當用戶嘗試調整窗口大小時,應保持縱橫比,即,如果寬度減小,則高度也應減小,反之亦然。 我只想計算新尺寸。 到目前為止,我已經嘗試過了
function ResizeWindow()
{
var iOrignalWidth = 950;
var iOrignalHeight = 500;
var iOuterHeight = window.outerHeight;
var iOuterWidth = window.outerWidth;
var iNewOuterWidth = Math.round((iOrignalWidth / iOrignalHeight) * iOuterHeight);
var iNewOuterHeight = Math.round((iOrignalHeight / iOrignalWidth) * iNewOuterWidth);
alert("New Width: "+ iNewOuterWidth + "\t" + "New Height" + iNewOuterHeight);
}
我知道那里有些問題,因為我沒有得到理想的結果。 可以解決這個問題嗎?
您可能想要將寬度調整為高度,反之亦然,而不是兩者都調整。 在此代碼中,我假設您要將寬度調整為高度:
function ResizeWindow()
{
var iOrignalWidth = 1000;
var iOrignalHeight = 500;
var iOrginalRatio = iOrignalWidth/iOrignalHeight; // 2
var iOuterWidth = window.outerWidth; // example: 1083
var iOuterHeight = window.outerHeight; //example: 600
var iNewOuterHeight = iOuterHeight; // 600
var iNewOuterWidth = Math.round(iNewOuterHeight*iOrginalRatio); //600 * 2 = 1200
alert("New Width: "+ iNewOuterWidth + "\t" + "New Height" + iNewOuterHeight);
}
我將示例的原始寬度更改為1000,但是您可以在實際代碼中將其更改為原來的寬度。
您應該按照一種調整大小的方式來保持縱橫比。 例如:
function ResizeWindow()
{
var iOrignalWidth = 950;
var iOrignalHeight = 500;
var iOuterHeight = window.outerHeight;
var iOuterWidth = window.outerWidth;
var w = (window.outerWidth - iOrignalWidth) / iOrignalWidth; // for exam: (1280-950) / 950= 0.34
var h = (window.outerHeight - iOrignalHeight) / iOrignalHeight; // for exam : (800 - 500) / 500= 0.60
var newWidth;
var newHeight;
if (w<h)
{
// If percentage of width is less than percentage of height, Resize should be according to percentage of width.
newWidth = iOrignalWidth * w * 100;
newHeight = iOrignalHeight * w *100;
}
else
{
// If percentage of height is less than percentage of width, Resize should be according to percentage of height.
newWidth = iOrignalWidth * h * 100;
newHeight = iOrignalHeight * h *100;
}
alert("New Width: "+ newWidth + "\t" + "New Height" + newHeight );
}
這樣始終保持長寬比不變。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.