canvas-繪制矩形及弧形

矩形是唯一一種可以直接在 2D 上下文中繪制的形狀。與矩形有關(guān)的方法包括 fillRect() 、strokeRect() 和 clearRect()
這三個方法都能接收 4 個參數(shù):矩形的 x 坐標(biāo)、矩形的 y 坐標(biāo)、矩形寬度和矩形高度

繪制灰色實(shí)心矩形、透明實(shí)心矩形

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

// 先設(shè)置填充色
context.fillStyle = '#ccc';
// 灰色實(shí)心矩形
// 1. 語法: x坐標(biāo), y坐標(biāo), 寬度, 高度
context.fillRect(10, 10, 50, 50);

// 透明實(shí)心矩形
context.fillStyle = 'rgba(0, 0, 0, .5)';
context.fillRect(30, 30, 50, 50);
image.png

繪制空心的矩形

語法: x坐標(biāo), y坐標(biāo), 寬度, 高度

// 1. 語法: x坐標(biāo), y坐標(biāo), 寬度, 高度
context.strokeStyle = 'rgba(255, 0, 0, 1)';
context.strokeRect(100, 10, 50, 50);

context.strokeStyle = 'rgba(255, 255, 0, 1)';
context.strokeRect(120, 30, 50, 50);

image.png

矩形路徑

ctx.rect(x, y, w, h);
坐標(biāo):(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

繪制弧形

畫弧形的語法:
從上一點(diǎn)(起始點(diǎn)) 開始繪制一條曲線,到(x2, y2)位置,并且以(x1, y1)和(x2, y2);為控制點(diǎn),radius: 弧形半徑
ctx.arcTo(x1, y1, x2, y2, radius);
說白話: arcTo會利用起始點(diǎn) ,(x1, y1), (x2, y2)三個點(diǎn),所形成的夾角,然后繪制一段與夾角兩邊相切的圓弧

image.png

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

ctx.beginPath();
ctx.lineWidth = 4;
ctx.strokeStyle='blue';
// 起始點(diǎn)
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();
image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容