Menu
×
   ❮     
HTML CSS JAVASCRIPT SQL PYTHON JAVA PHP HOW TO W3.CSS C C++ C# BOOTSTRAP REACT MYSQL JQUERY EXCEL XML DJANGO NUMPY PANDAS NODEJS R TYPESCRIPT ANGULAR GIT POSTGRESQL MONGODB ASP AWS AI GO KOTLIN SASS VUE GEN AI SCIPY CYBERSECURITY DATA SCIENCE
     ❯   

HTML Canvas Rectangles

Example

Draw a 150*100 pixels rectangle:

YourbrowserdoesnotsupporttheHTML5canvastag.
const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

ctx.beginPath();
ctx.rect(20, 20, 150, 100);
ctx.stroke();
Try it Yourself »

The rect() Method

The rect() method adds a rectangle to the path.

The syntax is context.rect(x, y, width, height)

Param Description Play it
x The x-coordinate of the upper-left corner of the rectangle Play it »
y The y-coordinate of the upper-left corner of the rectangle Play it »
width The width of the rectangle, in pixels Play it »
height The height of the rectangle, in pixels Play it »


More Examples

Example

Create three rectangles with the rect() method:

Yourbrowserdoesnotsupportthecanvastag.

JavaScript:

const canvas = document.getElementById("myCanvas");
const ctx = canvas.getContext("2d");

// Red rectangle
ctx.beginPath();
ctx.lineWidth = "6";
ctx.strokeStyle = "red";
ctx.rect(5, 5, 290, 140);
ctx.stroke();

// Green rectangle
ctx.beginPath();
ctx.lineWidth = "4";
ctx.strokeStyle = "green";
ctx.rect(30, 30, 50, 50);
ctx.stroke();

// Blue rectangle
ctx.beginPath();
ctx.lineWidth = "10";
ctx.strokeStyle = "blue";
ctx.rect(50, 50, 150, 80);
ctx.stroke();
Try it Yourself »

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Copyright 1999-2023 by Refsnes Data. All Rights Reserved. W3Schools is Powered by W3.CSS.