
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.
- Creating a Canvas Element:
<!DOCTYPE html><htmllang="en"><head><metacharset="UTF-8"><metaname="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><canvasid="canvas"></canvas><scriptsrc="index.js"></script></body></html>chevron_rightfilter_none - JavaScript code to make interactive canvas:
// 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 loadsdocument.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 operationsconst ctx = canvas.getContext('2d');// Resizes the canvas to the available size of the window.functionresize(){ctx.canvas.width = window.innerWidth;ctx.canvas.height = window.innerHeight;}// Stores the initial position of the cursorlet coord = {x:0 , y:0};// This is the flag that we are going to use to// trigger drawinglet paint =false;// Updates the coordianates of the cursor when// an event e is triggered to the coordinates where// the said event is triggered.functiongetPosition(event){coord.x = event.clientX - canvas.offsetLeft;coord.y = event.clientY - canvas.offsetTop;}// The following functions toggle the flag to start// and stop drawingfunctionstartPainting(event){paint =true;getPosition(event);}functionstopPainting(){paint =false;}functionsketch(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 coordinatectx.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 coordinatectx.lineTo(coord.x , coord.y);// Draws the line.ctx.stroke();}chevron_rightfilter_none - 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.

Recommended Posts:
- HTML | Canvas Draw Bezier Curve
- How to get the coordinates of a mouse click on a canvas element ?
- How to Draw Graphics using Canvas in HTML5 ?
- How to spin text on mouse hover using HTML and CSS?
- How to Draw a Half Moon using HTML and CSS?
- How to Draw a Semi-Circle using HTML and CSS ?
- How to Draw a Trapezium using HTML and CSS ?
- How to Draw a Pentagon using HTML and CSS?
- HTML | Canvas Basics
- How to resize an image in an HTML 5 canvas ?
- HTML | canvas lineWidth Property
- HTML | canvas textAlign Property
- HTML | canvas font Property
- HTML | canvas lineJoin Property
- HTML | DOM Canvas Object
- How to get Pixel from HTML Canvas ?
- HTML | canvas shadowColor Property
- HTML | canvas rect() Method
- HTML | canvas fillStyle Property
- HTML | canvas strokeStyle Property
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


