Programing

HTML5 Canvas 뷰포트의 너비 100 % 높이?

lottogame 2020. 6. 21. 19:41
반응형

HTML5 Canvas 뷰포트의 너비 100 % 높이?


뷰포트의 너비와 높이를 100 % 차지하는 캔버스 요소를 만들려고합니다.

내 예제 에서 발생하는 것을 볼 수 있지만 Chrome과 FireFox에 스크롤 막대를 추가하고 있습니다. 여분의 스크롤 막대를 방지하고 창의 너비와 높이를 캔버스 크기로 정확하게 제공하려면 어떻게해야합니까?


캔버스를 항상 전체 화면 너비와 높이로 만들려면 브라우저의 크기를 조정할 때도 캔버스를 window.innerHeight 및 window.innerWidth로 크기를 조정하는 함수 내에서 그리기 루프를 실행해야합니다.

예 : http://jsfiddle.net/jaredwilli/qFuDr/

HTML

<canvas id="canvas"></canvas>

자바 스크립트

(function() {
    var canvas = document.getElementById('canvas'),
            context = canvas.getContext('2d');

    // resize the canvas to fill browser window dynamically
    window.addEventListener('resize', resizeCanvas, false);

    function resizeCanvas() {
            canvas.width = window.innerWidth;
            canvas.height = window.innerHeight;

            /**
             * Your drawings need to be inside this function otherwise they will be reset when 
             * you resize the browser window and the canvas goes will be cleared.
             */
            drawStuff(); 
    }
    resizeCanvas();

    function drawStuff() {
            // do your drawing stuff here
    }
})();

CSS

* { margin:0; padding:0; } /* to remove the top and left whitespace */

html, body { width:100%; height:100%; } /* just to be sure these are full screen*/

canvas { display:block; } /* To remove the scrollbars */

이것이 캔버스를 브라우저의 전체 너비와 높이로 올바르게 만드는 방법입니다. drawStuff () 함수에서 캔버스에 그리기위한 모든 코드를 입력하면됩니다.


뷰포트 단위 (CSS3)를 사용해 볼 수 있습니다 .

canvas { 
  height: 100vh; 
  width: 100vw; 
  display: block;
}

창 크기를 조정할 때 캔버스의 크기를 동적으로 조정하는 방법에 대한 일반적인 질문에 대답하겠습니다. 허용 된 답변은 너비와 높이가 모두 100 %로 가정 된 경우를 적절하게 처리하며 이는 캔버스의 종횡비를 변경합니다. 많은 사용자는 가로 세로 비율을 그대로 유지하면서 창 크기를 조정할 때 캔버스 크기를 조정하려고합니다. 정확한 질문은 아니지만 "적합"하여 질문을 좀 더 일반적인 맥락에 넣습니다.

창에는 가로 세로 비율 (너비 / 높이)이 있으며 캔버스 객체도 마찬가지입니다. 이 두 종횡비가 서로 관련되기를 원하는 방법은 분명해야 할 한 가지입니다. 해당 질문에 대한 "하나의 크기가 모두 맞습니다"라는 대답은 없습니다. 필요.

html canvas 객체는 width 속성과 height 속성을 가지고 있습니다. 그런 다음 동일한 객체의 CSS에도 너비와 높이 속성이 있습니다. 이 두 너비와 높이는 다르며 둘 다 다른 것들에 유용합니다.

Changing the width and height attributes is one method with which you can always change the size of your canvas, but then you'll have to repaint everything, which will take time and is not always necessary, because some amount of size change you can accomplish via the css attributes, in which case you do not redraw the canvas.

I see 4 cases of what you might want to happen on window resize (all starting with a full screen canvas)

1: you want the width to remain 100%, and you want the aspect ratio to stay as it was. In that case, you do not need to redraw the canvas; you don't even need a window resize handler. All you need is

$(ctx.canvas).css("width", "100%");

where ctx is your canvas context. fiddle: resizeByWidth

2: you want width and height to both stay 100%, and you want the resulting change in aspect ratio to have the effect of a stretched-out image. Now, you still don't need to redraw the canvas, but you need a window resize handler. In the handler, you do

$(ctx.canvas).css("height", window.innerHeight);

fiddle: messWithAspectratio

3: you want width and height to both stay 100%, but the answer to the change in aspect ratio is something different from stretching the image. Then you need to redraw, and do it the way that is outlined in the accepted answer.

fiddle: redraw

4: you want the width and height to be 100% on page load, but stay constant thereafter (no reaction to window resize.

fiddle: fixed

All fiddles have identical code, except for line 63 where the mode is set. You can also copy the fiddle code to run on your local machine, in which case you can select the mode via a querystring argument, as ?mode=redraw


I was looking to find the answer to this question too, but the accepted answer was breaking for me. Apparently using window.innerWidth isn't portable. It does work in some browsers, but I noticed Firefox didn't like it.

Gregg Tavares posted a great resource here that addresses this issue directly: http://webglfundamentals.org/webgl/lessons/webgl-anti-patterns.html (See anti-pattern #'s 3 and 4).

Using canvas.clientWidth instead of window.innerWidth seems to work nicely.

Here's Gregg's suggested render loop:

function resize() {
  var width = gl.canvas.clientWidth;
  var height = gl.canvas.clientHeight;
  if (gl.canvas.width != width ||
      gl.canvas.height != height) {
     gl.canvas.width = width;
     gl.canvas.height = height;
     return true;
  }
  return false;
}

var needToRender = true;  // draw at least once
function checkRender() {
   if (resize() || needToRender) {
     needToRender = false;
     drawStuff();
   }
   requestAnimationFrame(checkRender);
}
checkRender();

http://jsfiddle.net/mqFdk/10/

<!DOCTYPE html>
<html>
<head>
    <title>aj</title>
</head>
<body>

    <canvas id="c"></canvas>

</body>
</html>

with CSS

body { 
       margin: 0; 
       padding: 0
     }
#c { 
     position: absolute; 
     width: 100%; 
     height: 100%; 
     overflow: hidden
   }

(Expanding upon 動靜能量's answer)

Style the canvas to fill the body. When rendering to the canvas take its size into account.

http://jsfiddle.net/mqFdk/356/

<!DOCTYPE html>
<html>
<head>
    <title>aj</title>
</head>
<body>

    <canvas id="c"></canvas>

</body>
</html>

CSS:

body { 
       margin: 0; 
       padding: 0
     }
#c { 
     position: absolute; 
     width: 100%; 
     height: 100%; 
     overflow: hidden
   }

Javascript:

function redraw() {
    var cc = c.getContext("2d");
    c.width = c.clientWidth;
    c.height = c.clientHeight;
    cc.scale(c.width, c.height);

    // Draw a circle filling the canvas.
    cc.beginPath();
    cc.arc(0.5, 0.5, .5, 0, 2*Math.PI);
    cc.fill();
}

// update on any window size change.
window.addEventListener("resize", redraw);

// first draw
redraw();

참고URL : https://stackoverflow.com/questions/4288253/html5-canvas-100-width-height-of-viewport

반응형