如何在矩形上制作圆弧?

时间:2017-05-02 03:01:49

标签: javascript html5 html5-canvas

我知道我可以使用moveTo(),lineTo()方法绘制不规则的矩形,但是如果我想在矩形上创建一个弧呢?

以下是我的想法: 我在两个lineTo()之间添加一个arc(),并在下面的图中显示。

function draw(){
    var c = document.getElementById("Canvas");
    var ctx = c.getContext("2d");

    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(40,40);
    ctx.lineTo(80,40);
    ctx.lineTo(80,80);
    ctx.arc(80,150,70,0.5*Math.PI,1.5*Math.PI,true);
    ctx.lineTo(80,260);
    ctx.lineTo(40,260);
    ctx.lineTo(40,40);
    ctx.stroke();
}

it's result I run for my code

这不是我预期的结果,我想呈现这样的图形,弧形和矩形之间没有线条。

It's the result I expected

2 个答案:

答案 0 :(得分:1)

只需反转圆弧绘制顺序即可。您目前正在从6点钟到12点钟进行绘制。

这里的关键点是arc确实包含lineTo(startPoint.x, startPoint.y),因此您需要处理此问题。

如果您想保留此订单,则必须在绘制弧线之前moveTo 6点钟,并在绘制完毕后再次moveTo 6 o'弧。



function draw(){
    var ctx = c.getContext("2d");
    var rad = 70,
    w = 40,
    h = 220,
    x = 40,
    y = 40;
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(x, y); // top left
    ctx.lineTo(x + w, y); // top right
    // draw a line to the end of your arc
    ctx.lineTo(x + w, y + (h - (rad * 2)) / 2);
    // move to the start of the arc (6 o'clock)
    ctx.moveTo(x + w, y + ((h - (rad * 2)) / 2) + rad * 2);
    // draw the arc
    ctx.arc(x + w, y + h/2, rad, 0.5*Math.PI, 1.5*Math.PI, true);
    // move again to the start of the arc (6 o'clock)
    ctx.moveTo(x + w, y + ((h - (rad * 2)) / 2) + rad * 2);
    ctx.lineTo(x + w, y + h); // bottom right
    ctx.lineTo(x, y + h); // bottom left
    ctx.lineTo(x, y); // top right again
    ctx.stroke();
}
draw();

<canvas id="c" height="300"></canvas>
&#13;
&#13;
&#13;

通过反转它,您可以避免这些moveTo

&#13;
&#13;
function draw() {
  var ctx = c.getContext("2d");
  var rad = 70,
    w = 40,
    h = 220,
    x = 40,
    y = 40;
  ctx.lineWidth = 1;
  ctx.beginPath();
  ctx.moveTo(x, y); // top left
  ctx.lineTo(x + w, y); // top right
  // to the start of the arc (12 o'clock)
  ctx.lineTo(x + w, y + (h - (rad * 2)) / 2);
  // draw the arc
  ctx.arc(x + w, y + h / 2, rad, 1.5 * Math.PI, 0.5 * Math.PI, false);
  ctx.lineTo(x + w, y + h); // bottom right
  ctx.lineTo(x, y + h); // bottom left
  ctx.lineTo(x, y); // top right again
  ctx.stroke();
}
draw();
&#13;
<canvas id="c" height="300"></canvas>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

两件事:(1)弧需要在一个单独的路径中,(2)以保持路径打开的方式改变起点和终点。

function draw(){
    var c = document.getElementById("Canvas");
    var ctx = c.getContext("2d");

    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(80,220);
    ctx.lineTo(80,260);
    ctx.lineTo(40,260);
    ctx.lineTo(40,40);
    ctx.lineTo(80,40);
    ctx.lineTo(80,80);
    ctx.stroke();
    ctx.beginPath();
    ctx.arc(80,150,70,0.5*Math.PI,1.5*Math.PI,true);
    ctx.stroke();
}