Javascript HTML Canvas 全屏
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4037212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML Canvas Full Screen
提问by Cameron
I'm playing with the following application using the HTML Canvas: http://driz.co.uk/particles/
我正在使用 HTML Canvas 使用以下应用程序:http: //driz.co.uk/particles/
At the moment it is set to 640x480 pixels, but I would like to make it full screen as it will be shown a projector. However as far as I can tell I cannot set the canvas size to be 100% as the variables only except numbers and not the %. Using CSS just stretches it rather than making it actual full screen.
目前它设置为 640x480 像素,但我想让它全屏显示,因为它将显示为投影仪。但是,据我所知,我不能将画布大小设置为 100% 作为变量,只有数字而不是 %。使用 CSS 只是拉伸它而不是让它真正全屏。
Any ideas?
有任何想法吗?
EDIT: Tried finding the height and width using jQuery but it breaks the canvas any ideas why?
编辑:尝试使用 jQuery 找到高度和宽度,但它打破了画布任何想法为什么?
var $j = jQuery.noConflict();
var canvas;
var ctx;
var canvasDiv;
var outerDiv;
var canvasW = $j('body').width();
var canvasH = $j('body').height();
//var canvasW = 640;
//var canvasH = 480;
var numMovers = 550;
var movers = [];
var friction = .96;
var radCirc = Math.PI * 2;
var mouseX, mouseY, mouseVX, mouseVY, prevMouseX = 0, prevMouseY = 0;
var isMouseDown = true;
function init()
{
canvas = document.getElementById("mainCanvas");
if( canvas.getContext )
{
setup();
setInterval( run , 33 );
}
}
function setup()
{
outerDiv = document.getElementById("outer");
canvasDiv = document.getElementById("canvasContainer");
ctx = canvas.getContext("2d");
var i = numMovers;
while( i-- )
{
var m = new Mover();
m.x = canvasW * .5;
m.y = canvasH * .5;
m.vX = Math.cos(i) * Math.random() * 25;
m.vY = Math.sin(i) * Math.random() * 25;
m.size = 2;
movers[i] = m;
}
document.onmousedown = onDocMouseDown;
document.onmouseup = onDocMouseUp;
document.onmousemove = onDocMouseMove;
}
function run()
{
ctx.globalCompositeOperation = "source-over";
ctx.fillStyle = "rgba(8,8,12,.65)";
ctx.fillRect( 0 , 0 , canvasW , canvasH );
ctx.globalCompositeOperation = "lighter";
mouseVX = mouseX - prevMouseX;
mouseVY = mouseY - prevMouseY;
prevMouseX = mouseX;
prevMouseY = mouseY;
var toDist = canvasW / 1.15;
var stirDist = canvasW / 8;
var blowDist = canvasW / 2;
var Mrnd = Math.random;
var Mabs = Math.abs;
var Msqrt = Math.sqrt;
var Mcos = Math.cos;
var Msin = Math.sin;
var Matan2 = Math.atan2;
var Mmax = Math.max;
var Mmin = Math.min;
var i = numMovers;
while( i-- )
{
var m = movers[i];
var x = m.x;
var y = m.y;
var vX = m.vX;
var vY = m.vY;
var dX = x - mouseX;
var dY = y - mouseY;
var d = Msqrt( dX * dX + dY * dY );
var a = Matan2( dY , dX );
var cosA = Mcos( a );
var sinA = Msin( a );
if( isMouseDown )
{
if( d < blowDist )
{
var blowAcc = ( 1 - ( d / blowDist ) ) * 2;
vX += cosA * blowAcc + .5 - Mrnd();
vY += sinA * blowAcc + .5 - Mrnd();
}
}
if( d < toDist )
{
var toAcc = ( 1 - ( d / toDist ) ) * canvasW * .0014;
vX -= cosA * toAcc;
vY -= sinA * toAcc;
}
if( d < stirDist )
{
var mAcc = ( 1 - ( d / stirDist ) ) * canvasW * .00022;
vX += mouseVX * mAcc;
vY += mouseVY * mAcc;
}
vX *= friction;
vY *= friction;
var avgVX = Mabs( vX );
var avgVY = Mabs( vY );
var avgV = ( avgVX + avgVY ) * .5;
if( avgVX < .1 ) vX *= Mrnd() * 3;
if( avgVY < .1 ) vY *= Mrnd() * 3;
var sc = avgV * .45;
sc = Mmax( Mmin( sc , 3.5 ) , .4 );
var nextX = x + vX;
var nextY = y + vY;
if( nextX > canvasW )
{
nextX = canvasW;
vX *= -1;
}
else if( nextX < 0 )
{
nextX = 0;
vX *= -1;
}
if( nextY > canvasH )
{
nextY = canvasH;
vY *= -1;
}
else if( nextY < 0 )
{
nextY = 0;
vY *= -1;
}
m.vX = vX;
m.vY = vY;
m.x = nextX;
m.y = nextY;
ctx.fillStyle = m.color;
ctx.beginPath();
ctx.arc( nextX , nextY , sc , 0 , radCirc , true );
ctx.closePath();
ctx.fill();
}
//rect( ctx , mouseX - 3 , mouseY - 3 , 6 , 6 );
}
function onDocMouseMove( e )
{
var ev = e ? e : window.event;
mouseX = ev.clientX - outerDiv.offsetLeft - canvasDiv.offsetLeft;
mouseY = ev.clientY - outerDiv.offsetTop - canvasDiv.offsetTop;
}
function onDocMouseDown( e )
{
isMouseDown = true;
return false;
}
function onDocMouseUp( e )
{
isMouseDown = true;
return false;
}
// ==========================================================================================
function Mover()
{
this.color = "rgb(" + Math.floor( Math.random()*255 ) + "," + Math.floor( Math.random()*255 ) + "," + Math.floor( Math.random()*255 ) + ")";
this.y = 0;
this.x = 0;
this.vX = 0;
this.vY = 0;
this.size = 0;
}
// ==========================================================================================
function rect( context , x , y , w , h )
{
context.beginPath();
context.rect( x , y , w , h );
context.closePath();
context.fill();
}
// ==========================================================================================
采纳答案by Nick Larsen
The javascript has
javascript有
var canvasW = 640;
var canvasH = 480;
in it. Try changing those as well as the css for the canvas.
在里面。尝试更改这些以及画布的 css。
Or better yet, have the initialize function determine the size of the canvas from the css!
或者更好的是,让 initialize 函数根据 css 确定画布的大小!
in response to your edits, change your init function:
响应您的编辑,更改您的 init 函数:
function init()
{
canvas = document.getElementById("mainCanvas");
canvas.width = document.body.clientWidth; //document.width is obsolete
canvas.height = document.body.clientHeight; //document.height is obsolete
canvasW = canvas.width;
canvasH = canvas.height;
if( canvas.getContext )
{
setup();
setInterval( run , 33 );
}
}
Also remove all the css from the wrappers, that just junks stuff up. You have to edit the js to get rid of them completely though... I was able to get it full screen though.
还要从包装器中删除所有 css,这只会使东西变得垃圾。你必须编辑 js 以完全摆脱它们......不过我能够全屏显示。
html, body {
overflow: hidden;
}
Edit: document.width
and document.height
are obsolete. Replace with document.body.clientWidth
and document.body.clientHeight
编辑:document.width
并且document.height
已经过时。替换为document.body.clientWidth
和document.body.clientHeight
回答by Martyn
You can just insert the following in to your main html page, or a function:
您可以将以下内容插入到您的主 html 页面或函数中:
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
Then to remove the margins on the page
然后删除页面上的边距
html, body {
margin: 0 !important;
padding: 0 !important;
}
That should do the job
那应该做的工作
回答by Frederic
The newest Chrome and Firefox support a fullscreen API, but setting to fullscreen is like a window resize. Listen to the onresize-Event of the window-object:
最新的 Chrome 和 Firefox 支持全屏 API,但设置为全屏就像调整窗口大小。监听 window-object 的 onresize-Event:
$(window).bind("resize", function(){
var w = $(window).width();
var h = $(window).height();
$("#mycanvas").css("width", w + "px");
$("#mycanvas").css("height", h + "px");
});
//using HTML5 for fullscreen (only newest Chrome + FF)
$("#mycanvas")[0].webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); //Chrome
$("#mycanvas")[0].mozRequestFullScreen(); //Firefox
//...
//now i want to cancel fullscreen
document.webkitCancelFullScreen(); //Chrome
document.mozCancelFullScreen(); //Firefox
This doesn't work in every browser. You should check if the functions exist or it will throw an js-error.
这不适用于每个浏览器。您应该检查这些函数是否存在,否则它会抛出一个 js 错误。
for more info on html5-fullscreen check this: http://updates.html5rocks.com/2011/10/Let-Your-Content-Do-the-Talking-Fullscreen-API
有关 html5-fullscreen 的更多信息,请查看:http: //updates.html5rocks.com/2011/10/Let-Your-Content-Do-the-Talking-Fullscreen-API
回答by Blixxy
All you need to do is set the width and height attributes to be the size of the canvas, dynamically. So you use CSS to make it stretch over the entire browser window, then you have a little function in javascript which measures the width and height, and assigns them. I'm not terribly familliar with jQuery, so consider this psuedocode:
您需要做的就是将宽度和高度属性动态设置为画布的大小。所以你使用 CSS 让它在整个浏览器窗口上伸展,然后你在 javascript 中有一个小函数来测量宽度和高度,并分配它们。我不是很熟悉 jQuery,所以考虑这个伪代码:
window.onload = window.onresize = function() {
theCanvas.width = theCanvas.offsetWidth;
theCanvas.height = theCanvas.offsetHeight;
}
The width and height attributes of the element determine how many pixels it uses in it's internal rendering buffer. Changing those to new numbers causes the canvas to reinitialise with a differently sized, blank buffer. Browser will only stretch the graphics if the width and height attributes disagree with the actual real world pixel width and height.
元素的宽度和高度属性决定了它在内部渲染缓冲区中使用的像素数。将这些更改为新数字会导致画布使用不同大小的空白缓冲区重新初始化。如果宽度和高度属性与实际现实世界的像素宽度和高度不一致,浏览器只会拉伸图形。
回答by chillyistkult
Because it was not posted yet and is a simple css fix:
因为它还没有发布并且是一个简单的 css 修复:
#canvas {
position:fixed;
left:0;
top:0;
width:100%;
height:100%;
}
Works great if you want to apply a fullscreen canvas background (for example with Granim.js).
如果您想应用全屏画布背景(例如使用 Granim.js),效果会很好。
回答by Hyman
On document load set the
在文档加载时设置
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
回答by Levent Divilioglu
A - How To Calculate Full Screen Width & Height
A - 如何计算全屏宽度和高度
Here is the functions;
这是功能;
canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
Check this out
检查了这出
B - How To Make Full Screen Stable With Resize
B - 如何通过调整大小使全屏稳定
Here is the resize method for the resize event;
这是resize事件的resize方法;
function resizeCanvas() {
canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
WIDTH = canvas.width;
HEIGHT = canvas.height;
clearScreen();
}
C - How To Get Rid Of Scroll Bars
C - 如何摆脱滚动条
Simply;
简单地;
<style>
html, body {
overflow: hidden;
}
</style>
D - Demo Code
D - 演示代码
<html>
<head>
<title>Full Screen Canvas Example</title>
<style>
html, body {
overflow: hidden;
}
</style>
</head>
<body onresize="resizeCanvas()">
<canvas id="mainCanvas">
</canvas>
<script>
(function () {
canvas = document.getElementById('mainCanvas');
ctx = canvas.getContext("2d");
canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
WIDTH = canvas.width;
HEIGHT = canvas.height;
clearScreen();
})();
function resizeCanvas() {
canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
WIDTH = canvas.width;
HEIGHT = canvas.height;
clearScreen();
}
function clearScreen() {
var grd = ctx.createLinearGradient(0,0,0,180);
grd.addColorStop(0,"#6666ff");
grd.addColorStop(1,"#aaaacc");
ctx.fillStyle = grd;
ctx.fillRect( 0, 0, WIDTH, HEIGHT );
}
</script>
</body>
</html>
回答by or linzer
I hope it will be useful.
我希望它会很有用。
// Get the canvas element
var canvas = document.getElementById('canvas');
var isInFullScreen = (document.fullscreenElement && document.fullscreenElement !== null) ||
(document.webkitFullscreenElement && document.webkitFullscreenElement !== null) ||
(document.mozFullScreenElement && document.mozFullScreenElement !== null) ||
(document.msFullscreenElement && document.msFullscreenElement !== null);
// Enter fullscreen
function fullscreen(){
if(canvas.RequestFullScreen){
canvas.RequestFullScreen();
}else if(canvas.webkitRequestFullScreen){
canvas.webkitRequestFullScreen();
}else if(canvas.mozRequestFullScreen){
canvas.mozRequestFullScreen();
}else if(canvas.msRequestFullscreen){
canvas.msRequestFullscreen();
}else{
alert("This browser doesn't supporter fullscreen");
}
}
// Exit fullscreen
function exitfullscreen(){
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}else{
alert("Exit fullscreen doesn't work");
}
}
回答by jaggedsoft
function resize() {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
render();
}
window.addEventListener('resize', resize, false); resize();
function render() { // draw to screen here
}
回答by user6063291
it's simple, set canvas width and height to screen.width and screen.height. then press F11! think F11 should make full screen in most browsers does in FFox and IE.
很简单,将画布宽度和高度设置为screen.width 和screen.height。然后按F11!认为 F11 应该在大多数浏览器中全屏显示在 FFox 和 IE 中。