我可以使用什么CSS来缩放画布来填充它的容器,而不改变它的长宽比? [英] What CSS can I use that will scale the canvas to fill its container without changing its aspect ratio?
问题描述
我有一个具有特定大小的画布(让我们说,300x150)。我可以使用什么CSS来缩放画布来填充它的容器,而不改变它的宽高比,并且在缩放后留下的任何额外空间水平和垂直居中。
I have a canvas with a specific size (lets, say 300x150). What CSS can I use that will scale the canvas to fill its container without changing its aspect ratio and center it both horizontally and vertically for any extra space that's left after scaling.
我尝试过
* {
box-sizing: border-box;
-moz-box-sizing: border-box;
}
html, body {
height: 100%;
}
#container {
width: 100%;
height: 100%;
text-align: center;
}
canvas {
width: auto;
height: auto;
max-width: 100%;
max-height: 100%;
}
<div id="container">
<canvas></canvas>
</div>
除了垂直居中之外,它都适用。我尝试将 #container
更改为 table-cell
和 vertical-align:middle
与
display:table
的外部容器。这有垂直居中,但它不再水平。我尝试将 #container
更改为flex box,但后来开始将画布垂直错误。
That works for everything except vertical centering. I tried changing #container
to a table-cell
with vertical-align: middle
with an outer container with display:table
. That got vertical centering but it no longer scaled horizontally. I tried changing #container
to flex box but then it started scaling the canvas vertically wrong.
这样的作品。
canvas {
max-width: 100%;
max-height: 100%;
margin: auto;
position: absolute;
top: 0; left: 0; bottom: 0; right: 0;
}
不幸的是,画布从未延伸,只是收缩
Unfortunately the canvas is never stretched, only shrunk
推荐答案
我建议一个小的css调整,应该为你工作。
I would suggest a small css tweak that should work for you.
#container {
width: 100%;
height: 100%;
text-align: center;
position:relative;
}
canvas {
width:100%;
height:100%;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
}
position:absolute
元素通常应由 position:relative
父容器包围。
设置 realtive
到 #container
将使 canvas的偏移
相对于其父 #container
。这是 演示
position:absolute
elements should generally be surrounded by position:relative
parent containers.
Setting realtive
to #container
will make the offsets of canvas
relative to its parent which is #container
. Here is a Demo.
这篇关于我可以使用什么CSS来缩放画布来填充它的容器,而不改变它的长宽比?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!