Drawing a line beneath the mouse's center using JavaScript

Struggling with my JavaScript drawing tool, particularly the draw() function. The line is consistently off-center below the mouse cursor. How do I fix this issue? My aim is to have the line always follow the center of the mouse as it moves. Could someone clarify if e.pageX and e.pageY accurately represent the mouse's center coordinates as x and y? Thanks in advance!

<!doctype html>
<html>

<head>
  <style>
    canvas {
      border: 1px solid black;
    }
  </style>
</head>

<body>
  <div class="controls">
    <button class="clear">Clear</button> <span>Color
            <input type="color" value="#ffff00" id="penColor"></span>
    <span>Width
            <input type="range" min="1" max="20" value="10" id="penWidth"></span>
  </div>

  <canvas id="canvas"></canvas>
  <script>
    let penColor = document.getElementById("penColor");
    let penWidth = document.getElementById("penWidth");
    let canvas = document.getElementById("canvas");
    canvas.width = 700;
    canvas.height = 700;

    let context = canvas.getContext("2d");
    let clearButton = document.querySelector(".clear");

    let position = {
      x: null,
      y: null
    }

    let initialization = (e) => {
      canvas.addEventListener("mousemove", draw);
      canvas.addEventListener("mouseenter", setPosition)
      canvas.addEventListener("mousemove", setPosition)
    }

    window.onload = initialization;

    let setPosition = (e) => {
      position.x = e.pageX;
      position.y = e.pageY;
    }

    clearButton.addEventListener("click", (e) => {
      let confirmation = confirm("Are you sure you want to clear the canvas?");

      let result = confirmation ? true : false;
      if (result) {
        context.clearRect(0, 0, canvas.width, canvas.height);
      }
    })


    let draw = (e) => {
      if (e.buttons !== 1) return;
      context.beginPath();
      context.moveTo(position.x, position.y);

      setPosition(e);

      context.lineTo(position.x, position.y);
      context.lineWidth = penWidth.value;
      context.strokeStyle = penColor.value;
      context.lineCap = "round";
      context.stroke();
    }
  </script>
</body>

</html>

Answer №1

Understanding MouseEvent.pageX

When dealing with the MouseEvent interface, the pageX property is a read-only attribute that provides the horizontal coordinate (in pixels) of the mouse click event, relative to the document's left edge.

https://example.com/mouseevent-pagex

It's important to note that this value does not represent the X position on the canvas directly, as adjustments need to be made by subtracting the canvas position.

e.pageX - canvas.offsetLeft;
e.pageY - canvas.offsetTop;

let canvas = document.getElementById("canvas");
canvas.width = canvas.height = 200;

let context = canvas.getContext("2d");
let position = { x: null, y: null }

let setPosition = (e) => {
  position.x = e.pageX - canvas.offsetLeft;
  position.y = e.pageY - canvas.offsetTop;
}

let draw = (e) => {
  if (e.buttons !== 1) return;
  context.beginPath();
  context.moveTo(position.x, position.y);

  setPosition(e);
  context.lineTo(position.x, position.y);
  context.stroke();
}

canvas.addEventListener("mousemove", draw);
canvas.addEventListener("mouseenter", setPosition)
canvas.addEventListener("mousemove", setPosition)
canvas {
  border: 1px solid black;
}
<canvas id="canvas"></canvas>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to present a Python list in individual lines on an HTML webpage?

This might be a simple question, and I apologize if I haven't explained it clearly. This is my first time working with HTML, and I'm using a given program that I don't fully comprehend. In the python program, app.py, I read a list of string ...

Exploring the wonders of CSS with Socialchef

Hey, I recently came across a solution on Stack Overflow where they provided code for SocialChef to convert decimal inputs into fractions. I'm wondering how I can write or incorporate some code to input fractions and mantissa as a fraction... I ...

"Displaying the y-axis in d3.js: A Step-by-Step

I am a beginner in d3.js and I'm having trouble with my y-axis not showing up in the browser. Can someone please help me find a solution? var barOffset=5; var barWidth=50; var width=700,height=700; function processData(data,key){ var objects=[]; ...

What is the best way to reverse a condition in CSS?

Here is my HTML/CSS code, I am relatively new to this field. Please let me know if I have overlooked anything. .dropdown-menu>li>a { padding: 3px 5px; } <li> <a id="btn-other-1" href="#"> <!–- I do not want apply css for t ...

