HTML Canvas全屏

时间:2010-10-27 20:05:34

标签: javascript html5 canvas

我正在使用HTML Canvas使用以下应用程序:http://driz.co.uk/particles/

目前设置为640x480像素,但我想将其全屏显示,因为它将显示为投影仪。但是据我所知,除了数字而不是%之外,我不能将画布大小设置为100%作为变量。使用CSS只是拉伸它而不是实际全屏。

有什么想法吗?

编辑:尝试使用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();
}


// ==========================================================================================

15 个答案:

答案 0 :(得分:49)

javascript有

var canvasW     = 640;
var canvasH     = 480;

在里面。尝试更改它们以及画布的CSS。

或者更好的是,让初始化函数从css中确定画布的大小!

响应您的编辑,更改您的初始化函数:

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 );
    }
}

同时从包装器中删除所有css,这只是简单的东西。你必须编辑js才能完全摆脱它们......虽然我能够全屏播放它。

html, body {
    overflow: hidden;
}

修改document.widthdocument.height are obsolete。替换为document.body.clientWidthdocument.body.clientHeight

答案 1 :(得分:32)

您只需将以下内容插入主html页面或功能:

即可
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

然后删除页面上的边距

html, body {
    margin: 0 !important;
    padding: 0 !important;
}

那应该做的工作

答案 2 :(得分:14)

最新的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

这在每个浏览器中都不起作用。您应检查函数是否存在,否则将引发js-error。

有关html5-fullscreen的更多信息,请查看以下内容: http://updates.html5rocks.com/2011/10/Let-Your-Content-Do-the-Talking-Fullscreen-API

答案 3 :(得分:8)

您需要做的就是动态地将width和height属性设置为画布的大小。所以你使用CSS让它延伸到整个浏览器窗口,然后你在javascript中有一个小函数来测量宽度和高度,并分配它们。我对jQuery并不十分熟悉,所以请考虑这个伪代码:

window.onload = window.onresize = function() {
  theCanvas.width = theCanvas.offsetWidth;
  theCanvas.height = theCanvas.offsetHeight;
}

元素的width和height属性决定了它在内部渲染缓冲区中使用的像素数。将这些更改为新数字会导致画布使用不同大小的空白缓冲区重新初始化。如果宽度和高度属性与实际的真实世界像素宽度和高度不一致,浏览器将仅拉伸图形。

答案 4 :(得分:6)

因为它尚未发布并且是一个简单的css修复:

#canvas {
    position:fixed;
    left:0;
    top:0;
    width:100%;
    height:100%;
}

如果要应用全屏画布背景(例如使用Granim.js),则效果很好。

答案 5 :(得分:4)

在文档加载设置

canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

答案 6 :(得分:3)

A - 如何计算全屏宽度&amp;高度

这是功能;

canvas.width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
canvas.height = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

选中此out

B - 如何通过调整大小使全屏稳定

这是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 - 如何摆脱滚动条

只需;

<style>
    html, body {
        overflow: hidden;
    }
</style>

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>

答案 7 :(得分:1)

function dataLoaded () {
  if (markers.drinks.items.length > 1) {
    showPlacesMarkers();
  } else {
    dataLoaded();
  }
}

https://jsfiddle.net/jy8k6hfd/2/

答案 8 :(得分:1)

它很简单,将画布宽度和高度设置为screen.width和screen.height。然后按F11!认为F11应该在大多数浏览器中全屏显示在FFox和IE中。

答案 9 :(得分:1)

我希望它会有用。

// 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");
    }
}

答案 10 :(得分:0)

AFAIK,HTML5不提供支持全屏的API。

这个问题对于使用webkit中的webkitEnterFullscreen制作html5视频全屏有一些观点。例如 Is there a way to make html5 video fullscreen

答案 11 :(得分:0)

您可以捕获窗口调整大小事件并将画布的大小设置为浏览器的视口。

答案 12 :(得分:0)

获取屏幕的整个宽度和高度,并创建一个设置为适当宽度和高度的新窗口,并禁用所有内容。在该新窗口内创建一个画布,将画布的宽度和高度设置为宽度 - 10px和高度 - 20px(以允许窗口和窗口的边缘)。然后在画布上运用你的魔法。

答案 13 :(得分:0)

好吧,我也希望将画布全屏显示,这就是我的方法。由于我还不是CSS专家,因此我将发布整个index.html :(基本上只使用position:fixed并将width和height设置为100%,top和left设置为0%,并且我为每个标签嵌套了此CSS代码。也将min-height和min-width设为100%。当我尝试使用1px边框时,边框大小在放大和缩小时都在变化,但是画布仍保持全屏显示。)

<!DOCTYPE html>
<html style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">
<head>
<title>MOUSEOVER</title>
<script "text/javascript" src="main.js"></script>

</head>


<body id="BODY_CONTAINER" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">



<div id="DIV_GUI_CONTAINER" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">

<canvas id="myCanvas"  style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">

</canvas>

</div>


</body>


</html>

编辑: 将此添加到canvas元素:

<canvas id="myCanvas" width="" height="" style="position:fixed;min-height:100%;min-width:100%;height:100%;width:100%;top:0%;left:0%;resize:none;">

</canvas>

将此添加到javascript

canvas.width = window.screen.width;

canvas.height = window.screen.height;

我发现这使绘图比我的原始注释要平滑得多。

谢谢。

答案 14 :(得分:0)

如果要在演示文稿中显示它,请考虑使用requestFullscreen()方法

let canvas = document.getElementById("canvas_id");
canvas.requestFullscreen();

无论当前情况如何,都应使其全屏显示。

还要检查支持表https://caniuse.com/?search=requestFullscreen