Languages
[Edit]
EN

JavaScript - draw rectangle on canvas element

0 points
Created by:
Selina-Miranda
737

In this article, we would like to show you how to draw a rectangle on an HTML canvas element using JavaScript.

Quick solution:

var canvas = document.querySelector('#my-canvas');
var context = canvas.getContext('2d');
context.beginPath();
context.rect(10, 10, 150, 100); // rect(x, y, width, height)
context.stroke();

 

Practical example

In this section, we present a practical example of how to use rect() method to draw a rectangle on the canvas.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>
    
    #my-canvas { border: 1px solid gray; }
    
  </style>
</head>
<body>
  <canvas id="my-canvas" width="200" height="200"></canvas>
  <script>

    var canvas = document.querySelector('#my-canvas');
    var context = canvas.getContext('2d');

    function drawRectangle(x, y, width, height) {
        context.beginPath();
        context.rect(x, y, width, height);
        context.stroke();
    }

    drawRectangle(10, 10, 150, 100);

  </script>
</body>
</html>

References

  1. CanvasRenderingContext2D.rect() - Web APIs | MDN

Alternative titles

  1. JavaScript - draw rectangle on HTML canvas element
  2. JavaScript - rect() method on HTML canvas element
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

JavaScript - HTML5 canvas tutorial

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join