- Resize HTML5 canvas to fit window
- 17 Answers 17
- CSS Свойство object-fit
- Поддержка браузерами
- CSS свойство object-fit
- Пример
- Пример
- Другой пример
- Пример
- Пример
- Все значения CSS свойства object-fit
- Пример
- CSS Object-* Свойства
- CSS The object-fit Property
- Поддержка браузера
- Свойство объекта CSS-Fit
- Пример
- Пример
- Другой пример
- Пример
- Пример
- Все значения свойства объекта CSS-Fit
- Sizing of HTML content to fit window , but not with responsive design
- 2 Answers 2
- Fit cell width to content
- 6 Answers 6
Resize HTML5 canvas to fit window
How can I automatically scale the HTML5 element to fit the page?
For example, I can get a
17 Answers 17
I believe I have found an elegant solution to this:
JavaScript
CSS
Hasn’t had any large negative performance impact for me, so far.
The following solution worked for me the best. Since I’m relatively new to coding, I like to have visual confirmation that something is working the way I expect it to. I found it at the following site: http://htmlcheats.com/html/resize-the-html5-canvas-dyamically/
The blue border shows you the edge of the resizing canvas, and is always along the edge of the window, visible on all 4 sides, which was NOT the case for some of the other above answers. Hope it helps.
Basically what you have to do is to bind the onresize event to your body, once you catch the event you just need to resize the canvas using window.innerWidth and window.innerHeight.
Setting the canvas coordinate space width and height based on the browser client’s dimensions requires you to resize and redraw whenever the browser is resized.
A less convoluted solution is to maintain the drawable dimensions in Javascript variables, but set the canvas dimensions based on the screen.width, screen.height dimensions. Use CSS to fit:
The browser window generally won’t ever be larger than the screen itself (except where the screen resolution is misreported, as it could be with non-matching dual monitors), so the background won’t show and pixel proportions won’t vary. The canvas pixels will be directly proportional to the screen resolution unless you use CSS to scale the canvas.
A pure CSS approach adding to solution of @jerseyboy above.
Works in Firefox (tested in v29), Chrome (tested in v34) and Internet Explorer (tested in v11).
But take care, as @jerseyboy states in his comment:
Rescaling canvas with CSS is troublesome. At least on Chrome and Safari, mouse/touch event positions will not correspond 1:1 with canvas pixel positions, and you’ll have to transform the coordinate systems.
Unless you want the canvas to upscale your image data automatically (that’s what James Black’s answer talks about, but it won’t look pretty), you have to resize it yourself and redraw the image. Centering a canvas
If your div completely filled the webpage then you can fill up that div and so have a canvas that fills up the div.
You may find this interesting, as you may need to use a css to use percentage, but, it depends on which browser you are using, and how much it is in agreement with the spec: http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element
The intrinsic dimensions of the canvas element equal the size of the coordinate space, with the numbers interpreted in CSS pixels. However, the element can be sized arbitrarily by a style sheet. During rendering, the image is scaled to fit this layout size.
You may need to get the offsetWidth and height of the div, or get the window height/width and set that as the pixel value.
Set initial size.
Update size on window resize.
CSS
JavaScript
If you’re interested in preserving aspect ratios and doing so in pure CSS (given the aspect ratio) you can do something like below. The key is the padding-bottom on the ::content element that sizes the container element. This is sized relative to its parent’s width, which is 100% by default. The ratio specified here has to match up with the ratio of the sizes on the canvas element.
Using jQuery you can track the window resize and change the width of your canvas using jQuery as well.
Something like that
Here’s a tiny, complete Code Snippet that combines all the answers. Press: «Run Code Snippet» then press «Full Page» and resize the window to see it in action:
This snippet uses canvas.clientWidth and canvas.clientHeight rather than window.innerWidth and window.innerHeight to make the snippet run inside a complex layout correctly. However, it works for full window too if you just put it in a div that uses full window. It’s more flexible this way.
The snippet uses the newish window.requestAnimationFrame to repeatedly resize the canvas every frame. If you can’t use this, use setTimeout instead. Also, this is inefficient. To make it more efficient, store the clientWidth and clientHeight and only recalculate and redraw when clientWidth and clientHeight change.
The idea of a «reference» resolution lets you write all of your draw commands using one resolution. and it will automatically adjust to the client size without you having to change the drawing code.
CSS Свойство object-fit
CSS свойство object-fit используется, чтобы указать, как или нужно изменить размер, чтобы соответствовать его контейнеру.
Object-fit — в пер. с анг. — подгонка объекта.
Поддержка браузерами
Числа в таблице указывают первую версию браузера, которая полностью поддерживает свойство.
Свойство | |||||
---|---|---|---|---|---|
object-fit | 31.0 | 16.0 | 36.0 | 7.1 | 19.0 |
CSS свойство object-fit
CSS свойство object-fit используется, чтобы указать, как или должны быть изменены, чтобы соответствовать его контейнеру.
Это свойство указывает содержимому заполнять контейнер различными способами; такие как «сохранить это соотношение сторон» или «растянуть и занять как можно больше места».
Посмотрите на следующее изображение из Парижа, размером 400×300 пикселей:
Однако, если мы добавим изображение более 200×400 пикселей, оно будет выглядеть так:
Пример
Мы видим, что изображение сжимается, чтобы уместиться в контейнер размером 200×400 пикселей, и его исходное соотношение сторон нарушается.
Если мы используем object-fit: cover; — это обрезает стороны изображения, сохраняя пропорции, а также заполняя пространство, как на изображении ниже:
Пример
Другой пример
Здесь у нас есть два изображения, и мы хотим, чтобы они занимали 50% ширины окна браузера и 100% высоты.
В следующем примере мы НЕ используем object-fit , поэтому при изменении размера окна браузера соотношение сторон изображений будет нарушено:
Пример
В следующем примере мы используем object-fit: cover; , поэтому при изменении размера окна браузера соотношение сторон изображений сохраняется:
Пример
Все значения CSS свойства object-fit
Свойство object-fit может иметь следующие значения:
- fill — Это по умолчанию. Размер заменяемого содержимого заполнен в поле содержимого элемента. При необходимости объект будет растянут или сдавлен, чтобы соответствовать
- contain — Замененное содержимое масштабируется, чтобы сохранить его пропорции, в то же время вписываясь в поле содержимого элемента
- cover — Размер заменяемого содержимого соответствует его пропорциям при заполнении всего поля содержимого элемента. Объект будет обрезан, чтобы соответствовать
- none — Замененный контент не изменяется
- scale-down — Размер содержимого определяется так, как если бы он не был указан или содержался (что привело бы к уменьшению размера конкретного объекта)
В следующем примере демонстрируются все возможные значения свойства object-fit :
Пример
CSS Object-* Свойства
В следующей таблице перечислены CSS свойства object-* :
CSS The object-fit Property
Свойство CSS object-fit используется для указания того, как или следует изменить размер в соответствии с его контейнером.
Поддержка браузера
Номера в таблице указывают первую версию браузера, которая полностью поддерживает свойство.
Свойство | |||||
---|---|---|---|---|---|
object-fit | 31.0 | 16.0 | 36.0 | 7.1 | 19.0 |
Свойство объекта CSS-Fit
Свойство CSS object-fit используется для указания способа изменения размера или в соответствии с его контейнером.
Это свойство указывает содержимому заполнять контейнер различными способами; Например, «сохранить это соотношение сторон» или «растянуть и занять столько места, сколько возможно».
Посмотрите на следующее изображение из Парижа, которое является 400кс300 пикселей:
Однако, если мы стиль изображения выше, чтобы быть 200кс400 пикселей, он будет выглядеть так:
Пример
Мы видим, что изображение сжимается в соответствии с контейнером 200кс400 пикселей, и его исходное соотношение сторон уничтожается.
Если мы используем object-fit: cover; он будет отрезать стороны изображения, сохранение соотношения сторон, а также заполнение пространства, как это:
Пример
Другой пример
Здесь мы имеем 2 изображения и мы хотим их заполнить ширину 50% из окна браузера и 100% из высоты.
В следующем примере мы не используем object-fit , поэтому при изменении размера окна браузера, пропорции изображений будут уничтожены:
Пример
В следующем примере мы используем object-fit: cover; , поэтому при изменении размера окна обозревателя сохраняется соотношение сторон изображения:
Пример
Все значения свойства объекта CSS-Fit
Свойство object-fit может иметь следующие значения:
- fill — Это значение по умолчанию. Заменяемое содержимое задается для заполнения поля содержимого элемента. При необходимости объект будет растягиваться или сжиматься по размеру
- contain — Заменяемое содержимое масштабируется для сохранения его пропорций при установке в поле содержимого элемента
- cover — Заменяемое содержимое имеет размер, чтобы сохранить его пропорции при заполнении всего содержимого поля элемента. Объект будет обрезан по размеру
- none — Заменяемое содержимое не изменено
- scale-down — Размер содержимого определяется так, как если бы не было указано ни одного, ни содержащего, (что привело бы к уменьшению размера конкретного объекта)
В следующем примере демонстрируются все возможные значения object-fit Свойство:
Sizing of HTML content to fit window , but not with responsive design
On a number of good websites, I see that the page loads so that the content is the same width as the browser. Specifically on iPad: If you rotate the screen after page load, and zoom out, the content seems to resize in width to match the screen width again. What is the «trick» to achieve this? I don’t want to use the «width:100%» technique, because I would still like the page to be able to «zoom in», where you then you have to pan/scroll to see the rest of the content.
2 Answers 2
Sites like what you are describing are NOT using fixed widths, so setting a width on your elements will not let them to fill the entire screen.
If you want to create flexible and fluid layouts, you DON’T want to do this in your CSS:
You would want to create your elements with percentage based layouts, or viewport based layouts.
You can play around all day trying to get a fixed width to look just right, but if you change your browser, you of course don’t get any responsiveness. Using something like:
will set to only use 50% of the screen width, no matter the browser sizing.
Using VH and VW (viewport height, viewport width) are preferable to using the fixed widths. Fixed widths can be changed depending on screen sizes using media queries, but this is essentially a waste of time and bootstrap will take care of (most) media queries for you.
Check out the bootstrap documentation of the CSS to see how this is achieved: http://getbootstrap.com/css/
You can still zoom in using a library like bootstrap.
Fit cell width to content
Given the following markup, how could I use CSS to force one cell (all cells in column) to fit to the width of the content within it rather than stretch (which is the default behaviour)?
EDIT: I realize I could hard code the width, but I’d rather not do that, as the content which will go in that column is dynamic.
Looking at the image below, the first image is what the markup produces. The second image is what I want.
6 Answers 6
I’m not sure if I understand your question, but I’ll take a stab at it:
why you write
will solve your problem.
For me, this is the best autofit and autoresize for table and its columns (use css !important . only if you can’t without)
Don’t specify css width for table or for table columns. If table content is larger it will go over screen size to.
Setting CSS width to 1% or 100% of an element according to all specs I could find out is related to the parent. Although Blink Rendering Engine (Chrome) and Gecko (Firefox) at the moment of writing seems to handle that 1% or 100% (make a columns shrink or a column to fill available space) well, it is not guaranteed according to all CSS specifications I could find to render it properly.
One option is to replace table with CSS4 flex divs:
That works in new browsers i.e. IE11+ see table at the bottom of the article.
There are many ways to do this!
correct me if I’m wrong but the question is looking for this kind of result.
The first 2 fields will «share» the remaining page (NOTE: if you add more text to either 50% fields it will take more space), and the last field will dominate the table constantly.
If you are happy to let text wrap you can move white-space:nowrap; to the style of the 3rd field
will be the only way to start a new line in that field.
alternatively, you can set a length on the last field ie. width:150px, and leave percentage’s on the first 2 fields.