html5 canvas中繪制矩形實(shí)例

字號:


    本文翻譯自steve fulton & jeff fulton html5 canvas, chapter 2, “the basic rectangle shape”.
    讓我們來看一下canvas內(nèi)置的簡單幾何圖形 — 矩形的繪制。在canvas中,繪制矩形有三種方法:填充(fillrect)、描邊(strokerect)以及清除(clearrect)。當(dāng)然,我們也可以使用“路徑”來描繪包括矩形在內(nèi)的所有圖形。
    以下是上述三種方法的api:
    1.fillrect(x,y,width,height)。繪制一個(gè)從(x,y)開始,寬度為width,高度為height的實(shí)心矩形。
    2.strokerect(x,y,width,height)。繪制一個(gè)從(x,y)開始,寬度為width,高度為height的矩形框。該矩形框會(huì)根據(jù)當(dāng)前設(shè)置的strokestyle、linewidth、linejoin和miterlimit屬性的不同而渲染成不同的樣式。
    3.clearrect(x,y,width,height)。清除從(x,y)開始,寬度為width,高度為height的矩形區(qū)域,使之完全透明。
    在調(diào)用上述方法繪制canvas之前,我們需要設(shè)定填充和描邊的樣式。設(shè)定這些樣式最基本的方法是使用24位色(用16進(jìn)制字符串表示)。以下是一個(gè)簡單的例子:
    代碼如下:
    context.fillstyle = #000000;
    context.strokestyle = #ff00ff;
    在下面的例子中,填充色設(shè)定為黑色,而描邊色則設(shè)定為紫色:
    代碼如下:
    function drawscreen() {
    context.fillstyle = #000000;
    context.strokestyle = #ff00ff;
    context.linewidth = 2;
    context.fillrect(10, 10, 40, 40);
    context.strokerect(0, 0, 60, 60);
    context.clearrect(20, 20, 20, 20);
    }