HTML5 Canvas Draw Straight Line with Mouse

HTML5 Canvas Draw Straight Line with Mouse
Code Snippet:Draw a Line in Canvas using Mouse and Touch Events
Author: Nithya Rajan
Published: January 19, 2024
Last Updated: January 22, 2024
Downloads: 674
License: MIT
Edit Code online: View on CodePen
Read More

This code enables HTML5 Canvas to draw a straight line with a mouse. It works by tracking mouse movements, and when the mouse is pressed and moved, it draws lines on the canvas. It’s helpful for creating interactive drawings or sketches.

Whether you are working on a canvas drawing tool or just want to add a line drawing feature, this code snippet is quite helpful for you. You can easily copy/paste its functionality to your existing project.

How to Create “HTML5 Canvas Draw Straight Line With Mouse” Functionality

1. Begin by setting up an HTML canvas element in your document. You can customize the canvas size to fit your needs. The following code snippet shows the HTML required for this step.

<canvas id="drawContainer" width="500px" height="500px"></canvas>

2. Customize the canvas appearance using CSS. You can adjust the canvas size, border, and background to match your website’s style.

#drawContainer{
   border: 1px solid #333;
   background: #fff;
}

3. Finally, add the following JavaScript code to your project to enable the line drawing functionality. It listens to mouse events and calculates coordinates to draw lines. Attach event listeners to the canvas for mouse and touch events, enabling users to draw with both methods.

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);

Feel free to modify the code to suit your specific needs. You can add color options, line thickness controls, or save functionality to enhance the drawing experience.

That’s all! hopefully, you have successfully created a functionality to draw a straight line with mouse and touch. If you have any questions or suggestions, feel free to comment below.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About CodeHim

Free Web Design Code & Scripts - CodeHim is one of the BEST developer websites that provide web designers and developers with a simple way to preview and download a variety of free code & scripts. All codes published on CodeHim are open source, distributed under OSD-compliant license which grants all the rights to use, study, change and share the software in modified and unmodified form. Before publishing, we test and review each code snippet to avoid errors, but we cannot warrant the full correctness of all content. All trademarks, trade names, logos, and icons are the property of their respective owners... find out more...

Please Rel0ad/PressF5 this page if you can't click the download/preview link

X