问题描述
HTML5 元素不接受其 width
和的相对大小(百分比) height
属性。
The HTML5 <canvas>
element does not accept relative sizes (percent) for its width
and height
properties.
我想要完成的是让我的画布相对于窗口大小。这是我到目前为止,但我想知道是否有一个更好的方法是:
What I'm trying to accomplish is to have my canvas sized relative to the window. This is what I've come up with so far, but I'm wondering if there is a better way that is:
- Simpler
- 不需要在
< div> < canvas>
>。 - 不依赖于jQuery(我使用它来获取父div的宽度/高度)
- 理想情况下, (但我认为这可能是一个要求)
- Simpler
- Does not require wrapping the
<canvas>
in a<div>
. - Not dependent on jQuery (I use it to get the width/height of the parent div)
- Ideally, doesn't redraw on browser resize (but I think that might be a requirement)
请参阅下面的代码,它在屏幕中间绘制一个圆圈, 40%宽,最大400px。
See below for the code, which draws a circle in the middle of the screen, 40% wide up to a maximum of 400px.
现场演示:。
I coded up the slightly simplified version here.
对于#4,你是对运气不好。可以在设置宽度和高度之前进行检查,如果不需要调整大小,则可以单独使用canvas,这将消除一些重绘,但是你不能删除所有的重绘。
For #4, you're right about being out of luck. It's possible to check before setting width and height and leave the canvas alone if it doesn't need resizing, which would eliminate some of the redraws, but you can't get rid of all of them.
编辑:波特曼指出,我搞砸了中心的风格。更新版本。
Portman pointed out I messed up the centering style. Updated version here.
这篇关于相对调整HTML画布大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!