HTML5的畫布:Stroke(筆觸)和Fill(填充)

一喵嗚發表於2015-08-06

每當一個HTML5畫布上繪製形狀,有兩個屬性,你需要設定:

1、Stroke

2、Fill

筆觸和填充決定的形狀如何繪製。Stroke(筆觸)是一個形狀的輪廓。Fill(填充)是在形狀內部的內容。

下面這圖是繪製了一個藍色外輪廓和綠色填充的矩形(實際上是兩個矩形):



下面試實現的程式碼:

<span style="font-size:14px;">// 1. wait for the page to be fully loaded.
window.onload = function() {
    drawExamples();
}


function drawExamples(){

    // 2. Obtain a reference to the canvas element.
    var canvas  = document.getElementById("ex1");

    // 3. Obtain a 2D context from the canvas element.
    var context = canvas.getContext("2d");


    // 4. Draw grahpics.
    context.fillStyle = "#009900";
    context.fillRect(10,10, 100,100);

    context.strokeStyle = "#0000ff";
    context.lineWidth   = 5;
    context.strokeRect(10,10, 100,100);
}</span>

請注意的筆觸樣式和填充樣式是分開設定,使用strokeStyle 和fillStyle的2D背景的性質。

還得注意這lineWidth屬性,這裡設定了一個線寬為5,最後,注意在2D背景下是如何指示或者畫一個矩形填充或者是矩形輪廓。


相關文章