Html full page canvas

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Mount an HTML5 canvas to the full width and height of the web page. When the page is resized the canvas resizes too.

License

smallhelm/full-page-canvas

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Mount an HTML5 canvas to the full width and height of the web page. When the page is resized the canvas resizes too.

Usefull for graphic visulizations or games that want to simply use the canvas to controll the entire page.

Your html is just a blank page that includes your javascript.

> html> head> meta name pl-s">viewport" content pl-s">width=device-width, initial-scale=1.0, user-scalable=no"> script src pl-s">main.js">script> head> body>body> html>

Then call mount on this library and it will inject a element into the and return it so you can use it.

Be sure to include this in your html to prevent zooming on mobile devices

meta name pl-s">viewport" content pl-s">width=device-width, initial-scale=1.0, user-scalable=no">

There are 3 ways to include this library

var canvas = require('full-page-canvas').mount(); .

Download this script then include it in your html

script src pl-s">full-page-canvas.min.js">script>
var canvas = FULL_PAGE_CANVAS.mount(); .
require(['full-page-canvas'], function(c)  var canvas = c.mount(); . >);

Copyright (c) 2014 Small Helm LLC

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the «Software»), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED «AS IS», WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

About

Mount an HTML5 canvas to the full width and height of the web page. When the page is resized the canvas resizes too.

Источник

HTML5 canvas full-screen and full-page

HTML5 canvas gets really complex for left brain oriented organisms!

This post tries to explain how to make a canvas element to occupy an entire page and also how to go full screen with canvas.

Even though the focus is mainly on full screen and full page canvas, the sample code demonstrates simple ways to create and color canvas.

Let’s see some code, without dry theory! :

Code to make canvas occupy full page :

// Get the canvas element form the page var canvas = document.getElementById("canvas"); /* Rresize the canvas to occupy the full page, by getting the widow width and height and setting it to canvas*/ canvas.width = window.innerWidth; canvas.height = window.innerHeight; //Done! Enjoy full page canvas!

Code to make canvas element to occupy full-screen :

// Get the canvas element form the page var canvas = document.queryselector('canvas'); function fullscreen(){ var el = document.getElementById('canvas'); if(el.webkitRequestFullScreen) { el.webkitRequestFullScreen(); } else { el.mozRequestFullScreen(); } } canvas.addEventListener("click",fullscreen)

Check out the demos! :

Full screen will be very useful for games indeed! But this is best /me can do with graphics!

Источник

Как использовать Fullscreen API

В комплекте с HTML5 появилось большое количество нового API. Одним из них является Fullscreen API, которое предоставляет нативный способ для браузера, позволяющий отобразить веб-страницу в полноэкранном режиме для пользователя.
А еще хорошо то, что Fullscreen API является очень простым в использовании.

Методы

Методы, входящие в состав Fullscreen API

Согласно стандарту W3C название некоторых методов было изменено, но старые названия продолжают работать.

Document.getElementById("myCanvas").requestFullscreen() 
Document.fullscreenEnabled 
Document.fullScreenElement 

Возвращает элемент, который в настоящее время находится в полноэкранном режиме.
Обратите внимание, что это стандартные методы. Для того, что бы они работали во всех браузерах, нам необходимо использовать префиксы.

Поддерживаемые браузеры
  • Chrome
  • Firefox
  • Safari
  • Opera Next
  • Opera (начиная с версии 12.10)
  • Internet Explorer (начиная с версии 11)

Более подробная информация по поддержке Fullscreen API современными браузерами доступна по ссылке.

Будет полезным скрипт, позволяющий автоматически определять поддержку браузером Fullscreen API и в случае необходимости добавляет необходимый префикс к методам Fullscreen API.

Запуск полноэкранного режима

Сначала мы должны выяснить, какой метод распознает наш браузер. Для этого мы создадим функцию, которая будет проверять поддержку метода и вызовет рабочий метод:

function fullScreen(element) < if(element.requestFullscreen) < element.requestFullscreen(); >else if(element.webkitrequestFullscreen) < element.webkitRequestFullscreen(); >else if(element.mozRequestFullscreen) < element.mozRequestFullScreen(); >> 

Если любой из requestFullscreen методов возвращают истинное значении, то вызывается тот метод, который поддерживается конкретным браузером и использует псевдокласс с его префикском.

После этого нужно вызвать функцию для полноэкранного режима:

//для всей страницы var html = document.documentElement; fullScreen(html); 
// Для конкретного элемента на странице var canvas = document.getElementById('mycanvas'); fullScreen(canvas); 

Результатом будет запрос пользователю с просьбой разрешить переход в полноэкранный режим, если пользователь разрешит переход, то все панели инструментов в браузере исчезнут, и на всем экране будет веб-страница или один элемент.

