【问题标题】:How to make a pill shape in Canvas? (rounded corner rect basically)如何在 Canvas 中制作药丸形状? (基本上是圆角矩形)
【发布时间】:2012-03-30 09:24:02
【问题描述】:

正在玩一个突破性的克隆并想要制作圆角通电。

有人能指出正确的方向吗?

谢谢!

【问题讨论】:

标签: html canvas


【解决方案1】:

一个简单的方法是使用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 要简单得多,不是吗? (正如我在您可能正在写答案时发现并链接到的重复问题所证明的那样。)
  • @Phrogz:使用贝塞尔弧使得各向异性舍入变得微不足道,并且四分之一圆和二次贝塞尔弧之间的差异在 IMO 小到足以在大多数情况下可以接受。画布arc/arcTo 在我看来设计得很糟糕(我什至发现过去浏览器之间存在兼容性问题):我通常使用arc 来画完整的圆圈。您对重复项是正确的,但 IMO 贝塞尔二次曲线更适合此用途。
【解决方案2】:

您可以执行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 上看到的那样

【讨论】:

  • 有些地方坏了。 jsfiddle 也不起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多