我已经搜索了一段时间,但没有找到解决方案。也许只是我的搜索词不对。 嗯,我想根据浏览器窗口的大小使画布居中。画布的大小为800x600。 如果窗口小于800x600,它也应该进行调整(但目前这不是非常重要)。
我已经搜索了一段时间,但没有找到解决方案。也许只是我的搜索词不对。 嗯,我想根据浏览器窗口的大小使画布居中。画布的大小为800x600。 如果窗口小于800x600,它也应该进行调整(但目前这不是非常重要)。
给canvas添加以下CSS样式属性:
canvas {
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
width: 800px;
}
编辑
由于这个答案非常受欢迎,让我再增加一些细节。
上述属性将使画布、div或其他相对于其父元素进行水平居中。无需更改顶部或底部的边距和填充。您可以指定宽度,然后让浏览器使用auto margins填充剩余的空间。
但是,如果您想少打一些字,可以使用任何您希望使用的CSS缩写属性,例如
canvas {
padding: 0;
margin: auto;
display: block;
width: 800px;
}
然而,要使画布在垂直方向上居中需要采用不同的方法。您需要使用绝对定位,并指定宽度和高度。然后将左、右、上和下属性设置为0,让浏览器使用自动边距填充剩余空间。
canvas {
padding: 0;
margin: auto;
display: block;
width: 800px;
height: 600px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
< p >画布将根据第一个具有position
设置为relative
或absolute
的父元素自我居中,如果找不到则基于。
另一种方法是使用display:flex
,它适用于IE11。
另外,请确保使用最新的doctype,如xhtml或html 5。
您可以为canvas添加以下CSS属性:
#myCanvas
{
display: block;
margin: 0 auto;
}
要将画布元素水平居中,您必须将其指定为块级元素,并将其左右边距属性留给浏览器:
canvas{
margin-right: auto;
margin-left: auto;
display: block;
}
如果您希望垂直居中它,则需要将画布元素绝对定位:
canvas{
position: absolute;
top: 50%;
transform: translate(0, -50%);
}
如果您想要水平和垂直居中,请执行以下操作:
canvas{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
了解更多信息,请访问:https://www.w3.org/Style/Examples/007/center.en.html
在HTML中将div居中:
#test {
width: 100px;
height:100px;
margin: 0px auto;
border: 1px solid red;
}
<div id="test">
<canvas width="100" height="100"></canvas>
</div>
只需将高度和宽度更改为所需大小,那么您就可以获得一个居中的div
你也可以使用Flexbox,但canvas
元素必须位于一个div
内,仅将其应用于canvas
元素不起作用。
HTML:
<div class="canvas-container">
<canvas width="150" height="200"></canvas>
</div>
CSS:
.canvas-container {
display: flex;
align-items: center;
justify-content: center;
}
在<canvas>
的父标签中添加text-align: center;
。就是这样。
示例:
<div style="text-align: center">
<canvas width="300" height="300">
<!--your canvas code -->
</canvas>
</div>
#container {
width: 100px;
height:100px;
border: 1px solid red;
margin: 0px auto;
text-align: center;
}
#canvas {
border: 1px solid blue;
width: 50px;
height: 100px;
}
<div id="container">
<canvas id="canvas" width="100" height="100"></canvas>
</div>
<!DOCTYPE html>
<html>
<head>
<style>
.text-center{
text-align:center;
margin-left:auto;
margin-right:auto;
}
</style>
</head>
<body>
<div class="text-center">
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
Your browser does not support the HTML5 canvas tag.
</canvas>
</div>
</body>
</html>
使用网格布局吗?
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
ctx.fillStyle = "#FF0000";
ctx.fillRect(0, 0, canvas.width, canvas.height);
body, html {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
background-color: black;
}
body {
display: grid;
grid-template-rows: auto;
justify-items: center;
align-items: center;
}
canvas {
height: 80vh;
width: 80vw;
display: block;
}
<html>
<body>
<canvas></canvas>
</body>
</html>