最近在使用canvas标签,使用的过程,要注意:设置canvas.width和canvas.height。对于PC端来讲,只用设置你须要的canvas的大小就ok了。在移动端,那就必需要考虑屏幕适配问题。canvas
获取canvas:测试
var canvas = document.querySelector("canvas"); var context = canvas.getContext('2d');
获取移动设备屏幕的大小:spa
1.document.documentElement.clientWidth:可见区域宽度;3d
document.documentElement.clientHeight:可见区域高度。code
canvas.width = document.documentElement.clientWidth;
canvas.height = document.documentElement.clientHeight;
2.screen.availWidth:屏幕可用宽度;blog
screen.availHeight:屏幕可见高度。get
canvas.width = screen.availWidth;
canvas.height = screen.availHeight;
3.screen.width:屏幕显示宽度;console
screen.height:屏幕显示高度。class
canvas.width = screen.width;
canvas.height = screen.height;
4.window.innerWidth:窗口的宽度;cli
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绘图很是好,它在移动设备上面的画面感挺不错的,期待使用它作出更多好的页面。若是有问题和意见,欢迎提出来,共同探讨,谢谢!