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