HTML5 <canvas>
要素は、width
およびheight
プロパティの相対サイズ(パーセント)を受け入れません。HTMLキャンバスの相対的なサイズ変更
私が達成しようとしているのは、キャンバスのサイズをウィンドウに合わせて設定することです。これは私がこれまでに作ってみたものですが、あるより良い方法があれば、私は思ったんだけど:<div>
で<canvas>
をラップする必要はありません
- よりシンプルに。
- のjQueryに依存しないが(私は親のdivの幅/高さを得るためにそれを使用)
- 理想的には、ブラウザのサイズ変更には再描画されません(ただし、私はそれが必要条件かもしれないと思う)
スクリーンの中央に円を描くコードについては、下の図を参照してください。幅は40%、最大で400ピクセルです。
ライブデモ:http://jsbin.com/elosil/2
コード:
<!DOCTYPE html>
<html>
<head>
<title>Canvas of relative width</title>
<style>
body { margin: 0; padding: 0; background-color: #ccc; }
#relative { width: 40%; margin: 100px auto; height: 400px; border: solid 4px #999; background-color: White; }
</style>
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script>
function draw() {
// draw a circle in the center of the canvas
var canvas = document.getElementById('canvas');
var relative = document.getElementById('relative');
canvas.width = $(relative).width();
canvas.height = $(relative).height();
var w = canvas.width;
var h = canvas.height;
var size = (w > h) ? h : w; // set the radius of the circle to be the lesser of the width or height;
var ctx = canvas.getContext('2d');
ctx.beginPath();
ctx.arc(w/2, h/2, size/2, 0, Math.PI * 2, false);
ctx.closePath();
ctx.fill();
}
$(function() {
$(window).resize(draw);
});
</script>
</head>
<body onload="draw()">
<div id="relative">
<canvas id="canvas"></canvas>
</div>
</body>
</html>
ありがとうございました。興味深いことに、それを中心にしたい場合は 'div'に' canvas'をラップする必要があるようです。 'margin:0 auto'はdivのようにキャンバスを中心にしていないようです。 – Portman
@Portmanいいえ、それでもできます。キャンバススタイルでdisplay:blockを配置するのを忘れてしまいました(デフォルトはインラインブロックですが、そのようにセンタリングしません)。この修正プログラムで更新された解答。 – sethobrien