How can you use HTML and SVG to move just one endpoint of a line using a mouse click?

I have been exploring ways to selectively move one end of a line, but I am encountering difficulties as it keeps altering the container and ultimately redrawing the entire line.

Here is a JSFiddle link for reference: https://jsfiddle.net/h2nwygu8/1/

<html>

  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="chrome=1">
    <title>Review Race</title>
  </head>

  <body>
    <div class="wrapper">
      <section>
        <h1>Line Test</h1>
        <div id="canvas" style="width: 960px; height:410px; border: 4px solid lime;">
          <svg id="svgContainer" xmlns="http://www.w3.org/2000/svg" version="1.1" style="position: absolute; top:95px; width:960px; height:410px;">
                    <line id="start_line" x1="10" y1="0" x2="10" y2="960" style="stroke:rgb(255,0,0);stroke-width:3;" />
                    </svg>
        </div>
      </section>
    </div>
  </body>

</html>

And here is the JavaScript code:

function moveTopLineEnd(event) {
  var line = document.getElementById('start_line');

  posY = event.clientY;
  posX = event.clientX;
  line.setAttribute("y1", posY)
  line.setAttribute("x1", posX)
}

document.addEventListener("click", moveTopLineEnd);

My goal is to have the top edge of the red line follow the mouse cursor's position over the green box while keeping the bottom end fixed. However, the issue arises from the containers changing with each click, causing the entire line to move. Additionally, there are inconsistencies in the offsets between the mouse cursor and the line. The only requirement is that the line should overlay the green boundary container.

Can anyone suggest the most effective approach to achieve this? Thank you.

Answer №1

There seems to be a confusion between the height and width when it comes to the x2 and y2 properties. To achieve the desired result, try setting y2 to match your height (410px).

For reference: https://jsfiddle.net/zukrtpyg/.

HTML:

<div id="canvas" style="width: 960px; height:410px; border: 4px solid lime;">
   <svg id="svgContainer" xmlns="http://www.w3.org/2000/svg" version="1.1" style="width:960px; height:410px;">
       <line id="start_line" x1="0" y1="0" x2="0" y2="410" style="stroke:rgb(255,0,0);stroke-width:3;" />
   </svg>
</div>

Javascript:

function placeLine(e) {
  var d = document.getElementById('start_line');

  posY = e.offsetY;
  posX = e.offsetX;
  d.setAttribute("y1", posY)
  d.setAttribute("x1", posX)
}

document.getElementById('canvas').addEventListener("click", placeLine);

The top and position declarations on the canvas element have been removed, as they were causing the line to exceed the green border at the bottom.

Additionally, the click listener has been changed to the canvas element, allowing the use of offsetX and offsetY to position the line relative to the canvas element, aligning with the path coordinates.

While clientX and clientY positions can still be used, adjustments must be made based on the canvas element's position on the page. To determine this, utilize Element.getBoundingClientRect(). Refer to https://jsfiddle.net/th0aLcx0/ for an example.

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

The panel header is clickable and overlaps with the header buttons

My panel component includes a header with a title and buttons positioned in the right corner. Currently, the downward arrow (chevron) is used to toggle the expansion/minimization of the panel's contents. When I attempt to make the header clickable to ...

Implement image uploading feature with Ant Design library in a React JS application

