canvas居中需同时设置html宽高属性和css布局,禁用css设置宽高以防绘图缩放失真;推荐flex布局,响应式时需结合devicepixelratio缩放上下文。

canvas 元素本身不支持 text-align 居中
很多人直接给 <canvas></canvas> 加 style="margin: 0 auto; display: block;",发现没用——因为 <canvas></canvas> 默认是 inline 元素,且它的“内容”(即绘制区域)由 width/height 属性决定,不是靠 CSS 盒模型撑开的。单纯居中标签本身,不等于居中绘制区域。
必须同时控制 HTML 结构和 CSS 盒模型
关键点:让 canvas 的父容器成为 flex 或 text-align 容器,并确保 canvas 有明确的 width/height(不能靠 CSS 拉伸),否则绘图会模糊或变形。
- 用
display: block+margin: 0 auto只对块级元素生效,所以先设display: block - 父容器加
text-align: center对 inline 元素有效,但 canvas 若没设宽高,浏览器按默认 300×150 渲染,可能被误判为“无尺寸” - 更可靠的是用 flex 布局:
<div style="display: flex; justify-content: center; align-items: center; height: 100vh;"> <canvas id="c" width="400" height="300"></canvas> </div>
千万别用 CSS 设置 canvas 的 width/height
这是最常踩的坑。如果写 <canvas style="width: 400px; height: 300px"></canvas>,实际 canvas 的 width 和 height 属性仍是默认值(300×150),只是被 CSS 拉伸显示——所有绘图坐标都会被缩放,线条变粗、文字模糊、鼠标位置错乱。
- 正确做法:只用 HTML 属性定义物理像素尺寸:
<canvas width="400" height="300"></canvas> - 再用 CSS 控制它在页面中的布局位置,比如
max-width: 100%; height: auto;配合父容器约束 - 验证方式:在 JS 中打印
canvas.width和canvas.height,必须等于你期望的像素数
响应式居中要小心设备像素比
在高清屏(dpr > 1)下,仅靠固定 width/height 会导致图形发虚。如果需要适配,得手动缩放上下文:
- 获取设备像素比:
const dpr = window.devicePixelRatio || 1 - 设置 canvas 物理尺寸:
canvas.width = desiredWidth * dpr;canvas.height = desiredHeight * dpr - 用 CSS 缩回显示尺寸:
canvas.style.width = "${desiredWidth}px";canvas.style.height = "${desiredHeight}px" - 最后缩放绘图上下文:
ctx.scale(dpr, dpr)
这一步漏掉,居中了也没用——图糊了,用户根本看不出你在居中什么。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











