HTML5 <canvas>
元素不接受其width
和height
属性的相对大小(百分比)。HTML Canvas的相对大小
我想要完成的是让我的画布相对于窗口大小。这是我想出到目前为止,但我不知道是否有这更好的办法:
- 简单
- 不需要在
<div>
包裹<canvas>
。 - 不依赖于jQuery的(我用它来获取父div的宽/高)
- 理想情况下,浏览器调整大小不重绘(但我认为这可能是一个要求)
请参阅下面的代码,它在屏幕中间绘制一个圆圈,宽度为40%,最大为400px。
现场演示: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>
谢谢。有趣的是,如果你想把它放在中心,你看起来像* do *需要将'canvas'包装在'div'中。 'margin:0 auto'似乎并不像画一个div那样将画布居中。 – Portman
@Portman不,你还可以。我只是忘记把display:block放在canvas样式中(它的默认是inline-block,它不会以这种方式进行居中)。使用此修复程序更新答案。 – sethobrien