I need assistance with a basic application that allows users to upload images. Once the image is uploaded and the user clicks on the get data from upload button, the result should be displayed in the console as console.log("Received values of form: ", valu ...

I'm looking to create a post using two mongoose models that are referencing each other. How can I do this effectively?

My goal is to create a Post with the author being the user who created it and have the Post added to the array of posts in the user model that references "Post". Despite searching and watching tutorials, I'm still struggling to understand how to achie ...

Error: cannot use .json data with `filter` method from WEBPACK_IMPORTED_MODULE_2__["filter"]

There seems to be an error occurring when attempting to retrieve data from a JSON file in the specific line of code selectedEmployee: employeeList.data.Table[0], An issue is arising with TypeError: _employeeList_json__WEBPACK_IMPORTED_MODULE_2__.filter ...

Building an Angular 4 universal application using @angular/cli and integrating third-party libraries/components for compilation

While attempting to incorporate server side rendering using angular universal, I referenced a post on implementing an angular-4-universal-app-with-angular-cli and also looked at the cli-universal-demo project. However, I ran into the following issue: Upon ...

Is it possible to capture a screen recording in Selenium using JavaScript?

While my tests are running, I am looking for a way to record my screen. I came across a post about screen recording using Java at . However, the code provided is in Java and I require something in JavaScript. Is it possible to record the screen using Jav ...

Troubleshooting issue with Gulp watch on Node v4.6.0

I'm currently facing a frustrating situation. I had a project up and running smoothly with a functioning gulpfile.js file, everything was perfect until I updated node to version 4.6.0. When I tried to report this issue on Gulp's git repository, t ...

The CSS property overflow:hidden or overflow:scroll is not functioning as expected when applied to a

On my practice website, I have set up a demonstration for showcasing text data. The issue arises when the user inserts an excessive amount of characters in the text box. To address this, I would like the text to be scrollable so that all content can be d ...

Can different versions of Node be used simultaneously for various Node scripts?

Currently, I am utilizing nvm. Can a specific node version be used for a particular script? For instance... Using node 6 forever start -a -l $MYPATH/forever.log -e $MYPATH/err.log -c "node --max_old_space_size=20" $MYPATH/script_with_node_version_6.js U ...

What happens to the npm package if I transfer ownership of a github repository to a different user?

I was considering transferring a GitHub repository to another user or organization, but I have concerns about what will happen to older versions of the npm package associated with it. Let's say my Node.js package is named node-awesome-package. Versi ...

What is the best way to restrict users from accessing more than 5 Bootstrap Tab-Panes at once?

Users are restricted to opening only a maximum of 5 tab panes, even if there are multiple tab buttons available. If the user tries to click on the 6th tab, an alert message will be displayed. function addTab(title, url){ var tabs=$(".tabs"), tab ...

Issue with data binding in file upload field

I am currently working on a project using Asp.Net Core MVC. In the model, there is a property called IFormFile. While using a basic input tag, everything works perfectly fine. However, when I tried to implement the file input plugin from this URL, the mode ...

Altering hues upon clicking the link

I'm looking for a way to set up my menu in the header using "include/header.php" and have it so that when I click on a link, it takes me to that page while also changing colors to indicate it's active. Would jQuery or PHP be more suitable for thi ...

The position of the mouse on the canvas following a CSS scaling

I'm currently working on finding the mouse coordinates on an HTML5 canvas element. I set the canvas dimensions to 700x700. When I hover over the canvas, I aim to retrieve the X,Y coordinates of the mouse. Everything goes smoothly until I resize the c ...

Is it possible to use the HTML script tag without specifying the type attribute as JavaScript? <script type="text/html"></script>?

While examining the source code of an HTML page, I stumbled upon the following snippet: <script id="searchItemTemplate" type="text/html"> <# var rows = Math.floor((Model.RecordsPerPage - 1) / 3 + 1); for (var i = 0; i < rows; ++i){ ...

Encountered a 404 error while trying to delete using VueJS, expressJS, and axios. Request failed with

Currently, I'm in the process of learning the fundamentals of creating a MEVN stack application and facing a challenge with the axios DELETE request method. The issue arises when attempting to make a DELETE request using axios, resulting in a Request ...

Generating fresh line with knockout effect

Currently in the process of developing a Single Page Application (SPA). Utilizing knockout and observable array to iterate through a json array. Encountering an issue where there are br tags present within the text, but when using data-bind="text: myVar" ...

CSS: Breaking free from the constraints of a Bootstrap-inspired grid layout

Looking to create a template with a background on the left side that extends to the edge of the page within an 8 of 12 bootstrap columns setup. The remaining 4 columns on the right will not have a background. This layout should be responsive, stacking on t ...

What is the best way to store my JSON output in a JavaScript variable?

In my jsonOutput.php page, the code looks like this: $response['imgsrc'] = $filename[1]; echo json_encode($response); When executed, it produces a JSON output like {"imgsrc":"071112164139.jpg"} My query now is, how can I make use of ...

(React) Error: Unable to access property 'this' as it is set to undefined while trying to utilize refs

When using a ref in React to refer to an input field, I encountered an error: "Uncaught TypeError: Cannot read property 'this' of undefined". Despite having defined the ref, React seems unable to locate it in my code. What could be causing this i ...