簡體   English   中英

通過單擊選項卡,HTML5 Canvas切換內容

[英]HTML5 Canvas switch content by clicking on tabs

我正在做一個關於HTML5 Canvas的簡單項目。 我想在畫布中有一些標簽,例如讓我們使用4個標簽。 所有這些選項卡都應在“活動內容”區域中顯示一些信息(請參見下圖)。 將顯示來自不同選項卡的不同內容。

這是我想要的樣子,非常簡單和基本:

http://i.stack.imgur.com/cWfhA.png

單擊畫布中的不同選項卡時,如何切換內容?

畫布不具有對內容繪圖的本機支持,因為所有內容都只是位圖上的像素,因此要在畫布上獲得這種行為,您必須自己實現基本邏輯。

我會推薦一種基於對象的方法。 將標簽頁創建為對象,然后可以渲染它們,還可以測試它們的點擊率,並且很容易擴展標簽頁等的數量。

現場演示

一個對象可以非常簡單:

var Tab = function(x, y, width, height, color) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.color = color;
    this.lineWidth = 3;
};

然后添加一個方法來構建矩形的路徑並進行渲染,這很簡單:

var Tab = function(x, y, width, height, color) {
    this.x = x;
    this.y = y;
    this.width = width;
    this.height = height;
    this.color = color;
    this.lineWidth = 3;

    /// creates a new path on the context
    this.getPath = function(ctx) {
        ctx.beginPath();
        ctx.rect(this.x, this.y, this.width, this.height);
    };

    /// draws this tab
    this.render = function(ctx) {
        this.getPath(ctx);
        ctx.strokeStyle = this.color;
        ctx.lineWidth = this.lineWidth;
        ctx.stroke();
    };
};

這樣做的目的是將其用於渲染和命中測試。

現在,您可以創建一些標簽:

var myTabs = [
        new Tab(0, 0, 100, 50, 'blue'),
        new Tab(100, 0, 100, 50, 'red'),
        new Tab(200, 0, 100, 50, 'yellow'),
        new Tab(300, 0, 100, 50, 'orange'),
    ];

現在簡單地渲染它們:

for(var i = 0, tab; tab = myTabs[i++];)
    tab.render(ctx);

要進行測試:

for(var i = 0, tab; tab = myTabs[i++];) {
    tab.getPath(ctx);
    if (ctx.isPointInPath(x, y)) {
        // got a hit, update content
    }
}

我將它留給您以擴展Tab對象,使其具有接受和呈現文本的能力,等等​​:-)

希望這可以幫助!

內容可以基於狀態變量來繪制。 您可以使用switch語句執行此操作。 然后,當用戶單擊選項卡時,可以更改狀態變量的值。 要檢測選項卡上的單擊,可以將onclick事件綁定到畫布,然后在事件處理程序中檢查單擊的位置(即單擊的是哪個選項卡),並相應地設置狀態變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM