JavaScript Canvas – Draw a Line in canvas using Mouse and Touch events

In this tutorial, I am going to show you how to draw lines in JavaScript canvas using mouse and touch events. This post is for absolute beginners who want to know how to use some of the JavaScript canvas methods with events to draw shapes.
What is JavaScript Canvas?
Canvas is an element which acts as a container, Imagine it as a plain board. Canvas itself is not a drawing container, you can only draw shapes by accessing the context API in JavaScript by using getContext('2d')
which returns the reference to the 2D context inside the canvas.
<canvas id="drawContainer" width="500" height="500"
style="border: 1px solid #333"></canvas>
This is how you can create a canvas element in your HTML. It’s mandatory for a canvas element to have width and height attributes. If you change the canvas width and height by using CSS width and height properties, the canvas will only scale up and down (not recommended).
Draw a Line in JavaScript Canvas
Before we dive into the canvas tutorial on drawing using mouse and touch events, we will have a look at how can we use some of the built-in JavaScript canvas methods to draw a static line.
In order to draw any shapes in canvas, you should get the 2D context of the API as below
const canvasEle = document.getElementById('drawContainer');
const context = canvasEle.getContext('2d');
To draw a line on the canvas, you should create a path using beginPath()
method in context API. After that, you can use moveTo(x,y)
method to move the drawing cursor based on x
and y
parameters.
// To draw a static line.
context.beginPath();
context.lineWidth = '5'; // width of the line
context.strokeStyle = 'red'; // color of the line
context.moveTo(50,50); // begins a new sub-path based on the given x and y values.
context.lineTo(50, 100); // used to create a pointer based on x and y
context.stroke(); // this is where the actual drawing happens.
- The
lineWidth
property is used to set the width of the line. - The
strokeStyle
property is used to set the color of the line. - The
moveTo(x, y)
method is used to begin a sub-path based on the given x and y value. In other words, It’s used to move the cursor. If you are a CSS person imagine it as padding in a div(padding-top: 50px, padding-left: 50px)
. - The
lineTo(x,y)
method is used to create a pointer from where the cursor left in the last method in our case it’s x = 50 and y = 50. Still, drawing won’t happen. - The
stroke()
method is used to draw the stroke/outlines based on the given stroke style.
That’s all it takes to draw a line using JavaScript canvas. Let’s dive deeper into how to draw a line using mouse and touch events.
Draw Line in Canvas using Mouse and Touch Events
We are going to use 6 types of events for mouse and touch:
mousedown
which gets triggered by clicking the mouse button.mousemove
gets triggered whenever you move the mouse.mouseup
gets triggered when you release the mouse button.touchstart
gets triggered by touching the canvas.touchmove
gets triggered whenever you move your finger on the screen.touchend
gets triggered when you release the touch.
const canvasEle = document.getElementById('drawContainer');
const context = canvasEle.getContext('2d');
let startPosition = {x: 0, y: 0};
let lineCoordinates = {x: 0, y: 0};
let isDrawStart = false;
const getClientOffset = (event) => {
const {pageX, pageY} = event.touches ? event.touches[0] : event;
const x = pageX - canvasEle.offsetLeft;
const y = pageY - canvasEle.offsetTop;
return {
x,
y
}
}
const drawLine = () => {
context.beginPath();
context.moveTo(startPosition.x, startPosition.y);
context.lineTo(lineCoordinates.x, lineCoordinates.y);
context.stroke();
}
const mouseDownListener = (event) => {
startPosition = getClientOffset(event);
isDrawStart = true;
}
const mouseMoveListener = (event) => {
if(!isDrawStart) return;
lineCoordinates = getClientOffset(event);
clearCanvas();
drawLine();
}
const mouseupListener = (event) => {
isDrawStart = false;
}
const clearCanvas = () => {
context.clearRect(0, 0, canvasEle.width, canvasEle.height);
}
canvasEle.addEventListener('mousedown', mouseDownListener);
canvasEle.addEventListener('mousemove', mouseMoveListener);
canvasEle.addEventListener('mouseup', mouseupListener);
canvasEle.addEventListener('touchstart', mouseDownListener);
canvasEle.addEventListener('touchmove', mouseMoveListener);
canvasEle.addEventListener('touchend', mouseupListener);
The above code is the complete code to draw a line on JavaScript canvas using mouse and touch events. Let’s see what’s happening
Declare 3 variables:
let startPosition = {x: 0, y: 0};
let lineCoordinates = {x: 0, y: 0};
let isDrawStart = false;
startPosition
– to store the x and y coordinates of the starting position of the line when the user clicked the canvas.lineCoordinates
– to store the x and y coordinates of the end position of the line. It gets updated whenever the user moves the mouse.isDrawLine
– a boolean to detect whether the user has clicked the mouse or not. Themousemove
event triggers whenever you move the mouse.
canvasEle.addEventListener('mousedown', mouseDownListener);
canvasEle.addEventListener('mousemove', mouseMoveListener);
canvasEle.addEventListener('mouseup', mouseupListener);
canvasEle.addEventListener('touchstart', mouseDownListener);
canvasEle.addEventListener('touchmove', mouseMoveListener);
canvasEle.addEventListener('touchend', mouseupListener);
Bind the following event listeners to the JavaScript canvas element: (mousedown, mousemove, mouseup, touchstart, touchmove, touchend)
Calculate the Start Position of the Line
const mouseDownListener = (event) => {
startPosition = getClientOffset(event);
isDrawStart = true;
}
The mouseDownListener
function calculates the startPosition
of the line by calling the getClientOffset
function.
We change the value of isDrawLine
to true, the purpose of this boolean is to prevent the mouse-move event if the user doesn’t click the mouse button because mouse move event triggers whenever the user moves the mouse even without clicking a mouse button.
Create a function to calculate the X and Y coordinates
const getClientOffset = (event) => {
const {pageX, pageY} = event.touches ? event.touches[0] : event;
const x = pageX - canvasEle.offsetLeft;
const y = pageY - canvasEle.offsetTop;
return {
x,
y
}
}
The getClientOffset
function is used to get the exact coordinates of x
and y
axis when the user clicks or touches the JavaScript canvas. To detect the exact location of the x
and y
axis in the canvas element, we should subtract pageX
and pageY
of the mouse event or touch events with the canvas element offsetLeft
and offsetTop
.
Draw Line in Canvas on mouse move
const mouseMoveListener = (event) => {
if(!isDrawStart) return;
lineCoordinates = getClientOffset(event);
clearCanvas();
drawLine();
}
The mouseMoveListener
function invokes whenever the user moves the mouse (touch move). At the very start of the function, we check boolean isDrawLine
to detect whether the user clicked the mouse button (touched the screen) or not. If it’s false, we call return
statement to prevent further execution.
Then, we calculate the end position of the line by invoking getClientOffset
function and stores the returned value in lineCoordinates
variable.
const clearCanvas = () => {
context.clearRect(0, 0, canvasEle.width, canvasEle.height);
}
After that, we should clear the JavaScript canvas using clearCanvas
function. Clearing the canvas is super important otherwise, the canvas will draw more lines whenever you move the mouse.
const drawLine = () => {
context.beginPath();
context.moveTo(startPosition.x, startPosition.y);
context.lineTo(lineCoordinates.x, lineCoordinates.y);
context.stroke();
}
The drawLine
function is responsible to draw the line in the canvas. Use context.beginPath()
method to begin the path, It actually tells the canvas that we are about to draw some paths in the canvas. To set the starting position of the line, invoke context.moveTo(startPosition.x, startPosition.y);
method.
The lineTo
method is used to set the end position of the line. Till now, nothing gets rendered in the canvas. The actual drawing happens once we call the context.stroke()
method.
Stop Drawing
const mouseupListener = (event) => {
isDrawStart = false;
}
To stop drawing the line, we set the isDrawLine
to false when the user leaves the mouse or touch screen. so that further mouse move (touch move) events will not execute the drawing.
Codepen Demo
See the Pen Draw a Line in Canvas using Mouse and Touch Events by Nithya Rajan (@bearnithi) on CodePen.default
Summary
I hope, This canvas tutorial helps you to understand what’s the use of some of the JavaScript canvas methods. Also, you learned how to use mouse and touch events to draw lines on JavaScript canvas.
- Declare variables to store start position and end position coordinates of the line.
- Bind mousemove, mousedown, mouseup, touchmove, touchstart, touchend events to the canvas element.
- Use a boolean to prevent mousemove if the user doesn’t click the mouse button.
- Clear the canvas in mouse move.
- Use beginPath, moveTo, lineTo, stroke methods in context API, to draw paths/lines.