WebGL Learning (一)繪製一個藍色矩形

用canvas繪製一個藍色矩形,顯示在網頁上

DrawRectangle.html:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Draw a blue rectangle</title>
</head>
<body onload="main()">
<canvas id="example" width="400" height="400">
    Please use a browser that supports "canvas"
</canvas>
<script src="DrawRectangle.js"></script>
</body>
</html>

main()作爲JS程序的入口,在下面的JS中實現

DrawRectangle.js:

function main(){
    var canvas = document.getElementById("example");
    if(!canvas){
        console.log("Failed to retrieve the <canvas> element");
        return false;
    }

    //Get the rendering context for 2DCG
    var ctx = canvas.getContext("2d");

    ctx.fillStyle = '#0000ff'; //設置填充顏色爲藍色 用'rgba(0,0,255,1.0)'也可
    ctx.fillRect(120,10,150,150); //填充矩形
}

canvas不直接提供繪圖的方法,而是提供叫上下文(context)的機制進行繪圖。
canvas.getContext(“2d”)指定上下文類型爲二維,來繪製二維圖形。同理:3d就是三維圖形。

發佈了51 篇原創文章 · 獲贊 17 · 訪問量 16萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章