3

我在试图弄清楚如何在页面中居中画布时遇到了麻烦。画布的代码位于 javascript 文件中。这是页面的html。

<!DOCTYPE html>
<html>
   <head>
       <meta charset="utf-8">
       <title>Game Tut</title>
   </head>
   <body>

       <script src="game.js"></script>
   </body>
 </html>

我在javascript文件中尝试过类似的东西。

var canvas = document.createElement("canvas");
canvas.width = 800;
canvas.height = 600;
canvas.tabindex = 0;
canvas.style = "position: absolute; top: 50px; left: 50px; border:2px solid blue"
document.addEventListener('keydown', doKeyDown, true);
var ctx = canvas.getContext("2d");
document.body.appendChild(canvas);

由于某种原因,蓝色边框或定位似乎没有出现在 Google Chrome 中。

4

3 回答 3

2

尝试这个:

var canvas = document.createElement("canvas");
canvas.width = 800;
canvas.height = 600;
canvas.tabindex = 0;
canvas.setAttribute('style', "position: absolute;  left: 50%;margin-left:-400px; top: 50%;margin-top:-300px; border:2px solid blue");
var ctx = canvas.getContext("2d");
document.body.appendChild(canvas);
document.addEventListener('keydown', doKeyDown, true);
于 2013-11-12T05:14:21.483 回答
2
var canvas = document.getElementsByName("canvas")[0];
var style = canvas.style;
style.marginLeft = "auto";
style.marginRight = "auto";
var parentStyle = canvas.parentElement.style;
parentStyle.textAlign = "center";
parentStyle.width = "100%";

或者

canvas.style = "position:absolute; left: 50%; width: 400px; margin-left: -200px;";
于 2013-11-12T05:06:38.320 回答
2

尝试这个

下面的代码使画布中心

canvas.style = "position: absolute; top: 0px; left: 0px; right: 0px; bottom: 0px; margin: auto; border:2px solid blue";

顺便一提

document.addEventListener('keydown', doKeyDown, true);

我发布了您的代码,但 chrome 显示“doKeyDown”函数未定义,因此您可能需要修复此错误,然后您的画布将正确显示。

错误显示

于 2018-07-25T02:00:26.447 回答