我在HTML/Javascript中工作,並打算根據窗口大小調整圖像大小。圖像將佔用所有窗口空間,但在調整大小時保持其縱橫比。此外,如果窗口大小大於其最長邊,圖像將旋轉並調整大小。例如,如果圖像的寬度大於高度,並且窗口大小變得非常高,則圖像應該旋轉並調整大小,以最大化窗口空間,同時保持圖像的寬高比相同。圖像也應該居中在屏幕上,以便在圖像的任一側具有相同的死角。HTML>根據窗口和圖像大小旋轉和縮放圖像
我無法得到這個工作。這是我的代碼到目前爲止。
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<link href="test.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function resize_canvas(){
var main_canvas=document.getElementById("test");
var cxt=main_canvas.getContext("2d");
var img=new Image();
var ratio = 1;
var changed = 1;
var mid = 1;
var srcLink = "tall.JPG"; // test with tall and wide pics
main_canvas.width = window.innerWidth;
main_canvas.height = window.innerHeight;
img.src=srcLink;
if(window.innerWidth > window.innerHeight){ // if window port is wider than tall
changed = window.innerWidth/(img.width/img.height);
mid = window.innerHeight/2;
img.onload = function()
{
if (img.width < img.height){
ratio = window.innerHeight/img.height;
changed = img.width * ratio;
cxt.rotate(90 * Math.PI/180);
cxt.drawImage(img, 0, -img.height,changed,window.innerWidth);
} else {
cxt.drawImage(img,0,mid,window.innerWidth,changed);
}
} // end img onload call
}else{ // if window port is taller than wide
ratio = window.innerHeight/img.height;
changed = img.width * ratio;
mid = window.innerWidth/2;
img.onload = function()
{
if (img.width > img.height){
ratio = window.innerWidth/img.width;
changed = img.height * ratio;
mid = window.innerHeight/2 - changed/2;
cxt.rotate(90 * Math.PI/180);
cxt.drawImage(img, 0, -img.height,window.innerHeight,changed);
} else {
cxt.drawImage(img,mid,0,changed,window.innerHeight);
}
} // end img on load
} // end window size else block
} // end resize function
</script>
</head>
<body onload="resize_canvas();" onresize="resize_canvas();">
<canvas id="test"> canvas not supported </canvas>
</body>
</html>
css file
html, body {
width: 100%;
height: 100%;
margin: 0px;
}
#test
{
width: 100%; height: auto;
}
我在這度過了許多天,因爲我剛開始學習,但我跑出來的關於如何解決問題的想法。任何幫助將非常感激。
謝謝。
哪部分不起作用? – 2012-02-05 00:19:18
我可以縮放圖像,但我無法正確定位圖像。另外,當圖像必須旋轉時,縮放和居中似乎不起作用。圖像部分不在屏幕上,或者當我嘗試調整圖像大小時,它只是不顯示。我不確定我的錯誤在哪裏。 – nomaam 2012-02-05 00:32:54
您需要支持哪些瀏覽器和版本? – Phrogz 2012-02-05 01:36:39