简体   繁体   English

如何将画布javascript居中?

[英]How to center canvas javascript?

I'm having trouble trying to figure out how to center the canvas in the page.我无法弄清楚如何在页面中居中画布。 The canvas's code is in a javascript file.画布的代码在一个 javascript 文件中。 Here's the html for the page.这是页面的html。

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

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

I've tried something like this in the javascript file.我在 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);

For some reason the blue border or the positioning don't seem to show up in Google Chrome.出于某种原因,蓝色边框或定位似乎没有出现在 Google Chrome 中。

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%";

OR或者

canvas.style = "position:absolute; left: 50%; width: 400px; margin-left: -200px;";

Try this:尝试这个:

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);

Try this尝试这个

the code below made the canvas center下面的代码使画布居中

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

By the way顺便一提

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

I posted your code but chrome showed the 'doKeyDown' function is undefined so maybe you need to fix this error then your canvas will show correctly.我发布了您的代码,但 chrome 显示“doKeyDown”函数未定义,因此您可能需要修复此错误,然后您的画布才能正确显示。

Error showed显示错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM