HTML5 キャンバスのサイズをウィンドウに合わせて変更する
-
12-09-2019 - |
質問
HTML5 を自動的にスケールするにはどうすればよいですか <canvas>
ページに合わせて要素を配置しますか?
たとえば、 <div>
を設定してスケールするには、 height
そして width
プロパティは 100% ですが、 <canvas>
スケールしないでしょう?
解決
これに対するエレガントな解決策を見つけたと信じています。
JavaScript
/* important! for alignment, you should make things
* relative to the canvas' current width/height.
*/
function draw() {
var ctx = (a canvas context);
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
//...drawing code...
}
CSS
html, body {
width: 100%;
height: 100%;
margin: 0;
}
今のところ、パフォーマンスに大きな悪影響はありません。
他のヒント
次のソリューションは、最高の私のために働きました。私は、コードに比較的新しいですので、私は何かが、私はそれが期待どおりに動作していることを視覚的に確認してもらいたいです。私は、次のサイトでそれを見つけました: http://htmlcheats.com/html/resize-the-html5-canvas- dyamically / の
ここでは、コードです。
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Resize HTML5 canvas dynamically | www.htmlcheats.com</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0px;
border: 0;
overflow: hidden; /* Disable scrollbars */
display: block; /* No floating content on sides */
}
</style>
</head>
<body>
<canvas id='c' style='position:absolute; left:0px; top:0px;'>
</canvas>
<script>
(function() {
var
// Obtain a reference to the canvas element using its id.
htmlCanvas = document.getElementById('c'),
// Obtain a graphics context on the canvas element for drawing.
context = htmlCanvas.getContext('2d');
// Start listening to resize events and draw canvas.
initialize();
function initialize() {
// Register an event listener to call the resizeCanvas() function
// each time the window is resized.
window.addEventListener('resize', resizeCanvas, false);
// Draw canvas border for the first time.
resizeCanvas();
}
// Display custom canvas. In this case it's a blue, 5 pixel
// border that resizes along with the browser window.
function redraw() {
context.strokeStyle = 'blue';
context.lineWidth = '5';
context.strokeRect(0, 0, window.innerWidth, window.innerHeight);
}
// Runs each time the DOM window resize event fires.
// Resets the canvas dimensions to match window,
// then draws the new borders accordingly.
function resizeCanvas() {
htmlCanvas.width = window.innerWidth;
htmlCanvas.height = window.innerHeight;
redraw();
}
})();
</script>
</body>
</html>
青色境界はあなたのサイズ変更キャンバスのエッジを示しており、他の上記の回答のいくつかの場合ではありませんでしたすべての4辺に可視窓の縁部に沿って常にあります。それがお役に立てば幸いです。
基本的に何をしなければならないことは、あなたがちょうどwindow.innerWidthとwindow.innerHeightを使用して、キャンバスのサイズを変更する必要があるイベントをキャッチしたら、あなたの体にさらにonResizeイベントをバインドすることです。
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Canvas Resize</title>
<script type="text/javascript">
function resize_canvas(){
canvas = document.getElementById("canvas");
if (canvas.width < window.innerWidth)
{
canvas.width = window.innerWidth;
}
if (canvas.height < window.innerHeight)
{
canvas.height = window.innerHeight;
}
}
</script>
</head>
<body onresize="resize_canvas()">
<canvas id="canvas">Your browser doesn't support canvas</canvas>
</body>
</html>
ブラウザクライアントの寸法に基づいてスペース幅と高さを調整キャンバスの設定、ブラウザのサイズが変更されるたびにサイズを変更して再描画する必要があります。
以下入り組んだ溶液では、JavaScript変数で描画可能な寸法を維持することであるが、screen.width、screen.height寸法に基づくキャンバスサイズを設定しました。合わせてCSSを使用します:
#containingDiv {
overflow: hidden;
}
#myCanvas {
position: absolute;
top: 0px;
left: 0px;
}
「(これはデュアルモニタを非一致するかもしれないように、画面解像度が誤って報告されている場合を除く)、ブラウザウィンドウは、一般的に、これまでの画面自体よりも大きくないので、背景は表示されませんと画素比率ウォンtは異なります。あなたはキャンバスを拡張するためにCSSを使用しない限り、キャンバスのピクセルは、画面の解像度に正比例します。
A の純粋なCSS の上記@jerseyboyの溶液に添加するアプローチ。
Firefoxの(V29でテスト)、クロム(V34でテスト)とInternet Explorer(V11でテスト)で動作します。
<!DOCTYPE html>
<html>
<head>
<style>
html,
body {
width: 100%;
height: 100%;
margin: 0;
}
canvas {
background-color: #ccc;
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillRect(25,25,100,100);
ctx.clearRect(45,45,60,60);
ctx.strokeRect(50,50,50,50);
}
</script>
</body>
</html>
例のリンク: http://temporaer.net/open /so/140502_canvas-fit-to-window.htmlする
しかし、彼のコメントに@jerseyboy状態として、世話をします:
CSSでキャンバスを再スケーリングすることは面倒です。クロムの少なくともと で1:サファリ、マウス/タッチイベントの位置は、1に対応しないであろう キャンバス画素位置を、あなたは座標変換する必要があります システムます。
。 キャンバスをセンタリング
function resize() {
var canvas = document.getElementById('game');
var canvasRatio = canvas.height / canvas.width;
var windowRatio = window.innerHeight / window.innerWidth;
var width;
var height;
if (windowRatio < canvasRatio) {
height = window.innerHeight;
width = height / canvasRatio;
} else {
width = window.innerWidth;
height = width * canvasRatio;
}
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
};
window.addEventListener('resize', resize, false);
あなたのdivを完全にWebページを満たした場合、あなたはdiv要素などのdivをいっぱいにキャンバスを持っていることを埋めることができます。
あなたはパーセンテージを使用するようにCSSを使用する必要がありますように、これは面白い、しかし、それはあなたが使用しているブラウザに依存し、どのくらいそれが仕様と一致していることがあります。 ます。http: //www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-elementする
キャンバスの固有寸法 要素は、サイズに等しいです 数字で、座標空間 CSSピクセルで解釈。しかしながら、 要素は、任意サイズにすることができます スタイルシートによって。レンダリング時には、 画像は、このレイアウトに合わせて拡大縮小されます サイズます。
あなたはoffsetWidthとdiv要素の高さを取得する必要があるかもしれない、またはウィンドウの高さ/幅と画素値とするように設定を取得ます。
CSS
body { margin: 0; }
canvas { display: block; }
JavaScript
window.addEventListener("load", function()
{
var canvas = document.createElement('canvas'); document.body.appendChild(canvas);
var context = canvas.getContext('2d');
function draw()
{
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(0, 0); context.lineTo(canvas.width, canvas.height);
context.moveTo(canvas.width, 0); context.lineTo(0, canvas.height);
context.stroke();
}
function resize()
{
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
draw();
}
window.addEventListener("resize", resize);
resize();
});
あなたは、以下のような何かを行うことができます。キーはpadding-bottom
要素のサイズ::content
要素にcontainer
です。これはデフォルトで100%
され、その親の幅にサイズの相対的です。ここで指定した比率はcanvas
要素の大きさの比と一致する必要があります。
// Javascript
var canvas = document.querySelector('canvas'),
context = canvas.getContext('2d');
context.fillStyle = '#ff0000';
context.fillRect(500, 200, 200, 200);
context.fillStyle = '#000000';
context.font = '30px serif';
context.fillText('This is some text that should not be distorted, just scaled', 10, 40);
/*CSS*/
.container {
position: relative;
background-color: green;
}
.container::after {
content: ' ';
display: block;
padding: 0 0 50%;
}
.wrapper {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
}
canvas {
width: 100%;
height: 100%;
}
<!-- HTML -->
<div class=container>
<div class=wrapper>
<canvas width=1200 height=600></canvas>
</div>
</div>
(function() {
// get viewport size
getViewportSize = function() {
return {
height: window.innerHeight,
width: window.innerWidth
};
};
// update canvas size
updateSizes = function() {
var viewportSize = getViewportSize();
$('#myCanvas').width(viewportSize.width).height(viewportSize.height);
$('#myCanvas').attr('width', viewportSize.width).attr('height', viewportSize.height);
};
// run on load
updateSizes();
// handle window resizing
$(window).on('resize', function() {
updateSizes();
});
}());
のjQueryを使用して、あなたは、ウィンドウのサイズ変更を追跡し、同様にjQueryを使用して、キャンバスの幅を変更することができます。
のようなもの。
$( window ).resize(function() {
$("#myCanvas").width($( window ).width())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
正確にやるべきことは次のとおりだと思います。 http://www.html5rocks.com/en/tutorials/casestudies/gopherwoord-studios-resizing-html5-games/
function resizeGame() {
var gameArea = document.getElementById('gameArea');
var widthToHeight = 4 / 3;
var newWidth = window.innerWidth;
var newHeight = window.innerHeight;
var newWidthToHeight = newWidth / newHeight;
if (newWidthToHeight > widthToHeight) {
newWidth = newHeight * widthToHeight;
gameArea.style.height = newHeight + 'px';
gameArea.style.width = newWidth + 'px';
} else {
newHeight = newWidth / widthToHeight;
gameArea.style.width = newWidth + 'px';
gameArea.style.height = newHeight + 'px';
}
gameArea.style.marginTop = (-newHeight / 2) + 'px';
gameArea.style.marginLeft = (-newWidth / 2) + 'px';
var gameCanvas = document.getElementById('gameCanvas');
gameCanvas.width = newWidth;
gameCanvas.height = newHeight;
}
window.addEventListener('resize', resizeGame, false);
window.addEventListener('orientationchange', resizeGame, false);
まず、あなたは、幅と高さは、それはそれを破るますので、(少なくとも、私の方法で)サイズを変更する属性を使用することはできません。あなたはこれを行うことができます: HTMLます:
<canvas id = 'myCanvas'></canvas>
JSます:
var canvas = document.getElementById('myCanvas');
var W = window.innerWidth;
var H = window.innerHeight;
canvas.width = W;
canvas.height = H;
canvas.style.position = 'absolute';
//Or set the position to absolute using CSS
(私はたくさんのことを行う傾向があり、いずれのタイプミスのために私を許してください)。
私はsketch.jsを使用しています。これは、親要素の寸法を基づかせています。
$( '#のDrawCanvas')。(スケッチ)。ATTR( '高さ'、$( '#のDrawCanvas')。親()。高さ())。ATTR( '幅'、$( '#のDrawCanvas' 。).parent()幅());