【发布时间】:2020-07-02 21:09:36
【问题描述】:
HTML5 <canvas> 元素不接受其width 和height 属性的相对大小(百分比)。
我想要完成的是让我的画布相对于窗口大小。到目前为止,这是我想出的,但我想知道是否有更好的方法:
- 更简单
- 不需要将
<canvas>包装在<div>中。 - 不依赖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>
【问题讨论】:
标签: javascript html canvas