如何用直线和圆弧正确填充HTML画布?

时间:2018-10-21 15:49:39

标签: html canvas

我要创建由线条和曲线组成的图形,如下所示。
而且我也想填补它。

<!DOCTYPE html>
<html>
<body>

<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

<script>

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.beginPath();

// half of arc
ctx.arc(100, 75, 50, 0.5 * Math.PI, 1.5 * Math.PI);

ctx.moveTo(100, 125);
ctx.lineTo(10, 125);		// bottom line
ctx.lineTo(10, 25);			// left line
ctx.lineTo(100, 25);		// left line
ctx.stroke();

</script> 

</body>
</html>

但是ctx.fill()丢弃曲线并以矩形填充,如下所示。

<!DOCTYPE html>
<html>

<body>

  <canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

  <script>
    var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.beginPath();
    https: //stackoverflow.com/questions/ask#

      // half of arc
      ctx.arc(100, 75, 50, 0.5 * Math.PI, 1.5 * Math.PI);

    ctx.moveTo(100, 125);
    ctx.lineTo(10, 125); // bottom line
    ctx.lineTo(10, 25); // left line
    ctx.lineTo(100, 25); // left line
    ctx.stroke();
    ctx.fill();
  </script>

</body>

</html>

如何正确填写我的身材?

1 个答案:

答案 0 :(得分:1)

您必须按照逻辑顺序画线。

 var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.beginPath();
    ctx.moveTo(100, 125)
    ctx.arc(100, 75, 50, 0.5 * Math.PI, 1.5 * Math.PI);
    ctx.lineTo(10, 25); // left line
    ctx.lineTo(10, 125); // bottom line
    ctx.closePath()
    ctx.stroke();
    ctx.fill()
 
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>

或者,您也可以这样:

 var c = document.getElementById("myCanvas");
    var ctx = c.getContext("2d");
    ctx.beginPath();
    ctx.arc(100, 75, 50, 1.5 * Math.PI, .5 * Math.PI,true);
    ctx.moveTo(100, 125);
    ctx.lineTo(10, 125); // bottom line
    ctx.lineTo(10, 25); // left line
    ctx.lineTo(100, 25); // left line
    ctx.stroke();
    ctx.fill();
 
<canvas id="myCanvas" width="300" height="150" style="border:1px solid #d3d3d3;">
Your browser does not support the HTML5 canvas tag.</canvas>