使画布均匀地左右扩展 由 {孤心}发布于 2020-05-17 22:32:11 cssjavascripthtml 收藏 我有一个画布,在处理浏览器窗口时,它始终会扩展到屏幕宽度的100%。我需要画布中心始终在浏览器窗口的中心可见。问题是,当我将画布扩展例如100 px时,它会向右扩展。我能以某种方式锚定此画布,以使其在左右均匀地扩展吗? incorrectly enlarged canvas correctly enlarged canvas 评论 请 登录后发表观点 Out 2020-05-17 22:32:11 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> 点赞 评论 到底啦
You can change display of canvas to
block
and margin auto it.例