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繪圖非常好,它在移動設備上面的畫面感挺不錯的,期待使用它做出更多好的頁面。如果有問題和意見,歡迎提出來,共同探討,謝謝!

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM