如何使用 HTML Canvas 绘制圆角矩形?

新手上路,请多包涵

HTML Canvas 提供了绘制矩形的方法, fillRect()strokeRect() ,但是我找不到制作圆角矩形的方法。我怎样才能做到这一点?

原文由 DNB5brims 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 863
2 个回答

方法一:使用路径绘制方法

使用 HTML Canvas 执行此操作的最直接方法是使用 ctx 的路径绘制方法

 const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

function roundedRect(ctx, x, y, width, height, radius) {
  ctx.beginPath();
  ctx.moveTo(x + radius, y);
  ctx.lineTo(x + width - radius, y);
  ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
  ctx.lineTo(x + width, y + height - radius);
  ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  ctx.lineTo(x + radius, y + height);
  ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
  ctx.lineTo(x, y + radius);
  ctx.quadraticCurveTo(x, y, x + radius, y);
  ctx.closePath();
}

ctx.fillStyle = "red";
roundedRect(ctx, 10, 10, 100, 100, 20);
ctx.fill();
 <canvas id="canvas">
  <!-- Fallback content -->
</canvas>

方法二:使用 Path2D

您还可以使用 Path2D 接口在 HTML Canvas 中绘制圆角矩形:

示例 1

 const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

function roundedRect(x, y, width, height, radius) {
  return new Path2D(`M ${x + radius} ${y} H ${x + width - radius} a ${radius} ${radius} 0 0 1 ${radius} ${radius} V ${y + height - radius} a ${radius} ${radius} 0 0 1 ${-radius} ${radius} H ${x + radius} a ${radius} ${radius} 0 0 1 ${-radius} ${-radius} V ${y + radius} a ${radius} ${radius} 0 0 1 ${radius} ${-radius}`);
}

ctx.fillStyle = "blue";
ctx.fill(roundedRect(10, 10, 100, 100, 20));
 <canvas id="canvas">
  <!-- Fallback content -->
</canvas>

示例 2

 const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");

function roundedRect(x, y, width, height, radius) {
  let path = new Path2D();
  path.moveTo(x + radius, y);
  path.lineTo(x + width - radius, y);
  path.quadraticCurveTo(x + width, y, x + width, y + radius);
  path.lineTo(x + width, y + height - radius);
  path.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
  path.lineTo(x + radius, y + height);
  path.quadraticCurveTo(x, y + height, x, y + height - radius);
  path.lineTo(x, y + radius);
  path.quadraticCurveTo(x, y, x + radius, y);
  path.closePath();
  return path;
}

ctx.fillStyle = "green";
ctx.fill(roundedRect(10, 10, 100, 100, 20));
 <canvas id="canvas">
  <!-- Fallback content -->
</canvas>

原文由 mrwolferinc 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题