The text box is intersecting with the photo

Struggling to craft a clean layout with an upvote button, I encountered an issue where the textarea appears to overlap with the image. Below is my sample code snippet: .my-component-row { display: flex; justify-content: center; align-items: center ...

Searching for a comprehensive guide to web-related terminology that is widely accepted

Constantly immersing myself in studying the languages I am familiar with and exploring new development concepts and languages is a regular practice for me. When it comes to books, O'Reilly is my go-to choice, but when it comes to online resources, I&a ...

Make sure the bootstrap row extends to the full height of the page

I am currently working on a Django project and I am in the process of integrating Bootstrap into my HTML files. One issue I am facing is that the row in my HTML template is only as big as its content, but I want it to take up the entire height of the page ...

Modify the CSS properties of the asp:AutoCompleteExtender using JavaScript

Is there a way to dynamically change the CompletionListItemCssClass attribute of an asp:AutoCompleteExtender using JavaScript every time the index of a combobox is changed? Here is the code snippet: ajaxtoolkit: <asp:AutoCompleteExtender ID="autocom" C ...

PHP script is not successfully receiving the Ajax post request that is

As a newcomer to the world of php and ajax, I am facing a challenge in passing a variable from jquery to a php page loaded within a modal window. My php script fetches table information for multiple users. Next to each user's name, there is an edit b ...

Challenges of performance in EmberJS and Rails 4 API

My EmberJS application is connected to a Rails 4 REST API. While the application is generally working fine, it has started to slow down due to the nature of the queries being made. Currently, the API response looks like this: "projects": [{ "id": 1, ...

Employing plain Javascript (without the use of jQuery) to concatenate information from two JSON strings - encountering an error due to the absence of

Having a JSON stringified form data like this: {"name":"jack miller", "address":"123 main st"} I aimed to append more records but encountered an error saying "append is not a function." The desired outcome is to have both sets of records in this format: ...

Establishing a pair of separate static directories within Nest

I am looking to utilize Nest in order to host two static applications. Essentially, I have a folder structure like this: /public /admin /main Within my Nest application, I currently have the following setup: app.useStaticAssets(join(__dirn ...

I want to utilize a select drop-down menu for navigating between pages in my pagination, breaking away from the traditional method of using <a> tags

I have a select dropdown that is dynamically generated for navigation to other pages within the script. It lists the number of pages available for navigation. However, after selecting a page and loading it, the dropdown does not stay selected. I've tr ...

What is the best way to initialize a value asynchronously for React context API in the latest version of NextJS, version

Currently, I'm working on implementing the React context API in my NextJS e-commerce application to manage a user's shopping cart. The challenge I'm facing is how to retrieve the cart contents from MongoDB to initiate the cart context. This ...

Trouble fetching data for my controller in AngularJS using UI Router resolve

My attempts to inject a resolve object containing loaded data into my controller are resulting in an Unknown Provider error : Error message: Unknown provider: configServiceProvider <- configService Below is the code I am working with: StateProvider ...

Having difficulty connecting images or photos to CodePen

I've been attempting to connect images and sound files to my CodePen project using a Dropbox shared link. <div class="container"> <div class="row second-line"> <div class="col-12"> <div d ...

Object of Razor enclosed within an anchor tag

Exploring the realm of MVC 4 and Razor is new to me. Currently, I am attempting to create a Gallery with "CSS3 Lightbox". Everything seems fine, but I am encountering difficulties with Razor and links. The issue lies in my understanding of the pre and ne ...

What is the best way to keep an HTML element visible on the page while it remains within the boundaries of another HTML object?

On my webpage, I have a selection of reports available. Currently, there are 4 sizable buttons located on the right-hand side for viewing, adding, editing, or deleting a report. However, there have been complaints from users who find it inconvenient to scr ...

Tips for accessing raw POST data in PHP using $_SERVER

I am facing a challenge with my dynamic page where I use on-page filters that modify the data through AJAX response. My concern is how to access raw POST data when it's not visible in the URL... The link on my page appears as "example.com/default/lis ...

Encountering the 'navigator is not defined' error when attempting to generate a Next JS build

After developing a custom hook in Next JS to retrieve network online status using the JavaScript navigator.onLine property, everything seemed to work flawlessly on my local machine. However, upon running npm run build to compile the project, I encountered ...