HTML5 Game - Using the arcTo() Method to draw rounded rectangles

Introduction

We can use arcTo() method to draw an arc.

This method takes the following form:

context.arcTo(x1, y1, x2, y2, radius) 

x1, y1, x2, and y2 are the control points, and radius is the radius of the arc.

The control points are special points attached to a curve that are used to alter the curve's shape and angle.

Stretching a control point changes the shape of a curve.

Rotating a control point changes the curve's angle.

The following code uses the arcTo() method to draw rounded rectangles.

Demo

ResultView the demo in separate window

<!DOCTYPE html>
<html lang="en">
 <head> 
  <meta charset="UTF-8"> 
  <title>HTML5 Canvas</title> 
  <script type="text/javascript">
    window.onload = function(){/*from  w w w .  ja v  a2s.  c o  m*/
        let canvas = document.getElementById("myCanvas");
        let context = canvas.getContext("2d");
        // draw stuff here
        let x = 25; 
        let y = 50; 
        let width = 150; 
        let height = 100; 
        let radius = 20; 
        context.lineWidth = 10; 
        // top and top right corner 
        context.moveTo(x + radius, y); 
        context.arcTo(x + width, y, x + width, y + radius, radius); 
        // right side and bottom right corner 
        context.arcTo(x + width, y + height, x + width - radius, y + height, radius); 
        // bottom and bottom left corner 
        context.arcTo(x, y + height, x, y + height - radius, radius); 
        // left and top left corner 
        context.arcTo(x, y, x + radius, y, radius); 
        context.stroke(); 
    };
</script> 
 </head> 
 <body> 
  <canvas id="myCanvas" width="300" height="200"></canvas>   
 </body>
</html>

Note

This code calls the arcTo() method four times.

The first call draws the top edge and upper-right corner of the rectangle.

The second call draws the right edge and lower-right corner.

The third call draws the bottom edge and lower-left corner.

The fourth call draws the left edge and upper-left corner.

Related Topic