如何在html5中居中画布

如何在html5中居中画布

本文介绍了如何在html5中居中画布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找解决方案一段时间,但没有找到任何东西.也许这只是我的搜索词.好吧,我正在尝试根据浏览器窗口的大小使画布居中.画布为 800x600.如果窗口低于 800x600,它也应该调整大小(但目前这不是很重要)

I've been searching for a solution for a while now, but haven't found anything. Maybe it's just my search terms.Well, I'm trying to make the canvas center according to the size of the browser window. The canvas is 800x600.And if the window gets below 800x600, it should resize as well(but that's not very important at the moment)

推荐答案

为画布提供以下 css 样式属性:

Give the canvas the following css style properties:

canvas {
    padding-left: 0;
    padding-right: 0;
    margin-left: auto;
    margin-right: auto;
    display: block;
    width: 800px;
}

编辑

由于这个答案很受欢迎,让我补充一点细节.

Since this answer is quite popular, let me add a little bit more details.

上述属性将水平将画布、div 或任何其他相对于其父节点的节点居中.无需更改顶部或底部边距和填充.您指定宽度并让浏览器使用自动边距填充剩余空间.

The above properties will horizontally center the canvas, div or whatever other node you have relative to it's parent. There is no need to change the top or bottom margins and paddings. You specify a width and let the browser fill the remaining space with the auto margins.

但是,如果您想减少输入,您可以使用任何您希望的 css 速记属性,例如

However, if you want to type less, you could use whatever css shorthand properties you wish, such as

canvas {
    padding: 0;
    margin: auto;
    display: block;
    width: 800px;
}

将画布垂直居中需要不同的方法.您需要使用绝对定位,并指定宽度和高度.然后将 left、right、top 和 bottom 属性设置为 0,让浏览器用自动边距填充剩余空间.

Centering the canvas vertically requires a different approach however. You need to use absolute positioning, and specify both the width and the height. Then set the left, right, top and bottom properties to 0 and let the browser fill the remaining space with the auto margins.

canvas {
    padding: 0;
    margin: auto;
    display: block;
    width: 800px;
    height: 600px;
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
}

画布将基于将 position 设置为 relativeabsolute 的第一个父元素居中,或者如果没有设置则以主体为中心找到了.

The canvas will center itself based on the first parent element that has position set to relative or absolute, or the body if none is found.

另一种方法是使用 display: flex,在 IE11 中可用

Another approach would be to use display: flex, that is available in IE11

另外,请确保您使用最新的文档类型,例如 xhtml 或 html 5.

Also, make sure you use a recent doctype such as xhtml or html 5.

这篇关于如何在html5中居中画布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 07:29