canvas高清屏模糊问题

202 阅读1分钟

使用 window.devicePixelRatioctx.scale 处理

// 创建 canvas 元素
const canvas = document.createElement("canvas")!;
// 获取 canvas 的 2D 绘图上下文
const ctx = canvas.getContext("2d")!;
// 获取设备像素比,如果未获取到则默认为 1
const ratio = window.devicePixelRatio || 1;

// 设置 canvas 元素的样式宽度为其实际宽度(以像素为单位)
canvas.style.width = canvas.width + "px";
// 设置 canvas 元素的样式高度为其实际高度(以像素为单位)
canvas.style.height = canvas.height + "px";
// 根据设备像素比调整 canvas 的宽度
canvas.width = canvas.width * ratio;
// 根据设备像素比调整 canvas 的高度
canvas.height = canvas.height * ratio;
// 缩放绘图上下文
ctx.scale(ratio, ratio);

// 设置填充颜色为绿色
ctx.fillStyle = "green";
// 绘制一个填充的矩形
ctx.fillRect(0, 0, 150, 100);
// 设置字体
ctx.font = "14px Georgia";
// 设置填充颜色为 #999
ctx.fillStyle = "#999";
// 绘制填充文字
ctx.fillText("我是清晰的文字", 10, 50);


document.body.appendChild(canvas);