說說如何使用 Canvas 繪製基本矩形

HTML5 提供的 canvas 元素,可以讓我們使用 JavaScript 在網頁上繪製圖像。畫布是一個矩形區域,我們可以控制其每一像素。canvas 擁有多種繪製路徑、矩形、圓形、字符以及添加圖像的方法。這次先說說如何繪製基本矩形。

1 搭建 Canvas 2D 環境

(1)引入 <canvas> 標籤

在 HTML 的 <body> 中新增一個 <canvas> 標籤。形如:

<canvas id="canvas" width="500" height="500"></canvas>

<canvas> 標籤有以下3個主要屬性。

屬性 說明
id 標識該 <canvas> 標籤。
width 畫布寬度,以像素爲單位 。
height 畫布高度,以像素爲單位 。

(2)獲取 Canvas 對象以及 2D 環境

利用下面的代碼,就可以獲取 Canvas 對象的 2D 環境。

let theCanvas = document.querySelector("#canvas");
let context = theCanvas.getContext("2d");

這樣, Canvas 2D 環境就搭建好了,我們可以開始繪圖啦O(∩_∩)O

2 Canvas 座標體系

Canvas 中的座標體系是以左上角( 0 , 0 )爲原點的 windows 窗體和 svg 也是如此。這樣設計主要是因爲過去標準的 CRT 監視器是從上到下、從左到右來顯示圖像的。

3 繪製基本矩形

繪製基本矩形有 3 種不同方式,它們分別是填充、描邊以及清除。

(1)填充

利用 fillRect() 方法,就可以繪製填充矩形。 fillRect() 方法提供以下入參:

參數 描述
x 矩形左上角的 x 座標
y 矩形左上角的 y 座標
width 矩形的寬度,以像素計
height 矩形的高度,以像素計
    //繪製填充矩形
    context.fillStyle = '#3498db';
    context.fillRect(20, 20, 145, 85);

    context.fillStyle = '#1bbc9d';
    context.fillRect(200, 20, 145, 85);

    context.fillStyle = '#dd7195';
    context.fillRect(380, 20, 145, 85);

運行結果:

fillStyle 屬性用於指定填充的顏色,顏色使用 RGB 來指定。

(2)描邊

利用 strokeRect() 方法,可以繪製描邊矩形。 strokeRect() 方法提供以下入參:

參數 描述
x 矩形左上角的 x 座標
y 矩形左上角的 y 座標
width 矩形的寬度,以像素計
height 矩形的高度,以像素計
    context.lineWidth = 1;
    context.strokeStyle = '#3498db';
    context.strokeRect(20, 200, 145, 85);

    context.strokeStyle = '#1bbc9d';
    context.strokeRect(200, 200, 145, 85);

    context.strokeStyle = '#dd7195';
    context.strokeRect(380, 200, 145, 85);

運行結果:

strokeStyle 屬性用於指定邊線的顏色;lineWidth 用於指定邊線寬度。

(3)清除

clearRect() 方法用於清除指定矩形區域,讓其完全透明,一般用於製作特殊圖示。它擁有以下屬性:

參數 描述
x 要清除的矩形左上角的 x 座標
y 要清除的矩形左上角的 y 座標
width 要清除的矩形的寬度,以像素計
height 要清除的矩形的高度,以像素計
   context.fillStyle = '#3498db';
    context.fillRect(20, 350, 550, 60);
    //指定區域透明
    for (let i = 1; i < 20; i++) {
        let x = 30 * i;
        console.log('x -> ' + x);
        context.clearRect(x, 350, 10, 10);
    }

運行結果:

在實心矩形中,通過清除多個透明矩形區域,就可以製作出這樣的城牆圖示啦O(∩_∩)O

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章