[Canvas] Make Canvas Responsive to Pixel Ratio
Canvas is great for high performance graphics rendering but by default the results look blocky on phones tablets and laptops with high pixel density or Retina displays. By using canvas width and height attributes and style props we can use window.devicePixelRatio
to create a canvas that is responsive to pixel ratio.
It's much faster to paint graphics to the screen using canvas and DOM. But on high pixel density displays, like phones and Macbooks, the results look pixelated. This is because by default one canvas pixel equals one CSS pixel, not one screen pixel.
To fix this, let's create a scale factor from the device pixel ratio. We use a scale factors to create a canvas, use width and height attributes, so double the CSS pixel width and height sizes we require. We make all our painting calls relative to the scale factor.
const canvas = document.querySelector('canvas') const sf = window.devicePixelRatio const elWidth = canvas.width const elHeight = canvas.height canvas.width = elWidth * sf canvas.height = elHeight * sf const ctx = canvas.getContext('2d') ctx.arc( canvas.width / 2, canvas.height / 2, canvas.width / 2, 0, Math.PI * 2 ) ctx.fill() canvas.style.width = `${elWidth}px`
To recap, the width and height attributes on the canvas element determine the number of pixels in the canvas, while the CSS width and height properties determine the size it will display on the screen. By setting an element's attributes different to the CSS properties.
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
2015-08-22 [Node.js] Web Scraping with Pagination and Advanced Selectors
2014-08-22 [jQuery] Custom event trigger
2014-08-22 [jQuery] $.map, $.each, detach() , $.getJSOIN()