How to draw with mouse in HTML 5 canvas ?
Last Updated :
05 May, 2025
In this article, we shall explore a few ways to draw with the mouse pointer on the HTML 5 canvas. The HTML canvas is essentially a container for various graphics elements such as squares, rectangles, arcs, images, etc. It gives us flexible control over animating the graphics elements inside the canvas. However, functionality to the canvas has to be added through JavaScript.

In the following procedure, we will use a flag variable to toggle the drawing on and off in relation to the mouse events. The events we will be listening to the mousedown, mouseup and the mousemove events in JavaScript.
The canvas element by default has some properties such as padding etc.(can be changed styles). Hence, properties offsetTop and offsetLeft are used to retrieve the position of the canvas, relative to its offsetParent (closest ancestor element of the canvas in the DOM). By subtracting these values from event.clientX and event.clientY, we can reposition the starting point of the drawing to the tip of the cursor. In the function sketch(), we use the following in-built methods to add functionality.
- beginPath(): Starts a new path, every time left mouse button is clicked.
- lineWidth: Sets the width of the line that will be drawn.
- strokeStyle: In this regard, we use it to set the color of the line to black. This attribute can be changed to produce lines of different colors.
- moveTo(): The Starting position of the path moves to the specified coordinates on the canvas.
- lineTo(): Creates a line to from the said position to the coordinates specified.
- stroke(): Adds stroke to the line created. Without this, the line will not be visible.
Example: Creating a Canvas Element and adding the JavaScript functionality.
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>
Draw with the mouse in a HTML5 canvas
</title>
<style>
* {
overflow: hidden;
}
body {
text-align: center;
}
h1 {
color: green;
}
</style>
</head>
<body>
<h1>GeeksforGeeks</h1>
<b>Draw anything you want</b>
<hr>
<canvas id="canvas"></canvas>
<script src="index.js"></script>
</body>
</html>
JavaScript
// wait for the content of the window element
// to load, then performs the operations.
// This is considered best practice.
window.addEventListener('load', ()=>{
resize(); // Resizes the canvas once the window loads
document.addEventListener('mousedown', startPainting);
document.addEventListener('mouseup', stopPainting);
document.addEventListener('mousemove', sketch);
window.addEventListener('resize', resize);
});
const canvas = document.querySelector('#canvas');
// Context for the canvas for 2 dimensional operations
const ctx = canvas.getContext('2d');
// Resizes the canvas to the available size of the window.
function resize(){
ctx.canvas.width = window.innerWidth;
ctx.canvas.height = window.innerHeight;
}
// Stores the initial position of the cursor
let coord = {x:0 , y:0};
// This is the flag that we are going to use to
// trigger drawing
let paint = false;
// Updates the coordianates of the cursor when
// an event e is triggered to the coordinates where
// the said event is triggered.
function getPosition(event){
coord.x = event.clientX - canvas.offsetLeft;
coord.y = event.clientY - canvas.offsetTop;
}
// The following functions toggle the flag to start
// and stop drawing
function startPainting(event){
paint = true;
getPosition(event);
}
function stopPainting(){
paint = false;
}
function sketch(event){
if (!paint) return;
ctx.beginPath();
ctx.lineWidth = 5;
// Sets the end of the lines drawn
// to a round shape.
ctx.lineCap = 'round';
ctx.strokeStyle = 'green';
// The cursor to start drawing
// moves to this coordinate
ctx.moveTo(coord.x, coord.y);
// The position of the cursor
// gets updated as we move the
// mouse around.
getPosition(event);
// A line is traced from start
// coordinate to this coordinate
ctx.lineTo(coord.x , coord.y);
// Draws the line.
ctx.stroke();
}
Output: The function sketch() will only execute if the value of the flag is true.It is important to update the coordinates stored in the object coord after beginPath(), hence getPosition(event) is called. After linking the JavaScript file to the HTML file, the following code will be obtained.

Similar Reads
How to use the canvas drawImage() method in HTML5 ? The canvas drawImage() method of the Canvas 2D API is used to draw an image in various ways on a canvas element. This method has additional parameters that can be used to display the image or a part of the image. Syntax: context.drawImage(img, x, y, swidth, sheight, sx, sy, width, height); Approach:
2 min read
How to Draw Graphics using Canvas in HTML5 ? In this article, we will draw graphics by using the canvas element in the document. This tag in HTML is used to draw graphics on a web page using JavaScript. It can be used to draw paths, boxes, texts, gradient, and adding images. By default, it does not contain borders and text. Note: This tag is n
1 min read
How to Set the height and width of the Canvas in HTML5? The canvas element is a part of HTML5 which allows us for dynamic, scriptable rendering of 2D shapes and bitmap images, facilitating the creation of games, graphs, animations, and compositions. To set the height and width of the canvas in HTML5, we can utilize the height and width attributes within
2 min read
How to Drawing Canvas in React.js ? In this article, we are going to learn how we can add drawing canvas in ReactJs. React is a free and open-source front-end JavaScript library for building user interfaces or UI components. It is maintained by Facebook and a community of individual developers and companies. Prerequisites:NodeJS or NP
2 min read
How to create 3D cube using canvas in HTML5 ? In this article, we will see How to create 3D cube using canvas in  HTML5. Approach: We will use the canvas element. The HTML Canvas element is used to draw graphics with the help of javascript. It can be used to draw different types of shapes, graphs or create simple and complex animations. Keep i
3 min read