2012-05-09 42 views
0

最近Mozilla推出了名爲Browser Quest的HTML5遊戲。在遊戲中,如果調整窗口大小,畫布也會調整大小。帆布上的CSS長寬比

我看起來更進,我看到了,這是怎麼一回事,因爲usign CSS3媒體查詢發現這裏https://developer.mozilla.org/en/CSS/Media_queries

不過,我仍然不認爲我這樣做是正確的。我的畫布ID是#canvas。我將如何去把它放在我的畫布上?

我的畫布特定寬/高:height:352px;width:512px;

回答

1

媒體查詢不會爲你提供你所尋求的功能。其目的僅僅是限制何時將特定樣式表應用於頁面。

此外,CSS widthheight屬性不調整畫布元素的實際尺寸。相反,他們將元素縮放到所需的大小。就你而言,我假設你希望畫布實際上是不同的分辨率。畫布的分辨率通過<canvas>標籤上的DOM widthheight屬性指定。

爲了處理大小調整,您需要使用window.onresize來捕獲調整大小事件。您的畫布代碼將需要創建一個所需大小的新畫布,並正確複製原始畫布上的所有內容(當您調整畫布對象的大小時,其像素數據將被清除)。

0

正如尚未通過Xenethyl指出,最重要的一點是要在onResize掛鉤,這樣就可以適應新的畫布對象大小:

  • 調整畫布尺寸(繪圖區域的尺寸)到畫布呈現區域(clientWidth和clientHeight)
  • 考慮到畫布的新尺寸繪圖算法
  • 重繪帆布

你不必須製作一個新的畫布(這會迫使你重新綁定其他事件處理程序)。

大部分在我的web應用程序的畫布,以待完全調整到窗口,由專門的類,它的骨架的管理是在這裏:

function Grapher(options) { 
    this.graphId = options.canvasId; 
    this.dimChanged = true; // you may remove that if you want (see above) 
}; 

Grapher.prototype.draw = function() { 
    if (!this._ensureInit()) return; 

    // makes all the drawing, depending on the state of the application's model 

    // uses dimChanged to know if the positions and dimensions of drawed objects have 
    // to be recomputed due to a change in canvas dimensions 

} 

Grapher.prototype._ensureInit = function() { 
    if (this.canvas) return true; 
    var canvas = document.getElementById(this.graphId); 
    if (!canvas) { 
     return false; 
    } 
    if (!$('#'+this.graphId).is(':visible')) return false; 
    this.canvas = canvas; 
    this.context = this.canvas.getContext("2d"); 
    var _this = this; 
    var setDim = function() { 
     _this.w = _this.canvas.clientWidth; 
     _this.h = _this.canvas.clientHeight; 
     _this.canvas.width = _this.w; 
     _this.canvas.height = _this.h; 
     _this.dimChanged = true; 
     _this.draw(); // calls the function that draws the content 
    }; 
    setDim(); 
    $(window).resize(setDim); 
    // other inits (mouse hover, mouse click, etc.) 
    return true; 
}; 

在你的情況我會創造一個new Grapher({canvasId:'#canvas'})和#canvas維度在css中定義(並且通常以複雜的方式調整到可用空間)。

最有趣的一點是在setDim函數中。

2

所以你不想在CSS中定義畫布的大小,因爲你只能將它從「真實」大小縮放。您總是希望使用Canvas的widthheight屬性。

但是,這並不意味着你不能這樣定義它的父母的大小。裹帆布的股利和股利的CSS寬度/高度設置爲100%(或任何你取悅)

在代碼中,你將不得不做安裝過程中:

// javascript pseudocode 
canvas.width = theCanvasParent.clientWidth; // or whatever attribute it is, I'd reccomend putting all of those things in one giant container div 
canvas.height = theCanvasParent.clientHeight; 

由於大多數瀏覽器當父div改變大小時不會觸發事件,那麼您只需每隔半秒就用一個定時器來檢查div是否已經改變大小。如果有,則相應地調整畫布大小。

但是,有onresize事件,並根據您的頁面設置的方式,這可能會伎倆。

在Firefox,Opera,Google Chrome和Safari中,僅當瀏覽器窗口的大小發生更改時,纔會觸發onresize事件

在Internet Explorer中,當瀏覽器窗口或元素的大小發生更改時,會觸發onresize事件。

所以如果要改變你的div的大小的唯一方法是通過改變窗口的大小,onresize會做你很好。否則,您需要一個定時器,不斷檢查畫布大小和div大小是否不同(如果是,則調整畫布大小)。

不停地檢查計時器就是Mozilla的Bepsin團隊做(前貝斯平成爲Skywriter,然後用王牌項目合併,刪除所有帆布使用)

+1

「檢查每半秒」 ewwwwwwww ... – quemeful