Отмена полноэкранного режима

Этот метод также требует префиксы, поэтому мы будем использовать ту же идею для проверки поддержки методов браузерами. Создадим функцию, которая будет определять, какой префикс мы должны использовать в зависимости от браузера пользователя.

Этот метод не требует никаких параметров, поскольку в отличие от метода requestFullscreen он всегда относится ко всему документу.

function fullScreenCancel() < if(document.requestFullscreen) < document.requestFullscreen(); >else if(document.webkitRequestFullscreen ) < document.webkitRequestFullscreen(); >else if(document.mozRequestFullscreen) < document.mozRequestFullScreen(); >> 
//отменяет полноэкранный режим fullScreenCancel(); 

CSS псевдоклассы

Он может быть использован для задания стиля любых элементов на веб-странице, когда страница или элемент находится в полноэкранном режиме. Данный псевдокласс может пригодиться для задания размера элементов страницы, потому что в полноэкранном режиме происходит увеличение и самого рабочего пространства браузера.

:-webkit-full-screen :-moz-full-screen :full-screen /*изменения одного элемента img*/ :-webkit-full-screen img < width: 100%; height: 100%; >:-moz-full-screen img

Учтите, что нельзя отделять префиксы запятыми, потому что браузер не сможет распознать их:

/* Это не будет работать */ :-webkit-full-screen img,:-moz-full-screen img

Для того, чтобы стили применялись правильно, вы должны поместить каждый псевдокласс с префиксом браузера в своем собственном блоке.

Заключение

Этот JavaScript API является одним из наименее известных из поставляемых с HTML5, но это эффективный и простой в реализации метод, позволяющий сфокусировать внимание пользователя на одном элементе, что особенно полезно для видео, изображений и игр.

Источник

Full Screen Canvas

Heads up! This blog post hasn’t been updated in over 2 years. CodePen is an ever changing place, so if this post references features, you’re probably better off checking the docs. Get in touch with support if you have further questions.

It is a fairly common need when doing stuff with that you want as much screen real estate as you can get. Ideally covering the browser window edge to edge. This should be as simple as this:

var can = document.getElementById("my-canvas"); can.style.width = window.innerWidth + "px"; can.style.height = window.innerHeight + "px";

And it is that easy. Except… sadly on CodePen.

There is a little browser bug that makes us have to do a tiny bit more work to get this working. The issue is that CodePen renders the previews of the code you create in iframes. We do that to give a completely clean slate for demos as well as provide some security. When you change your code, we refresh that preview in the iframe. We literally re-render the entire demo. We do that so it behaves as expected, and things like your DOM ready functions will fire correctly. But there are some quirks. One of which is that when you re-render an iframe, sometimes

window.innerHeight is a wrong value or zero. But just for a split nanosecond at the beginning of the render. If you slow down the execution of the JavaScript at all, the value will be fine.

var can = document.getElementById("my-canvas"); can.style.width = window.innerWidth + "px"; setTimeout(function() < can.style.height = window.innerHeight + "px"; >, 0);

This is in Blink/WebKit browsers like Chrome/Safari, not Gecko browsers like Firefox.

The preview area in the editor can be resized, and of course browser windows can be resized. Your canvas is set to a fixed size now if you use the code above, and will stay that way unless you change it. So, it can be a good idea to resize that canvas when the window changes. You can do that like this:

var can = document.getElementById("my-canvas"); function resizeCanvas() < can.style.width = window.innerWidth + "px"; setTimeout(function() < can.style.height = window.innerHeight + "px"; >, 0); >; // Webkit/Blink will fire this on load, but Gecko doesn't. window.onresize = resizeCanvas; // So we fire it manually. resizeCanvas();

With jQuery that would be like:

var win = $(window); function resize() < $("#my-canvas") // best to save a reference of this .width(win.width()) .height(win.height()); >win.resize(resize).resize();

You also may trigger scrollbars by setting a canvas to the exact full size of the window. Seems strange since it’s not bigger than the window, it’s the exact reported size. But even if somehow it becomes 1px bigger, that will trigger a scrollbar and then that scrollbar will trigger the scrollbar on the other axis. I’ve found if you subtract 4px from the height of window.innerHeight before applying you’re OK, but that leaves a 1px gap at the bottom. Blech. If every single pixel isn’t vital in your demo (like it might be in a game), you can just leave it as is and fix it with CSS.

If it truly is a browser bug that causes the window.innerHeight wrongness we’ll see who we can tap to get it fixed. Or if we can figure out a fix on the CodePen side without being too intrusive, we’ll do that.

Pens

Оцените статью