iT邦幫忙

2021 iThome 鐵人賽

DAY 7
0
Modern Web

Canvas 小錦囊系列 第 7

Day 7 - 用 canvas 復刻 小畫家 繪製矩形與圓角矩形

繪製矩形

核心

先來學習繪製矩形的方法

strokeRect 使用當前的繪畫樣式,描繪一個起點在 (x, y) 、寬度為 w 、高度為 h 的矩形的方法。

void ctx.strokeRect(x, y, width, height);

再來只要知道滑鼠移動的位置即可知道高寬

const handleDrawCanvas = (point: pointIF) => {
  ...
  case "rectangle":
      const width = point?.x - initialPoint?.x;
      const height = point?.y - initialPoint?.y;
      ctx.strokeRect(initialPoint?.x, initialPoint?.y, width, height);
  break;
  ...
}
 
const handleMouseDown = (event: any) => {
  ...
  case "rectangle":
    initialPoint = { x: point?.x, y: point?.y };
    break;
  ...
};

是不是似曾相似?
還記得,在上一篇我們學習到清空及復原上個畫面完成直線,本篇章利用相同的原理來繪製矩形。

const handleDrawCanvas = (point: pointIF) => {
  ...
  case "rectangle": 
      clearCanvas(); // 補上
      restore(); // 補上
      const width = point?.x - initialPoint?.x;
      const height = point?.y - initialPoint?.y;
      ctx.strokeRect(initialPoint?.x, initialPoint?.y, width, height);
  break;
  ...
}
 
const handleMouseDown = (event: any) => {
  ...
  case "rectangle":
    initialPoint = { x: point?.x, y: point?.y };
    break;
  ...
};

const handleMouseDown = (event: any) => {
  ...
  case "rectangle":
    initialPoint = { x: point?.x, y: point?.y };
    saveCanvas(); // 補上
    break;
  ...
};

完成矩形啦!

補充

順便補充其他矩形的相關參數

ctx.shadowColor = '#d53' // 光暈顏色
ctx.shadowBlur = 20; // 光暈粗度 

這兩者通常會一起使用

圓角矩形

核心

先來學習繪製矩形的方法

arcTo 使用給定的控制點和半徑將圓弧添加到當前子路徑。 如果指定參數需要,圓弧會自動使用直線連接到路徑的最新點。

void ctx.arcTo(x1, y1, x2, y2, radius);

給予各個點來繪製帶有圓角的矩形

const handleMouseDown = (event: any) => {
  ...
 case "roundedRectangle":
  clearCanvas();
  restore();
  ctx.strokeStyle = activeColor;
  roundRect(ctx, initialPoint?.x, initialPoint?.y, width, height, 10); // 繪製圓角矩形
  ctx.stroke();
  break;
  ...
};



const roundRect = (ctx ,x ,y ,w ,h , r:圓角的程度) => {
    if (w < 2 * r) r = w / 2;
    if (h < 2 * r) r = h / 2;
    ctx.beginPath();
    ctx.moveTo(x + r, y);
    ctx.arcTo(x + w, y, x + w, y + h, r);
    ctx.arcTo(x + w, y + h, x, y + h, r);
    ctx.arcTo(x, y + h, x, y, r);
    ctx.arcTo(x, y, x + w, y, r);
};

迅速地搞定!


上一篇
Day 6 - 用 canvas 復刻 小畫家 直線
下一篇
Day 8 - 用 canvas 復刻 小畫家 繪製圓形/橢圓形
系列文
Canvas 小錦囊30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言