少し実験した後、最終的には css プロパティを変更するだけでよい解決策を見つけました。
非常に長いですが、答えは非常に簡単です。
これは私のhtml-bodyです:
<body onload='init()'>
<div id="canvasWrapper">
<canvas id="canvas" width="100px" height="100px"></canvas>
</div>
</body>
そして、これは私のcssです:
*{
padding: 0;
margin: 0;
border: 0;
}
body{
overflow: hidden;
}
#canvasWrapper {
background-color: red;
display: inline-block;
}
重要な部分は、キャンバス ラッパーの「インライン ブロック」と、ボディ要素の「オーバーフロー: 非表示」です。キャンバスの下にいくつかのピクセルがあり、両方のスクロールバーが表示されるようです。
いくつかの実験の後、次のjs コードを取得しました。
function init(){
resizeCanvas(); //resize the canvas-Element
window.onresize = function() { resizeCanvas(); }
}
画面サイズが変更されるたびに、私の「サイズ変更」関数が呼び出されます。
全体のトリックは、このサイズ変更関数で行われます。
function resizeCanvas() {
var w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight|| e.clientHeight|| g.clientHeight;
var cv = document.getElementsByTagName("canvas")[0];
//var cc = document.getElementsByClassName("canvas-container")[0]; //In case of non-Static Canvas will be used
var cc = document.getElementById("canvasWrapper");
var cx,cy; //The size of the canvas-Element
var cleft=0; //Offset to the left border (to center the canvas-element, if there are borders on the left&right)
if(x/y > sizeX/sizeY){ //x-diff > y-diff ==> black borders left&right
cx = (y*sizeX/sizeY);
cy = y;
cleft = (x-cx)/2;
}else{ //y-diff > x-diff ==> black borders top&bottom
cx = x;
cy = (x*sizeY/sizeX);
}
cc.setAttribute("style", "width:"+x+"px;height:"+y+"px;"); //canvas-content = fullscreen
cv.setAttribute("style", "width:"+cx+"px;height:"+cy+"px;position: relative; left:"+cleft+"px"); //canvas: 16:9, as big as possible, horizintally centered
}
この関数は、window-width と、比率を変更せずに可能な最大の canvas-size を計算します。
その後、wrapper-div を fullscreen-size に設定し、canvas-Element のサイズを以前に計算したサイズに設定しました。
canvas 要素の内容を変更したり、何も再描画したりする必要なく、すべてが機能します。
クロスブラウザー互換性があります (Firefox 25、Chrome 31、Internet Explorer 11 でテスト済み)。