【发布时间】:2012-03-30 09:24:02
【问题描述】:
正在玩一个突破性的克隆并想要制作圆角通电。
有人能指出正确的方向吗?
谢谢!
【问题讨论】:
-
How to draw a rounded Rectangle on HTML Canvas? 的副本;尤其见this answer。下次,请先在网站或网络上搜索答案。
正在玩一个突破性的克隆并想要制作圆角通电。
有人能指出正确的方向吗?
谢谢!
【问题讨论】:
一个简单的方法是使用quadraticCurveTo 来平滑边角
function roundRect(x0, y0, x1, y1, r, color)
{
var w = x1 - x0;
var h = y1 - y0;
if (r > w/2) r = w/2;
if (r > h/2) r = h/2;
ctx.beginPath();
ctx.moveTo(x1 - r, y0);
ctx.quadraticCurveTo(x1, y0, x1, y0 + r);
ctx.lineTo(x1, y1-r);
ctx.quadraticCurveTo(x1, y1, x1 - r, y1);
ctx.lineTo(x0 + r, y1);
ctx.quadraticCurveTo(x0, y1, x0, y1 - r);
ctx.lineTo(x0, y0 + r);
ctx.quadraticCurveTo(x0, y0, x0 + r, y0);
ctx.closePath();
ctx.fillStyle = color;
ctx.fill();
}
【讨论】:
arcTo 要简单得多,不是吗? (正如我在您可能正在写答案时发现并链接到的重复问题所证明的那样。)
arc/arcTo 在我看来设计得很糟糕(我什至发现过去浏览器之间存在兼容性问题):我通常使用arc 来画完整的圆圈。您对重复项是正确的,但 IMO 贝塞尔二次曲线更适合此用途。
您可以执行on this article by Juan Mendes 显示的操作:
HTML:
<canvas id="rounded-rect" width="600" height="600">
<!-- Insert fallback content here -->
</canvas>
JavaScript:
CanvasRenderingContext2D.prototype.roundRect = function(x, y, width, height, radius, fill, stroke) {
if (typeof stroke == "undefined") {
stroke = true;
}
if (typeof radius === "undefined") {
radius = 5;
}
this.beginPath();
this.moveTo(x + radius, y);
this.lineTo(x + width - radius, y);
this.quadraticCurveTo(x + width, y, x + width, y + radius);
this.lineTo(x + width, y + height - radius);
this.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
this.lineTo(x + radius, y + height);
this.quadraticCurveTo(x, y + height, x, y + height - radius);
this.lineTo(x, y + radius);
this.quadraticCurveTo(x, y, x + radius, y);
this.closePath();
if (stroke) {
this.stroke(stroke);
}
if (fill) {
this.fill(fill);
}
};
// Now you can just call
var ctx = document.getElementById("rounded-rect").getContext("2d");
// Manipulate it again
ctx.strokeStyle = "#2d6";
ctx.fillStyle = "#abc";
ctx.roundRect(100, 200, 200, 100, 50, true);
正如你在 JsFiddle 上看到的那样
【讨论】: