HTML5 캔버스를 창에 맞게 크기를 조정하십시오
-
12-09-2019 - |
문제
HTML5를 자동으로 확장하려면 어떻게해야합니까? <canvas>
페이지에 맞는 요소?
예를 들어, 나는 얻을 수있다 <div>
설정하여 height
그리고 width
속성은 100%이지만 a <canvas>
확장하지 않을까요?
해결책
나는 이것에 대한 우아한 해결책을 찾았다 고 생각합니다.
자바 스크립트
/* important! for alignment, you should make things
* relative to the canvas' current width/height.
*/
function draw() {
var ctx = (a canvas context);
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
//...drawing code...
}
CSS
html, body {
width: 100%;
height: 100%;
margin: 0;
}
지금까지 나에게 큰 부정적인 성능에 영향을 미치지 않았습니다.
다른 팁
다음 솔루션이 저를 위해 가장 잘 작동했습니다. 나는 코딩을 비교적 처음 접했기 때문에, 내가 기대하는 방식으로 무언가가 작동한다는 시각적 확인을 좋아합니다. 다음 사이트에서 찾았습니다.http://htmlcheats.com/html/resize-html5-canvas-dyamically/
코드는 다음과 같습니다.
<!DOCTYPE html>
<head>
<meta charset="utf-8">
<title>Resize HTML5 canvas dynamically | www.htmlcheats.com</title>
<style>
html, body {
width: 100%;
height: 100%;
margin: 0px;
border: 0;
overflow: hidden; /* Disable scrollbars */
display: block; /* No floating content on sides */
}
</style>
</head>
<body>
<canvas id='c' style='position:absolute; left:0px; top:0px;'>
</canvas>
<script>
(function() {
var
// Obtain a reference to the canvas element using its id.
htmlCanvas = document.getElementById('c'),
// Obtain a graphics context on the canvas element for drawing.
context = htmlCanvas.getContext('2d');
// Start listening to resize events and draw canvas.
initialize();
function initialize() {
// Register an event listener to call the resizeCanvas() function
// each time the window is resized.
window.addEventListener('resize', resizeCanvas, false);
// Draw canvas border for the first time.
resizeCanvas();
}
// Display custom canvas. In this case it's a blue, 5 pixel
// border that resizes along with the browser window.
function redraw() {
context.strokeStyle = 'blue';
context.lineWidth = '5';
context.strokeRect(0, 0, window.innerWidth, window.innerHeight);
}
// Runs each time the DOM window resize event fires.
// Resets the canvas dimensions to match window,
// then draws the new borders accordingly.
function resizeCanvas() {
htmlCanvas.width = window.innerWidth;
htmlCanvas.height = window.innerHeight;
redraw();
}
})();
</script>
</body>
</html>
파란색 테두리는 크기 조정 캔버스의 가장자리를 보여 주며, 항상 창의 가장자리를 따라 4면 모두에서 볼 수 있는데, 위의 다른 답변 중 일부는 그렇지 않았습니다. 도움이되기를 바랍니다.
기본적으로 당신이해야 할 일은 onresize 이벤트를 신체에 묶는 것입니다. 일단 이벤트를 잡으면 Window.innerWidth 및 Window.innerHeight를 사용하여 캔버스를 크기를 조정해야합니다.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Canvas Resize</title>
<script type="text/javascript">
function resize_canvas(){
canvas = document.getElementById("canvas");
if (canvas.width < window.innerWidth)
{
canvas.width = window.innerWidth;
}
if (canvas.height < window.innerHeight)
{
canvas.height = window.innerHeight;
}
}
</script>
</head>
<body onresize="resize_canvas()">
<canvas id="canvas">Your browser doesn't support canvas</canvas>
</body>
</html>
브라우저 클라이언트의 크기를 기준으로 캔버스 좌표 공간 너비와 높이 설정 브라우저가 크기를 조정할 때마다 크기를 조정하고 다시 그리기를해야합니다.
덜 복잡한 솔루션은 JavaScript 변수의 차원 차원을 유지하지만 Screen.width, Screen.height 치수를 기반으로 Canvas 크기를 설정하는 것입니다. 적합한 CSS를 사용하십시오.
#containingDiv {
overflow: hidden;
}
#myCanvas {
position: absolute;
top: 0px;
left: 0px;
}
브라우저 창은 일반적으로 화면 자체보다 크지 않습니다 (화면 해상도가 잘못보고되는 경우 제외하고 비일 매칭 듀얼 모니터와 함께) 배경이 표시되지 않고 픽셀 비율이 다르지 않습니다. CSS를 사용하여 캔버스를 확장하지 않는 한 캔버스 픽셀은 화면 해상도에 직접 비례합니다.
ㅏ 순수한 CSS 위의 @jerseyboy 솔루션에 추가하십시오.
Firefox (V29에서 테스트), 크롬 (V34로 테스트) 및 Internet Explorer (V11에서 테스트)에서 작동합니다.
<!DOCTYPE html>
<html>
<head>
<style>
html,
body {
width: 100%;
height: 100%;
margin: 0;
}
canvas {
background-color: #ccc;
display: block;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<canvas id="canvas" width="500" height="500"></canvas>
<script>
var canvas = document.getElementById('canvas');
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
ctx.fillRect(25,25,100,100);
ctx.clearRect(45,45,60,60);
ctx.strokeRect(50,50,50,50);
}
</script>
</body>
</html>
예에 대한 링크 : http://temporaer.net/open/so/140502_canvas-fit-to-window.html
그러나 @jerseyboy가 그의 의견에서 말한 것처럼주의하십시오.
CSS로 캔버스를 저장하는 것은 번거 롭습니다. 최소한 Chrome 및 Safari에서 마우스/터치 이벤트 위치는 캔버스 픽셀 위치와 1 : 1에 해당하지 않으며 좌표 시스템을 변환해야합니다.
캔버스가 이미지 데이터를 자동으로 업 스케일하기를 원하지 않는 한 (James Black의 답변이 말하는 것인데 예쁘지는 않을 것입니다), 직접 크기를 조정하고 이미지를 다시 그리워해야합니다. 캔버스 중심
function resize() {
var canvas = document.getElementById('game');
var canvasRatio = canvas.height / canvas.width;
var windowRatio = window.innerHeight / window.innerWidth;
var width;
var height;
if (windowRatio < canvasRatio) {
height = window.innerHeight;
width = height / canvasRatio;
} else {
width = window.innerWidth;
height = width * canvasRatio;
}
canvas.style.width = width + 'px';
canvas.style.height = height + 'px';
};
window.addEventListener('resize', resize, false);
DIV가 웹 페이지를 완전히 채우면 해당 DIV를 채울 수 있으며 DIV를 채우는 캔버스가 있습니다.
CSS를 사용하여 백분율을 사용해야 할 수도 있지만 사용중인 브라우저와 사양과 일치하는 금액에 따라 다릅니다.http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-lement.html#the-canvas-element
캔버스 요소의 고유 치수는 CSS 픽셀로 해석 된 숫자와 함께 좌표 공간의 크기와 같습니다. 그러나 요소는 스타일 시트에 의해 임의로 크기가 될 수 있습니다. 렌더링 중에 이미지는이 레이아웃 크기에 맞게 조정됩니다.
div의 오프셋 폭과 높이를 가져 오거나 창 높이/너비를 가져 와서 픽셀 값으로 설정해야 할 수도 있습니다.
CSS
body { margin: 0; }
canvas { display: block; }
자바 스크립트
window.addEventListener("load", function()
{
var canvas = document.createElement('canvas'); document.body.appendChild(canvas);
var context = canvas.getContext('2d');
function draw()
{
context.clearRect(0, 0, canvas.width, canvas.height);
context.beginPath();
context.moveTo(0, 0); context.lineTo(canvas.width, canvas.height);
context.moveTo(canvas.width, 0); context.lineTo(0, canvas.height);
context.stroke();
}
function resize()
{
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
draw();
}
window.addEventListener("resize", resize);
resize();
});
종횡비 보존에 관심이 있고 순수한 CSS (종횡비가 주어진)에서 그렇게하는 데 관심이 있다면 아래와 같은 일을 할 수 있습니다. 열쇠는 padding-bottom
에 ::content
크기의 요소 container
요소. 이것은 부모의 폭에 비해 크기입니다. 100%
기본적으로. 여기에 지정된 비율은 canvas
요소.
// Javascript
var canvas = document.querySelector('canvas'),
context = canvas.getContext('2d');
context.fillStyle = '#ff0000';
context.fillRect(500, 200, 200, 200);
context.fillStyle = '#000000';
context.font = '30px serif';
context.fillText('This is some text that should not be distorted, just scaled', 10, 40);
/*CSS*/
.container {
position: relative;
background-color: green;
}
.container::after {
content: ' ';
display: block;
padding: 0 0 50%;
}
.wrapper {
position: absolute;
top: 0;
right: 0;
left: 0;
bottom: 0;
}
canvas {
width: 100%;
height: 100%;
}
<!-- HTML -->
<div class=container>
<div class=wrapper>
<canvas width=1200 height=600></canvas>
</div>
</div>
(function() {
// get viewport size
getViewportSize = function() {
return {
height: window.innerHeight,
width: window.innerWidth
};
};
// update canvas size
updateSizes = function() {
var viewportSize = getViewportSize();
$('#myCanvas').width(viewportSize.width).height(viewportSize.height);
$('#myCanvas').attr('width', viewportSize.width).attr('height', viewportSize.height);
};
// run on load
updateSizes();
// handle window resizing
$(window).on('resize', function() {
updateSizes();
});
}());
jQuery를 사용하면 jQuery를 사용하여 창 크기 조정 및 캔버스 너비를 추적 할 수 있습니다.
그런 것
$( window ).resize(function() {
$("#myCanvas").width($( window ).width())
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<canvas id="myCanvas" width="200" height="100" style="border:1px solid #000000;">
나는 이것이 우리가 정확히해야 할 일이라고 생각합니다. http://www.html5rocks.com/en/tutorials/casestudies/gopherwoord-studios-resizing-html5-games/
function resizeGame() {
var gameArea = document.getElementById('gameArea');
var widthToHeight = 4 / 3;
var newWidth = window.innerWidth;
var newHeight = window.innerHeight;
var newWidthToHeight = newWidth / newHeight;
if (newWidthToHeight > widthToHeight) {
newWidth = newHeight * widthToHeight;
gameArea.style.height = newHeight + 'px';
gameArea.style.width = newWidth + 'px';
} else {
newHeight = newWidth / widthToHeight;
gameArea.style.width = newWidth + 'px';
gameArea.style.height = newHeight + 'px';
}
gameArea.style.marginTop = (-newHeight / 2) + 'px';
gameArea.style.marginLeft = (-newWidth / 2) + 'px';
var gameCanvas = document.getElementById('gameCanvas');
gameCanvas.width = newWidth;
gameCanvas.height = newHeight;
}
window.addEventListener('resize', resizeGame, false);
window.addEventListener('orientationchange', resizeGame, false);
첫째, 너비와 높이 속성을 사용하여 크기를 변경할 수 없습니다 (적어도 내 방식으로). 당신은 이것을 할 수 있습니다 : html :
<canvas id = 'myCanvas'></canvas>
JS :
var canvas = document.getElementById('myCanvas');
var W = window.innerWidth;
var H = window.innerHeight;
canvas.width = W;
canvas.height = H;
canvas.style.position = 'absolute';
//Or set the position to absolute using CSS
(오타를 용서 해주세요. 나는 그렇게 많이하는 경향이 있습니다)
Sketch.js를 사용하고 있으므로 캔버스의 init 명령을 실행 한 후 jQuery로 너비와 높이를 변경합니다. 부모 요소의 치수를 기본으로합니다.
$ ( '##drawCanvas'). sketch (). att ().너비());