ResizeObserver + Canvas 自适应缩放方案
如何用 ResizeObserver 监听 Canvas 容器的尺寸变化并自适应缩放?如何处理 HiDPI 屏幕的清晰度问题(devicePixelRatio)?Canvas 尺寸与 CSS 尺寸的关系?
回答
古法程序员
const observer=new ResizeObserver(entries=>{const {width,height}=entries[0].contentRect; const dpr=window.devicePixelRatio||1; canvas.width=widthdpr; canvas.height=heightdpr; canvas.style.width=width+'px'; canvas.style.height=height+'px'; ctx.scale(dpr,dpr); draw()})。Canvas width/height(实际像素)负责分辨率;CSS尺寸负责布局。HiDPI: Canvas内部尺寸设为CSS尺寸*dpr,ctx.scale缩放。ResizeObserver: 元素级别监听,比 window.resize+getBoundingClientRect 高效。注意: resize后ctx变换矩阵重置,需重新scale。防抖加rAF。