HTML Canvas 坐標

畫布坐標

HTML 畫布是一個二維的網格。

畫布的左上角坐標為 (0,0)。

在上一章中,我們使用了方法:fillRect(0,0,150,75)。

意思是:從左上角 (0,0) 開始繪制一個 150x75 像素的矩形。

坐標實例

將鼠標懸停在下面的矩形上,可查看其 x 和 y 坐標:

X
Y

畫線

要在畫布上繪制直線,請使用以下方法:

  • moveTo(x,y) - 定義線的起點
  • lineTo(x,y) - 定義線的終點

要實際繪制線條,您必須使用“顏料”方法之一,比如 stroke()。

Your browser does not support the HTML5 canvas tag.

實例

在位置 (0,0) 定義起點,在位置 (200,100) 定義終點。然后使用 stroke() 方法來實際地繪制線條:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.moveTo(0, 0);
ctx.lineTo(200, 100);
ctx.stroke();

親自試一試

畫一個圓

要在畫布上繪制圓形,請使用以下方法:

  • beginPath() - 開始一條路徑
  • arc(x,y,r,startangle,endangle) - 創建圓弧/曲線

要使用 arc() 創建圓:請將起始角度設置為 0,結束角度設置為 2*Math.PI。 x 和 y 參數定義圓心的 x 和 y 坐標。 r 參數定義圓的半徑。

Your browser does not support the HTML5 canvas tag.

實例

使用 arc() 方法定義一個圓。然后使用 stroke() 方法來實際繪制圓:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");
ctx.beginPath();
ctx.arc(95, 50, 40, 0, 2 * Math.PI);
ctx.stroke();

親自試一試

另請參閱:

CodeW3C.com 的完整 Canvas 參考手冊