我正在尝试使用JavaScript将动态html 5 Canvas 窗口居中。我知道我的代码行不通,但是我想知道是否有一种方法可以实现margin-left:auto / margin-left:自动技术,该技术通常将元素放在html页面中。我也在我的 Canvas 类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() {
}

最佳答案

使 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>

07-24 09:47
查看更多