Program Tip

HTML 캔버스 전체 화면

programtip 2020. 11. 30. 19:49
반응형

HTML 캔버스 전체 화면


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


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

자바 스크립트에는

var canvasW     = 640;
var canvasH     = 480;

그것에. 캔버스의 CSS와 함께 변경해보십시오.

또는 더 나은 방법은 초기화 함수가 CSS에서 캔버스의 크기를 결정하도록하는 것입니다!

편집에 대한 응답으로 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 );
    }
}

또한 래퍼에서 모든 CSS를 제거하십시오. 하지만 js를 편집하여 완전히 제거해야합니다. 그래도 전체 화면으로 볼 수있었습니다.

html, body {
    overflow: hidden;
}

편집 : document.width그리고 document.height 더 이상 사용되지 않습니다 . document.body.clientWidth및로 바꾸기document.body.clientHeight


다음을 기본 html 페이지 또는 함수에 삽입 할 수 있습니다.

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

그런 다음 페이지의 여백을 제거하려면

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

그게 일을해야합니다


최신 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 오류가 발생합니다.

html5-fullscreen에 대한 자세한 내용은 http://updates.html5rocks.com/2011/10/Let-Your-Content-Do-the-Talking-Fullscreen-API를 확인하십시오.


너비와 높이 속성을 캔버스의 크기로 동적으로 설정하기 만하면됩니다. 따라서 CSS를 사용하여 전체 브라우저 창에 걸쳐 확장 한 다음 너비와 높이를 측정하고 할당하는 자바 스크립트에 약간의 기능이 있습니다. 나는 jQuery에별로 익숙하지 않으므로이 의사 코드를 고려하십시오.

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

요소의 너비 및 높이 속성은 내부 렌더링 버퍼에서 사용하는 픽셀 수를 결정합니다. 새 숫자로 변경하면 캔버스가 다른 크기의 빈 버퍼로 다시 초기화됩니다. 브라우저는 너비 및 높이 속성이 실제 실제 픽셀 너비 및 높이와 일치하지 않는 경우에만 그래픽을 늘립니다.


아직 게시되지 않았고 간단한 CSS 수정이기 때문에 :

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

전체 화면 캔버스 배경 (예 : Granim.js)을 적용하려는 경우 유용합니다.


문서로드시

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

A-전체 화면 너비 및 높이 계산 방법

다음은 기능입니다.

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

이것 좀

B-크기 조정으로 전체 화면을 안정적으로 만드는 방법

다음은 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>


function resize() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    render();
}
window.addEventListener('resize', resize, false); resize();
function render() { // draw to screen here
}

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


간단합니다. 캔버스 너비와 높이를 screen.width 및 screen.height로 설정합니다. 그런 다음 F11을 누르십시오! F11은 FFox와 IE에서하는 대부분의 브라우저에서 전체 화면을 만들어야한다고 생각합니다.


도움이 되길 바랍니다.

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

AFAIK, HTML5는 전체 화면을 지원하는 API를 제공하지 않습니다.

이 질문에는 예를 들어 webkitEnterFullscreen웹킷에서 사용하여 html5 비디오를 전체 화면으로 만드는 데 대한 몇 가지 관점이 있습니다.
HTML5 비디오를 전체 화면으로 만드는 방법이 있습니까?


창 크기 조정 이벤트를 캡처하고 캔버스의 크기를 브라우저의 뷰포트로 설정할 수 있습니다.


Get the full width and height of the screen and create a new window set to the appropriate width and height, and with everything disabled. Create a canvas inside of that new window, setting the width and height of the canvas to the width - 10px and the height - 20px (to allow for the bar and the edges of the window). Then work your magic on that canvas.


Well, I was looking to make my canvas fullscreen too, This is how i did it. I'll post the entire index.html since I am not a CSS expert yet : (basically just using position:fixed and width and height as 100% and top and left as 0% and i nested this CSS code for every tag. I also have min-height and min-width as 100%. When I tried it with a 1px border the border size was changing as I zoomed in and out but the canvas remained fullscreen.)

<!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>

EDIT: add this to the canvas element:

<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>

add this to the javascript

canvas.width = window.screen.width;

canvas.height = window.screen.height;

I found this made the drawing a lot smoother than my original comment.

Thanks.

참고URL : https://stackoverflow.com/questions/4037212/html-canvas-full-screen

반응형