canvas自适应屏幕大小
最近在使用canvas标签,使用的过程,要注意:设置canvas.width和canvas.height。对于PC端来说,只用设置你需要的canvas的大小就ok了。在移动端,那就必须要考虑屏幕适配问题。
获取canvas:
var canvas = document.querySelector("canvas"); var context = canvas.getContext('2d');
获取移动设备屏幕的大小:
1.document.documentElement.clientWidth:可见区域宽度;
document.documentElement.clientHeight:可见区域高度。
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
2.screen.availWidth:屏幕可用宽度;
screen.availHeight:屏幕可见高度。
canvas.width = screen.availWidth;
canvas.height = screen.availHeight;
3.screen.width:屏幕显示宽度;
screen.height:屏幕显示高度。
canvas.width = screen.width;
canvas.height = screen.height;
4.window.innerWidth:窗口的宽度;
window.innerHeight:窗口的高度;
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
通过Chrome控制台进行验证,以上四种获取移动设备屏幕大小的方法,均可以达到canvas自适应屏幕的需求。
验证:
//1 console.log(document.documentElement.clientWidth); console.log(document.documentElement.clientHeight); //2 console.log(screen.availWidth); console.log(screen.availHeight); //3 console.log(screen.width); console.log(screen.height); //4 console.log(window.innerWidth); console.log(window.innerHeight);
结果:
iPhone 5 iPad Galaxy Nexus 6P
经过测试发现一个问题:
Nexus 5X 的高度出现差异,原因是在Chrome下测试,它的可见高度要大于屏幕可用高度。
小果觉得canvas绘图非常好,它在移动设备上面的画面感挺不错的,期待使用它做出更多好的页面。如果有问题和意见,欢迎提出来,共同探讨,谢谢!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 一文读懂知识蒸馏
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下