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

  • 相关阅读:
    关于音视频同步
    redis JedisConnectionException: Could not get a resource from the pool
    ping指定IP的指定端口号
    如何查看端口号是否被占用
    mongodb增删改查基础语法
    mongodb重置密码
    本地MongoDB服务开启与连接本地以及远程服务器MongoDB服务
    MongoDB服务的安装与删除
    可视化
    Elasticsearch下载安装
  • 原文地址:https://www.cnblogs.com/mihoutaoguniang/p/5998511.html
Copyright © 2011-2022 走看看