javascript 如何将画布javascript居中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19921248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:15:03  来源:igfitidea点击:

How to center canvas javascript?

javascripthtmlcanvas

提问by Jalepano

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. Here's the html for the page.

我无法弄清楚如何在页面中居中画布。画布的代码在一个 javascript 文件中。这是页面的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 中。

回答by Trident D'Gao

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

回答by Vicky Gonsalves

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

回答by Victor.Chou

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

显示错误