JavaScript: Draw a rectangular shape

JavaScript Drawing: Exercise-1 with Solution

Write a JavaScript program to draw the following rectangular shape.

Sample output:

rectagular shape

Sample Solution:

HTML Code:

<!DOCTYPE html>
<meta charset=utf-8 />
<title>Draw a rectangular shape</title>
<body onload="draw();">
<canvas id="canvas" width="150" height="150"></canvas>

JavaScript Code:

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


Live Demo:

See the Pen javascript-drawing-exercise-1 by w3resource (@w3resource) on CodePen.

Improve this sample solution and post your code through Disqus.

Previous: javascript Drawing Exercises.
Next: Write a JavaScript program to draw a circle.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.