Draw Rectangle on Image with JavaScript – Easy Tutorial

Bobby Jul 13, 2026

In the dynamic world of web development, images are not just passive elements on a page. With JavaScript, you can bring them to life by drawing shapes directly onto them. Today, we're going to explore how to draw a rectangle on an image using JavaScript.

a coffee mug with the letter s on it is surrounded by confetti and sprinkles
a coffee mug with the letter s on it is surrounded by confetti and sprinkles

Before we dive into the coding aspect, let's first visualize what we're aiming to achieve. Imagine having an image on your webpage, and you want to highlight a specific area by drawing a rectangle around it. This could be useful for a variety of purposes, such as intervening user attention, creating interactive heat maps, or even building simple games.

an image of some type of pixel art
an image of some type of pixel art

Understanding the Canvas API

The Canvas API is the backbone of drawing on images in JavaScript. It provides methods and properties to draw graphics, images, text, and even animations on an HTMLcanvas element. To draw a rectangle, we'll be using the strokeRect method, which outline a specified rectangle on the canvas.

landscape
landscape

Before we start drawing, we need to set up our canvas. In HTML, this involves adding acanvas element to your page. In JavaScript, we select this element using methods like getElementById or querySelector, and then initialize a 2D drawing context using the getContext('2d') method.

Setting Up the Canvas

The story of Retronator
The story of Retronator

Let's start with a simple example of setting up the canvas:

// Select the canvas element const canvas = document.getElementById('myCanvas'); // Get the 2D drawing context const ctx = canvas.getContext('2d');

In this example, replace 'myCanvas' with the id of your canvas element. Once we have our drawing context, we're ready to start drawing.

Drawing a Rectangle

Animated Image Slider With HTML CSS JavaScript
Animated Image Slider With HTML CSS JavaScript

Now, let's draw a simple rectangle. The strokeRect method takes four parameters: the x and y coordinates of the top-left corner, and the width and height of the rectangle:

ctx.strokeRect(10, 10, 150, 100);

The coordinates 10, 10 represent the top-left corner of the rectangle. The width is set to 150, and the height to 100. The result is a rectangle extending 150 pixels to the right and 100 pixels down from the top-left corner.

By default, the rectangle is outlined in black. You can change the color using the strokeStyle property before drawing the rectangle:

Front-end Programmer
Front-end Programmer

ctx.strokeStyle = 'blue'; ctx.strokeRect(10, 10, 150, 100);

This will draw a blue rectangle instead of black.

Drawing Rectangles on Image Contexts

an abstract drawing with lines and squares in the center, all connected by intersecting circles
an abstract drawing with lines and squares in the center, all connected by intersecting circles
How Do I Create a Dashed Line Rectangle in Photoshop? | Techwalla
How Do I Create a Dashed Line Rectangle in Photoshop? | Techwalla
the instructions for how to draw eyes in pixel art, with pictures and text below
the instructions for how to draw eyes in pixel art, with pictures and text below
Mulyasriwahyuni Author Portfolio | Magnific (formerly Freepik)
Mulyasriwahyuni Author Portfolio | Magnific (formerly Freepik)
plants are growing out of the windowsills in this pixel art style scene,
plants are growing out of the windowsills in this pixel art style scene,
Create Image Accordion Slider With HTML CSS And JavaScript
Create Image Accordion Slider With HTML CSS And JavaScript
Bruno Pixels
Bruno Pixels
javascript?
javascript?
The Digital World
The Digital World
8 JavaScript Libraries to Animate SVG
8 JavaScript Libraries to Animate SVG
some type of pixel art with different shapes and sizes on the screen, including an image of
some type of pixel art with different shapes and sizes on the screen, including an image of
How to create pure CSS illustrations and animate them - Part 1
How to create pure CSS illustrations and animate them - Part 1
Download Canvas As Image In Javascript
Download Canvas As Image In Javascript
1bit Pixel art - Ko-fi.com
1bit Pixel art - Ko-fi.com
geométrico formas, retângulo vetor ícone ilustração
geométrico formas, retângulo vetor ícone ilustração
an image of a green object on a white background in the shape of a hexagon
an image of a green object on a white background in the shape of a hexagon
16+ Amazing Particles Animation With CSS and JavaScript - OnAirCode
16+ Amazing Particles Animation With CSS and JavaScript - OnAirCode
an image of the letter c in black and yellow with grey letters on it's sides
an image of the letter c in black and yellow with grey letters on it's sides
pixel art with the words creating pixel art with css
pixel art with the words creating pixel art with css

Drawing on a blank canvas is one thing, but what if we want to draw on an existing image? To do this, we need to load the image into our canvas context first, using the drawImage method:

const img = new Image(); img.src = 'image.jpg'; img.onload = function() { ctx.drawImage(img, 0, 0); ctx.strokeRect(10, 10, 150, 100); };

In this example, the image is drawn from the top-left corner (0, 0) of the canvas. Then, a rectangle is drawn on top of the image at the specified coordinates.

Preserving Aspect Ratio

When drawing images onto a canvas, it's crucial to preserve the image's aspect ratio. Otherwise, the image might be stretched or squashed, distorting the original proportions. To preserve the aspect ratio, you can calculate the scaling factors for the width and height, and use the smaller value to scale both dimensions:

const imgWidth = img.width; const imgHeight = img.height; const scaleFactor = Math.min(canvas.width / imgWidth, canvas.height / imgHeight); ctx.drawImage(img, 0, 0, imgWidth * scaleFactor, imgHeight * scaleFactor);

This ensures that the image is resized to fit within the canvas while maintaining its original aspect ratio.

Performance Considerations

While the Canvas API provides powerful functionality, it's important to consider performance when drawing a large number of shapes on an image. Every draw operation can potentially cause a re-render of the page, which can slow down the user interface. One way to optimize performance is by using requestAnimationFrame, which tells the browser to wait until the next screen repaint to execute the drawing commands:

function draw() { // Drawing code here requestAnimationFrame(draw); } draw();

This ensures that the drawing operations are batched together and executed in a single pass, reducing the number of times the browser needs to update the screen.

And there you have it! With these techniques, you're well on your way to creating interactive and engaging web pages that draw rectangles on images using JavaScript. As you delve deeper into the Canvas API, you'll discover a world of possibilities for creating dynamic and responsive visual content on the web.