How to Draw Shapes with Javascript?

Through JavaScript, we can draw many shapes on the HTML canvas. We will draw many shapes in javascript in this blog post, so let’s start.

Draw Rectangular Shapes in javascript

HTML

<body onload="draw();">

<canvas id="canvas" width="200" height="200"></canvas>

</body>

Javascript

function draw() {
  var canvas = document.getElementById('canvas');
  if (canvas.getContext) {
    var context = canvas.getContext('2d');

    context.fillRect(20,20,100,100);
    context.clearRect(30,30,80,80);
    ctx.strokeRect(50, 50, 50, 50);
  }
}

Result

Draw Circle Shapes in javascript

Html

<body onload="draw();">

<canvas id="canvas" width="200" height="200"></canvas>

</body>

Javascript

function draw() {

    var c = document.getElementById("canvas");
    var ctx = c.getContext("2d");
    ctx.beginPath();
    ctx.arc(100, 75, 50, 0, 2 * Math.PI);
    ctx.stroke();

}

Result

Draw a circle in javascript

Draw a right-angled triangle in javascript

Html

<body onload="draw();">

<canvas id="canvas" width="150" height="150"></canvas>

</body>

Javascript

function draw() 
{
  var canvas = document.getElementById('canvas');
  if (canvas.getContext)
  {
    var context = canvas.getContext('2d');

    context.beginPath();
    context.moveTo(75,75);
    context.lineTo(10,75);
    context.lineTo(10,25);
    context.fill();
  }
}

Result

Right angle triangle

Similarly, we can draw many more shapes and sizes.

Visit: drawing shape in js