Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> HTML

วิธีวาดสี่เหลี่ยมมุมโค้งบน HTML Canvas


บทนำ

Canvas ไม่มีเมธอดวาดสี่เหลี่ยมมุมโค้งโดยตรง ต้องใช้ lineTo() และ quadraticCurveTo() ร่วมกันเพื่อสร้างมุมโค้ง

ตัวอย่างโค้ด

<!DOCTYPE HTML>
<html>
  <head>
    <title>HTML5 Canvas Rounded Rectangle</title>
  </head>
  <body>
    <canvas id="newCanvas" width="300" height="150"></canvas>
    <script>
      var canvas = document.getElementById('newCanvas');
      var ctx = canvas.getContext('2d');
      ctx.beginPath();
      ctx.moveTo(20, 10);
      ctx.lineTo(80, 10);
      ctx.quadraticCurveTo(90, 10, 90, 20);  // มุมขวาบน
      ctx.lineTo(90, 80);
      ctx.quadraticCurveTo(90, 90, 80, 90);  // มุมขวาล่าง
      ctx.lineTo(20, 90);
      ctx.quadraticCurveTo(10, 90, 10, 80);  // มุมซ้ายล่าง
      ctx.lineTo(10, 20);
      ctx.quadraticCurveTo(10, 10, 20, 10);  // มุมซ้ายบน
      ctx.stroke();
    </script>
  </body>
</html>

ฟังก์ชันสำเร็จรูป (Reusable)

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.stroke(); // หรือ ctx.fill()
}