← 中文资源

简体中文版本

Canvas 按 devicePixelRatio 缩放

只按 CSS 像素设置画布尺寸在高清屏上必然发虚:backing store 乘以 devicePixelRatio、ctx.scale 反向缩放坐标系,1/dpr 线宽让细线依旧锐利,最后打印两套尺寸便于核对。

阅读英文原文

实现说明

失败路径是显式的——守卫条件成立就抛出 Error。 各个操作都建立在顶层绑定之上:canvas、dpr、cssWidth、cssHeight。

使用要点

  • 浏览器才是这里的运行环境:document、window 在 Node 里拿不到。
  • 守卫 !ctx 一旦成立就走提前的 throw,把后续流程挡掉。
  • 演示输出是带标签的(backing store:),每个操作都会留下自己的一行标注。

常见问题

输入不合法时代码会怎么表现?

校验先行——Error 标记失败(位于 !ctx),不会先做一半再失败。

「Canvas 按 devicePixelRatio 缩放」能在裸 Node.js 里跑吗?

不能——这类 API 归浏览器环境所有(document、window),Node 里不存在。请在页面或 DevTools 控制台中运行。

核心语句

if (!ctx) throw new Error('2d context unavailable');

代码示例

// A canvas sized only in CSS pixels renders blurry on high-DPI displays;
// devicePixelRatio scales the backing store to match the screen
const canvas = document.querySelector('#chart');
const dpr = window.devicePixelRatio || 1;

const cssWidth = canvas.clientWidth;
const cssHeight = 160;

canvas.width = Math.round(cssWidth * dpr);
canvas.height = Math.round(cssHeight * dpr);
canvas.style.height = `${cssHeight}px`;

const ctx = canvas.getContext('2d');
if (!ctx) throw new Error('2d context unavailable');

ctx.scale(dpr, dpr);
ctx.lineWidth = 1 / dpr; // hairlines stay crisp after scaling

ctx.beginPath();
ctx.moveTo(10, 80);
ctx.lineTo(120, 80);
ctx.stroke();

console.log('backing store:', canvas.width, 'x', canvas.height, 'dpr:', dpr);