繪製矩形 canvas 繪製矩形及弧形

2021-10-14 22:46:33 字數 2045 閱讀 6475

矩形是唯一一種可以直接在 2d 上下文中繪製的形狀。與矩形有關的方法包括 fillrect() 、strokerect() 和 clearrect()

這三個方法都能接收 4 個引數:矩形的 x 座標、矩形的 y 座標、矩形寬度和矩形高度

首先, fillrect() 方法在畫布上繪製的矩形會填充指定的顏色。填充的顏色通過fillstyle 屬性指定

// 先設定填充色

context.fillstyle = '#ccc';

// 灰色實心矩形

// 1. 語法: x座標, y座標, 寬度, 高度

context.fillrect(10, 10, 50, 50);

// 透明實心矩形

語法: x座標, y座標, 寬度, 高度

// 1. 語法: x座標, y座標, 寬度, 高度

座標:(x, y); w: 寬度 , h: 高度

ctx.beginpath();

// 線條顏色

ctx.strokestyle = 'orange';

// 填充顏色

ctx.fillstyle = 'red';

ctx.linewidth = 2;

ctx.rect(350, 50, 100, 100);

// 描邊

ctx.stroke();

// 填充

ctx.fill();

image.png

畫弧形的語法:

從上一點(起始點) 開始繪製一條曲線,到(x2, y2)位置,並且以(x1, y1)和(x2, y2);為控制點,radius: 弧形半徑

ctx.arcto(x1, y1, x2, y2, radius);

說白話: arcto會利用起始點 ,(x1, y1), (x2, y2)三個點,所形成的夾角,然後繪製一段與夾角兩邊相切的圓弧

弧形可以成為矩形的四個角,使其成為乙個圓角矩形

ctx.beginpath();

ctx.linewidth = 4;

ctx.strokestyle='blue';

// 起始點

ctx.moveto(50, 150);

// 左上角

ctx.arcto(50, 100, 100, 100, 50);

// 右上角

ctx.arcto(250, 100, 250, 150, 50);

// 右下角

ctx.arcto(250, 300, 200, 300, 50);

// 左下角

ctx.arcto(50, 300, 50, 250, 50);

ctx.closepath();

ctx.stroke();

Canvas繪製矩形

context.rect x y width height 規劃了矩形的路徑 context.fillrect x y width height 根據fillstyle繪製出乙個填充的矩形 context.strokerect x y width height 根據strokestyle繪製出乙個矩...

canvas繪製矩形

1.繪製乙個填充的矩形 fillrect x,y,width,height 2.繪製乙個矩形的邊框 strokerect x,y,width,height 3.清除指定矩形區域,讓清除部分完全透明 clearrect x,y,width,height 其中x y是相對於畫布左上角0,0 的距離,wi...

Canvas 元素繪製矩形

使用canvas元素,必須先設定 width 和 height 屬性,指定可以繪圖的區域大小。要在這塊畫布上繪圖,需要取得繪圖上下文。而取得繪圖上下文物件的引用,需要呼叫 getcontext 方法並傳入上下文的名字。傳入 2d 就可以取得2d上下文物件。與矩形相關的方法包括 fillrect st...