使画布均匀地左右扩展

我有一个画布,在处理浏览器窗口时,它始终会扩展到屏幕宽度的100%。我需要画布中心始终在浏览器窗口的中心可见。问题是,当我将画布扩展例如100 px时,它会向右扩展。我能以某种方式锚定此画布,以使其在左右均匀地扩展吗?

incorrectly enlarged canvas

correctly enlarged canvas

评论
Out
Out

You can change display of canvas to block and margin auto it.

const canvas = document.querySelector("#canvas");
const context = canvas.getContext("2d");

canvas.width = window.innerWidth / 2;
canvas.height = window.innerHeight / 2;

context.fillStyle = "black";
context.fillRect(0, 0, canvas.width, canvas.height);

window.addEventListener("resize", () => {
  canvas.width = window.innerWidth / 2;
  canvas.height = window.innerHeight / 2;
  context.fillStyle = "black";
  context.fillRect(0, 0, canvas.width, canvas.height);
})
html,
body {
  width: 100%;
}

#canvas {
  display: block;
  margin: auto;
}
<canvas id="canvas"></canvas>
点赞
评论