0
以下代碼將創建具有寬高比的全屏圖像。但是它不用在excanvas上工作。我無法解決問題。任何幫助?寬高比圖像調整大小上的excanvas錯誤
這裏的jsfiddle鏈接: http://jsfiddle.net/salt/Zs6uV/
解決方案: http://jsfiddle.net/salt/xpwZh/
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>aspectratio test</title>
<script type="text/javascript">
function getWindowSize(typ) {
var myWidth = 0, myHeight = 0;
if(typeof(window.innerWidth) == 'number') {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if(document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if(document.body && (document.body.clientWidth || document.body.clientHeight)) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
if(typ=="width"){
return myWidth;
}else{
return myHeight;
};
};
</script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<!--[if IE]><script type="text/javascript" src="http://explorercanvas.googlecode.com/svn/trunk/excanvas.js"></script><![endif]-->
<!--[if lt IE 9]><script src="http://html5shim.googlecode.com/svn/trunk/html5.js"></script><![endif]-->
</head>
<body style="margin:0px;" onLoad="setupBackground();">
<canvas id="myCanvas" style="position:absolute;left: 0px; top: 0px; z-index: 1;"></canvas>
<script type="text/javascript">
function setupBackground() {
canvas = document.getElementById('myCanvas');
if (typeof window.G_vmlCanvasManager!="undefined") {
canvas=window.G_vmlCanvasManager.initElement(canvas);
var ctx = canvas.getContext('2d');
}else{
var ctx = canvas.getContext('2d');
};
function draw() {
canvas.width = 0;
canvas.height = 0;
var divWidth = getWindowSize("width");
var divHeight = getWindowSize("height");
var yScale = divHeight/img.height;
var xScale = divWidth/img.width;
var newImgHeight = img.height * xScale;
var newImgWidth = divWidth;
if (divHeight >= newImgHeight) {
newImgHeight = divHeight;
newImgWidth = img.width * yScale;
};
canvas.width = divWidth;
canvas.height = divHeight;
var diffX =(Math.max(newImgWidth,divWidth)-Math.min(newImgWidth,divWidth))/2;
var diffY =(Math.max(newImgHeight,divHeight)-Math.min(newImgHeight,divHeight))/2;
var imgX=0-diffX;
var imgY=0-diffY;
ctx.drawImage(img,imgX,imgY,newImgWidth,newImgHeight);
};
var img = new Image();
img.onload = function() {
$(window).bind('resize', function() {
draw();
});
draw();
};
img.src ='http://userserve-ak.last.fm/serve/_/460496/Popperklopper.jpg';
};
</script>
</body>
</html>