使用 canvas 画图时图像文字模糊的解决办法
最近在使用 canvas 画图的时候,遇到了图像文字模糊的问题,解决思路就是根据分辨率创建不同尺寸的画布。以下是创建高分辨率画布的代码:
/**
* 创建高分辨率画布
* @param w 画布宽
* @param h 画布高
* @param ratio 屏幕分辨率
*/
function createHiDPICanvas(w, h, ratio?) {
const PIXEL_RATIO = (function () {
const c = <HTMLCanvasElement>document.createElement("canvas"),
ctx = c.getContext("2d"),
dpr = window.devicePixelRatio || 1,
bsr = ctx['webkitBackingStorePixelRatio'] ||
ctx['mozBackingStorePixelRatio'] ||
ctx['msBackingStorePixelRatio'] ||
ctx['oBackingStorePixelRatio'] ||
ctx['backingStorePixelRatio'] || 1;
return dpr / bsr;
})();
if (!ratio) { ratio = PIXEL_RATIO; }
const can = document.createElement("canvas");
can.width = w * ratio;
can.height = h * ratio;
can.style.width = w + "px";
can.style.height = h + "px";
can.getContext("2d").setTransform(ratio, 0, 0, ratio, 0, 0);
return can;
}
// 不创建高分辨率画布
const canvas = document.createElement("canvas");
canvas.width = 100;
canvas.height = 100;
// 创建使用默认分辨率的画布
const myCanvas = this.createHiDPICanvas(100, 100);
// 创建分辨率为 3 的画布
const myCustomCanvas = this.createHiDPICanvas(100, 100, 3);
最后,贴一个高分辨率画布的开源库
https://github.com/jondavidjohn/hidpi-canvas-polyfill
感谢您的阅读,如果您对我的文章感兴趣,可以关注我的博客,我是叙帝利,下篇文章再见!
低代码平台必备轻量级 GUI 库 https://github.com/acrodata/gui
适用于 Angular 的 CodeMirror 6 组件 https://github.com/acrodata/code-editor
适用于 Angular 的水印组件(防删除,盲水印) https://github.com/acrodata/watermark
支持拖拽和缩放的弹窗组件 https://github.com/acrodata/rnd-dialog
开发低代码平台的必备拖拽库 https://github.com/ng-dnd/ng-dnd
基于 Angular Material 的中后台管理框架 https://github.com/ng-matero/ng-matero
Angular Material Extensions 扩展组件库 https://github.com/ng-matero/extensions
Unslider 轮播图插件纯 JS 实现 https://github.com/nzbin/unsliderjs
仿 Windows 照片查看器插件 https://github.com/nzbin/photoviewer
仿 Windows 照片查看器插件 jQuery 版 https://github.com/nzbin/magnify
完美替代 jQuery 的模块化 DOM 库 https://github.com/nzbin/domq
简化类名的轻量级 CSS 框架 https://github.com/nzbin/snack
与任意 UI 框架搭配使用的通用辅助类 https://github.com/nzbin/snack-helper
单元素纯 CSS 加载动画 https://github.com/nzbin/three-dots
有趣的 jQuery 卡片抽奖插件 https://github.com/nzbin/CardShow
悬疑科幻电影推荐 https://github.com/nzbin/movie-gallery
锻炼记忆力的小程序 https://github.com/nzbin/memory-stake
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)