캔버스 중앙에 맞추기
HTML5로 페이지를 마크업 canvas
하여canvas
너비의 80%를 차지합니다.
비율을 효과적으로 정의하는 해당 픽셀 높이와 너비가 있습니다(캔버스가 80%로 늘어날 때 비례적으로 유지됨).
세로 및 가로로 중앙에 배치됨
canvas
페이지의 유일한 것이라고 가정할 수 있지만 div
필요한 경우 s 에 캡슐화할 수 있습니다.
이렇게 하면 캔버스가 가로로 가운데에 맞춰집니다.
#canvas-container {
width: 100%;
text-align:center;
}
canvas {
display: inline;
}
HTML:
<div id="canvas-container">
<canvas>Your browser doesn't support canvas</canvas>
</div>
현재 답변을 보면 하나의 쉽고 깨끗한 수정이 누락되었다고 생각합니다. 누군가 지나가다가 올바른 해결책을 찾는 경우를 대비하여. 나는 몇 가지 간단한 CSS와 자바 스크립트로 꽤 성공적입니다.
캔버스를 화면 또는 상위 요소의 중앙에 배치합니다. 포장하지 않습니다.
HTML:
<canvas id="canvas" width="400" height="300">No canvas support</canvas>
CSS:
#canvas {
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin:auto;
}
자바스크립트:
window.onload = window.onresize = function() {
var canvas = document.getElementById('canvas');
canvas.width = window.innerWidth * 0.8;
canvas.height = window.innerHeight * 0.8;
}
매력처럼 작동 - 테스트: 파이어폭스, 크롬
바이올린: http://jsfiddle.net/djwave28/j6cffppa/3/
가장 쉬운 방법
캔버스를 다음과 같이 단락 태그에 넣습니다.
<p align="center">
<canvas id="myCanvas" style="background:#220000" width="700" height="500" align="right"></canvas>
</p>
Firefox에서만 테스트:
<script>
window.onload = window.onresize = function() {
var C = 0.8; // canvas width to viewport width ratio
var W_TO_H = 2/1; // canvas width to canvas height ratio
var el = document.getElementById("a");
// For IE compatibility http://www.google.com/search?q=get+viewport+size+js
var viewportWidth = window.innerWidth;
var viewportHeight = window.innerHeight;
var canvasWidth = viewportWidth * C;
var canvasHeight = canvasWidth / W_TO_H;
el.style.position = "fixed";
el.setAttribute("width", canvasWidth);
el.setAttribute("height", canvasHeight);
el.style.top = (viewportHeight - canvasHeight) / 2;
el.style.left = (viewportWidth - canvasWidth) / 2;
window.ctx = el.getContext("2d");
ctx.clearRect(0,0,canvasWidth,canvasHeight);
ctx.fillStyle = 'yellow';
ctx.moveTo(0, canvasHeight/2);
ctx.lineTo(canvasWidth/2, 0);
ctx.lineTo(canvasWidth, canvasHeight/2);
ctx.lineTo(canvasWidth/2, canvasHeight);
ctx.lineTo(0, canvasHeight/2);
ctx.fill()
}
</script>
<body>
<canvas id="a" style="background: black">
</canvas>
</body>
창 내에서 캔버스를 가운데에 맞추려면 +"px"를 el.style.top
및 에 추가해야 합니다 el.style.left
.
el.style.top = (viewportHeight - canvasHeight) / 2 +"px";
el.style.left = (viewportWidth - canvasWidth) / 2 +"px";
CSS를 사용하여 캔버스 크기를 조정하는 것은 좋은 생각이 아닙니다. Javascript를 사용하여 수행해야 합니다. 그것을 수행하는 아래 기능을 참조하십시오
function setCanvas(){
var canvasNode = document.getElementById('xCanvas');
var pw = canvasNode.parentNode.clientWidth;
var ph = canvasNode.parentNode.clientHeight;
canvasNode.height = pw * 0.8 * (canvasNode.height/canvasNode.width);
canvasNode.width = pw * 0.8;
canvasNode.style.top = (ph-canvasNode.height)/2 + "px";
canvasNode.style.left = (pw-canvasNode.width)/2 + "px";
}
여기 데모 : http://jsfiddle.net/9Rmwt/11/show/
.
단순한:
<body>
<div>
<div style="width: 800px; height:500px; margin: 50px auto;">
<canvas width="800" height="500" style="background:#CCC">
Your browser does not support HTML5 Canvas.
</canvas>
</div>
</div>
</body>
캔버스 자바 스크립트없이 아무것도 없다는 것을 감안할 때, 사용하는 자바 스크립트가 너무 크기 및 위치 설정하기 위해 (당신은 알고있다 onresize
, position:absolute
등)
CSS 제안:
#myCanvas {
width: 100%;
height: 100%;
}
표준에 따라 CSS는 캔버스 좌표계의 크기를 조정하지 않고 내용의 크기를 조정합니다. Chrome에서 언급된 CSS는 브라우저의 레이아웃에 맞게 캔버스 크기를 늘리거나 줄입니다. 좌표계가 브라우저의 픽셀 치수보다 작은 일반적인 경우에 이는 도면의 해상도를 효과적으로 낮춥니다. 비례하지 않는 드로잉도 발생할 가능성이 큽니다.
div로 래핑하면 작동합니다. Firefox, Fedora 13( 데모 )의 Chrome에서 테스트했습니다 .
#content {
width: 95%;
height: 95%;
margin: auto;
}
#myCanvas {
width: 100%;
height: 100%;
border: 1px solid black;
}
그리고 캔버스는 태그로 묶어야 합니다.
<div id="content">
<canvas id="myCanvas">Your browser doesn't support canvas tag</canvas>
</div>
작동하는지 알려주십시오. 건배.
위의 Nickolay와 동일한 코드이지만 IE9 및 chrome에서 테스트되었습니다(추가 렌더링 제거).
window.onload = window.onresize = function() {
var canvas = document.getElementById('canvas');
var viewportWidth = window.innerWidth;
var viewportHeight = window.innerHeight;
var canvasWidth = viewportWidth * 0.8;
var canvasHeight = canvasWidth / 2;
canvas.style.position = "absolute";
canvas.setAttribute("width", canvasWidth);
canvas.setAttribute("height", canvasHeight);
canvas.style.top = (viewportHeight - canvasHeight) / 2 + "px";
canvas.style.left = (viewportWidth - canvasWidth) / 2 + "px";
}
HTML:
<body>
<canvas id="canvas" style="background: #ffffff">
Canvas is not supported.
</canvas>
</body>
상단 및 왼쪽 오프셋은 를 추가할 때만 작동합니다 px
.
참조URL : https://stackoverflow.com/questions/1152203/centering-a-canvas
'IT이야기' 카테고리의 다른 글
Docker는 종료된 컨테이너의 로그를 봅니다. (0) | 2021.10.18 |
---|---|
SPAN의 차이점 (0) | 2021.10.18 |
8진수를 사용할 때 잘못된 토큰 (0) | 2021.10.18 |
Android의 파일 시스템 (0) | 2021.10.18 |
javac의 정적 최종 변수 인라인을 비활성화 (0) | 2021.10.17 |