如何将 html 5 canvas 与 javascript 居中

How to center a html 5 canvas with javascript

我正在尝试将动态 html 5 canvas window 与 javascript 居中。我知道我的代码不起作用,但我想知道是否有一种方法可以实现 margin-left: auto/margin-left: auto 技术,通常将 html 页面中的元素居中。我也用我的 canvas class css 尝试过这个,但它也不起作用,所以感谢任何帮助。谢谢

我的代码:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");


document.getElementById("canvas").style.marginLeft = "auto";
document.getElementById("canvas").style.marginRight = "auto";

canvas.width = 300;
canvas.height = 300;
drawScreen();

formElement = document.getElementById("height");
formElement.addEventListener('change', heightChanged, true);

formElement = document.getElementById("width");
formElement.addEventListener('change', widthChanged, false);

function widthChanged(e) {
  var target = e.target;
  canvas.width = target.value;
  drawScreen();
}

function heightChanged(e) {
  var target = e.target;
  canvas.height = target.value;
  drawScreen();
}

function drawScreen() {
}

你喜欢 css :

canvas {
        display: block;
        position: absolute;
        margin: auto;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
    }

javascript :

 document.getElementById("canvas").style.display = "block";
        document.getElementById("canvas").style.margin = "auto";
        document.getElementById("canvas").style.position = "absolute";
        document.getElementById("canvas").style.top = 0;
        document.getElementById("canvas").style.bottom = 0;
        document.getElementById("canvas").style.left = 0;
        document.getElementById("canvas").style.right = 0;

LIVE DEMO

为什么不将 canvas 放入 div 容器中?

你也可以通过 javascript 完成。

var container = document.createElement("div");
container.style.marginLeft = "auto";
container.style.marginRight = "auto";
container.style.width = "300px";

container.innerHtml = canvas;

使 canvas 成为块级元素。您可以使用 CSS 或将此行添加到您的代码中:

canvas.style.display= 'block';

示例:

var canvas = document.getElementById("canvas");
var context = canvas.getContext("2d");

document.getElementById("canvas").style.marginLeft = "auto";
document.getElementById("canvas").style.marginRight = "auto";
canvas.style.display= 'block';
canvas.width = 300;
canvas.height = 300;
drawScreen();

formElement = document.getElementById("height");
formElement.addEventListener('change', heightChanged, true);

formElement = document.getElementById("width");
formElement.addEventListener('change', widthChanged, false);

function widthChanged(e) {
  var target = e.target;
  canvas.width = target.value;
  drawScreen();
}

function heightChanged(e) {
  var target = e.target;
  canvas.height = target.value;
  drawScreen();
}

function drawScreen() {
}
canvas {
  border: 1px solid black;
  background: yellow;
}
<canvas id="canvas"></canvas>

<div id="height"></div>
<div id="width"></div>