为画布提供以下 CSS 样式属性:
canvas {
padding-left: 0;
padding-right: 0;
margin-left: auto;
margin-right: auto;
display: block;
width: 800px;
}
编辑
由于这个答案很受欢迎,让我添加更多细节。
上述属性将水平居中画布、div 或您拥有的任何其他节点相对于它的父节点。无需更改顶部或底部边距和填充。您指定宽度并让浏览器使用自动边距填充剩余空间。
但是,如果您想输入更少的内容,您可以使用任何您希望的 css 速记属性,例如
canvas {
padding: 0;
margin: auto;
display: block;
width: 800px;
}
然而,垂直居中画布需要不同的方法。您需要使用绝对定位,并指定宽度和高度。然后将left、right、top和bottom属性设置为0,让浏览器用自动边距填充剩余空间。
canvas {
padding: 0;
margin: auto;
display: block;
width: 800px;
height: 600px;
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
}
画布将根据第一个将 position
设置为 relative
或 absolute
的父元素或主体(如果没有找到)居中。
另一种方法是使用 display: flex
,它在 IE11 中可用
此外,请确保您使用最新的文档类型,例如 xhtml 或 html 5。
你可以给你的画布 ff 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;
}
仅当您的画布与容器的宽度相同时,上述答案才有效。
这无论如何都有效:
#container { 宽度:100px;高度:100px;边框:1px 纯红色;边距:0px 自动;文本对齐:居中; } #canvas { 边框:1px 纯蓝色;宽度:50px;高度:100px; }
将 text-align: center;
添加到 <canvas>
的父标记。而已。
例子:
<div style="text-align: center">
<canvas width="300" height="300">
<!--your canvas code -->
</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>
我遇到了同样的问题,因为我有许多不同宽度的图片,我只加载了高度信息。设置宽度允许浏览器拉伸和挤压图片。我通过将 image_tag 行之前的文本行居中来解决问题(也摆脱了 float: left;)。我本来希望文本左对齐,但这是一个小小的不便,我可以容忍。
使用网格?
const canvas = document.querySelector('canvas'); const ctx = canvas.getContext('2d'); ctx.fillStyle = "#FF0000"; ctx.fillRect(0, 0, canvas.width, canvas.height);正文,html {高度:100%;宽度:100%;边距:0;填充:0;背景颜色:黑色; } 身体 { 显示:网格;网格模板行:自动;对齐项目:中心;对齐项目:居中; }画布{高度:80vh;宽度:80vw;显示:块; }
不定期副业成功案例分享