简体   繁体   中英

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

<!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.

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.

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.

Error showed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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