如何在视口中居中动态大小的画布?

时间:2012-08-19 22:23:40

标签: canvas resize center

我已经在这方面苦苦挣扎了一段时间,我希望你们能提供帮助。我有一个动态大小的画布,根据拒绝居中的画布大小绘制网格。我已经尝试了很多来自这个网站的建议,但它们似乎都适用于固定宽度的画布。这对我不起作用..

这是所有的代码,所以你可以看到我正在做的一切......我正在使用mootools来动画调整画布和内容的大小。如果有一种方法可以在没有任何人知道的mootools的情况下调整大小,那也会很棒。

谢谢!

HTML

<!doctype html>
<html>
        <LINK href="style.css" rel="stylesheet" type="text/css">
<head>
<meta charset="utf-8">
        <script type='text/javascript' src='https://my-youtube.googlecode.com/files/mootools-core-1.4.2-full-nocompat.js'></script>
        <script type='text/javascript' src="chessboard.js"></script>
<title>Untitled Document</title>
</head>

<body>

<div id="header"></div>
<div id="content">
    <canvas id="canvas">TEST</canvas>
</div>

<div id="footer"></div>

</body>
</html>

CSS

@charset "utf-8";
/* CSS Document */

#header {
    margin-top: 0px;
    height: 75px;
    width: 100%;
    background: url(images/logo1.png) no-repeat top center;
}

#content {
    width: 100%;
    height: 100%-75px;
}

#footer {

}

body, html {
    margin-left: auto;
    margin-right: auto;
    margin-top: 0;
    background-color: #a6a6a6;
    background-image: url(images/background_image3.jpg);
    background-repeat: repeat-x;
    height: 100%;
}

的Javascript

window.addEvent('load', function() {
(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.height = window.innerHeight-100;
        canvas.width = canvas.height;

        drawStuff();
    }

resizeCanvas();

    function drawStuff() {

        var width = canvas.height/8;
        var baseX = 0.5, baseY = 0.5;


// draws the 8 by 8 chessboard
        for (var i = 0; i < 8; i++) {
            for (var j = 0; j < 8; j++) {
                var x = baseX + width * i, y = baseY + width * j;
                context.strokeRect(x, y, width, width);
                if ((i + j) % 2 != 0) {
                    context.fillStyle = '#BA1A1A';
                    context.fillRect(x, y, width, width);
                }
                if ((i + j) % 2 == 0) {
                    context.fillStyle = 'E6A3A3';
                    context.fillRect(x, y, width, width);
                }
            }
        }
    }
})();
});

1 个答案:

答案 0 :(得分:2)

由于这个问题的回答,我弄明白了:Centering a div block without the width

简而言之,在CSS容器中使用CSS display: inline block;。然后在该div的父容器中使用text-align: center;

所以,就我而言:

#content {
    margin: 0 auto;
    text-align: left;
    background-color: black;
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
}

body, html {
    margin-left: auto;
    margin-right: auto;
    margin-top: 0;
    background-color: #a6a6a6;
    background-image: url(images/background_image3.jpg);
    background-repeat: repeat-x;
    height: 100%;
    text-align:center;
}