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绘图非常好,它在移动设备上面的画面感挺不错的,期待使用它做出更多好的页面。如果有问题和意见,欢迎提出来,共同探讨,谢谢!

 

转载于:https://www.cnblogs.com/mihoutaoguniang/p/5998511.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值