Atitit html5 Canvas 如何自適應螢幕大小

來源:互聯網
上載者:User

標籤:

 

Atitit  html5 Canvas 如何自適應螢幕大小  

 

可以用JS監控螢幕大小,然後調整Canvas的大小。在代碼中加入JS

1

2

3

4

5

6

7

$(window).resize(resizeCanvas);

 function resizeCanvas() {

        canvas.attr("width", $(window).get(0).innerWidth);

        canvas.attr("height", $(window).get(0).innerHeight);

        context.fillRect(0, 0, canvas.width(), canvas.height());

 };

 resizeCanvas();

就可以了。

 

<canvas> 標籤只是圖形容器,您必須使用指令碼來繪製圖形

 

 

但是僅僅是這樣canvas的內容並不能隨著視窗大小的改變而改變。 
我們需要在視窗大小改變的同時調整畫板的大小,所以我們需要在js中加入下面這段代碼: 

Javascript代碼 

1. $(window).resize(resizeCanvas);  

2.    

3.  function resizeCanvas() {  

4.    

5.         canvas.attr("width", $(window).get(0).innerWidth);  

6.    

7.         canvas.attr("height", $(window).get(0).innerHeight);  

8.    

9.         context.fillRect(0, 0, canvas.width(), canvas.height());  

10.    

11.  };  

12.    

13.  resizeCanvas();  



這樣畫布就能根據視窗大小自動調整了,並且不會出現捲軸了。 

註:使用$(window).get(0).innerHeight代替$(window).height()是因為後者無法返回所有瀏覽器視窗的完整高度值。這種方法實際效果並不完美,瀏覽器視窗中canvas元素和捲軸的四周仍存在白色地區 

 

 

 

 

 

html5 Canvas 如何自適應螢幕大小 - - ITeye技術網站.html

 

作者:: 綽號:老哇的爪子 ( 全名::Attilax Akbar Al Rapanui 阿提拉克斯 阿克巴 阿爾 拉帕努伊 ) 

漢字名:艾提拉(艾龍),   EMAIL:[email protected]

轉載請註明來源: http://www.cnblogs.com/attilax/

atiend

 

 

 

Atitit html5 Canvas 如何自適應螢幕大小

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.