HTML Canvas 提供了绘制矩形的方法, fillRect()
和 strokeRect()
,但是我找不到制作圆角矩形的方法。我怎样才能做到这一点?
原文由 DNB5brims 发布,翻译遵循 CC BY-SA 4.0 许可协议
HTML Canvas 提供了绘制矩形的方法, fillRect()
和 strokeRect()
,但是我找不到制作圆角矩形的方法。我怎样才能做到这一点?
原文由 DNB5brims 发布,翻译遵循 CC BY-SA 4.0 许可协议
使用 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 中绘制圆角矩形:
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>
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 许可协议
5 回答1.9k 阅读
3 回答2.2k 阅读
2 回答1.1k 阅读✓ 已解决
4 回答997 阅读
2.6k 阅读
4 回答873 阅读
2 回答918 阅读
HTML5 画布不提供绘制圆角矩形的方法。
使用
lineTo()
和arc()
方法怎么样?您也可以使用
quadraticCurveTo()
方法代替arc()
方法。