What is the best way to prevent two paths within an SVG from intersecting with each other?

Currently, I am developing a program that allows the user to draw lines. Once the user completes drawing a line, I receive an array of points in this format: [[x, y], [x, y], ...].

I then convert these points into a path string using the following function:

export const pointsToSVGPathString = (points) => points
    .map(({x, y}, idx) => idx ? `${x} ${y}`:`M ${x} ${y}`)
    .join(' ') 

After obtaining the string, I generate a new path element like so:

export const createSvgFromPoints = (points, namespaceURI) => {
const path = document.createElementNS(namespaceURI, "path");
const stroke = pointsToSVGPathString(points)
path.setAttributeNS(null, 'd', stroke)
path.setAttributeNS(null, "fill", "none");
path.setAttributeNS(null, "stroke", COLOR_WRITING.DRAWING_COLOR); 
path.setAttributeNS(null, "stroke-width", 9);  
path.setAttributeNS(null, "stroke-linecap", 'round');  
path.setAttributeNS(null, "stroke-linejoin", 'round');  

return path
}

Finally, I retrieve the target SVG element using the document's ID and append the created path with appendChild().

The functionality works smoothly, however, each time a new line is drawn and added to the SVG, its start point gets connected to the end of the previous line. How can I prevent this issue?

Answer №1

To ensure the integrity of your new path, it is important to clear the array of previous points before incorporating new ones.

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

Utilizing Vue and Vuex to execute Axios operations within a store module

Currently, I am developing an application in Vue that utilizes Vuex for state management. For CRUD operations on the data, I have implemented Axios. The issue arises when, for example... I make a POST request to my MongoDB database through an Express ...

JavaScript is sending a variable to a .php file, which then returns data based on the variable. The information is displayed using JavaScript and AJAX, along with triggers set using the bind('input', function

Currently, I am attempting to create a form that automatically populates some input fields when there is a change. However, I am struggling to understand how to send the #url field to my PHP script. Any insights or suggestions would be greatly appreciated. ...

The use of anonymous arrow functions results in Fast Refresh not maintaining local component state

I am facing an issue with the code in my pages/index.js file: import React from 'react'; import dynamic from 'next/dynamic'; const TVChartContainer = dynamic( () => import('../components/TVChartContainer').then ...

The button colors in Material Ui do not update properly after switching themes

React Material UI is being utilized in this project. Although the theme is being overridden, the colors of buttons and inputs remain unchanged. Here is how the Material UI theme is created in theme.js // @flow import { createMuiTheme } from '@materi ...

Error: Papa is not defined. The file was loaded from the CDN in the header section

I have integrated the cdn hosted lib for PapaParse in my HTML header. However, when I execute my JavaScript file and it reaches the function where I call Papa.unparse(data); It throws an error stating that Papa is undefined. This has left me puzzled as I h ...

Code in JavaScript: Generating Random Number within a Loop

Can anyone help me come up with a unique JavaScript loop that can guess a correct number within the range of 1-500? I want each iteration of the loop to generate a new number that has not been guessed before, but it should guess in a random order. For ex ...

ES6 Class Directive for Angular 1.4

I am currently exploring the possibility of incorporating a directive from version 1.4 and adapting it to resemble a 1.5 component. By utilizing bindToController and controllerAs, I aim to integrate the controller within my directive rather than using a se ...

Having trouble accessing JSON response properties within an Angular.js controller

My Angular.js controller is called 'forecastController'. This is the code for the Angular.js Controller: weatherApp.controller('forecastController', ['$scope','$routeParams','cityService', 'weat ...

Can someone provide a description for a field within typedoc documentation?

Here is the code snippet: /** * Description of the class */ export class SomeClass { /** * Description of the field */ message: string; } I have tested it on the TSDoc playground and noticed that there is a summary for the class, but not for it ...

Mapping arguments as function values

Hello there, I have an array of objects that I am attempting to map through. const monthObject = { "March 2022": [ { "date": "2022-03-16", "amount": "-50", &q ...

Select the first item that is visible and chosen

Currently, I am working with a select list: <option ng-repeat="hour in Hours" value="{{hour.Value}}" ng-show="filterEvent($index)" ng-selected="hour.Value == EventDate || $first"> {{hour.Text}} </opti ...

Combining Jquery with Append to Dynamically Update PHP Variables

Code Snippet (index.html) <script> $(document).ready(function() { var interval = setInterval(function() { $.get("load_txt.php", { 'var1': 4, 'var2' : 52}, function(data){ $('#msg' ...

Is the RadioButton change jQuery function malfunctioning following modifications to the DOM?

After updating the HTML of the radio button (with the same name) through AJAX based on certain logic (such as rate or duration changes), I noticed that the change(function(e) method worked perfectly before the DOM was updated. However, once the DOM chang ...

Leveraging JavaScript within the Selenium JavaScript Executor

I am trying to check if the required text is visible on the page, but I am unable to use the gettext() method from Selenium WebDriver due to a permission exception. As a workaround, I have created a JavaScript script to compare the text. String scriptToE ...

Efficiently handling multiple form submissions using a single jQuery Ajax request

I'm working on a page that has 3-4 forms within divs, and I want to submit them all with just one script. Additionally, I want to refresh the content of the specific div where the form is located. However, I'm unsure of how to specify the current ...

The regex string parameter in node.js is not functioning properly for matching groups

The String.prototype.replace() method documentation explains how to specify a function as a parameter. Specifying a string as a parameter The replacement string can contain special patterns for inserting matched substrings, preceding and following portion ...

Mapping an array using getServerSideProps in NextJS - the ultimate guide!

I'm facing an issue while trying to utilize data fetched from the Twitch API in order to generate a list of streamers. However, when attempting to map the props obtained from getServerSideProps, I end up with a blank page. Interestingly, upon using co ...

Switch the dropdown selection depending on the checkbox status

I'm currently facing a bit of confusion with my project. I am constrained by an existing framework and need to come up with a workaround. To simplify, I am tasked with populating a dropdown list based on the selected checkboxes. I have managed to get ...

Should we integrate a MongoDB database calculation app with a POST Controller in sails.js?

The primary function of the application interface is to provide variables that have been initially posted by the client, as well as any subsequent database calculations carried out in real time by a specialized engine. Is it possible to integrate this eng ...

Retrieve and save files under a common directory

I have a specific route called payments/transactions that retrieves all relevant data. I'm interested in finding a way to generate a CSV file without the need to create new routes or add query parameters, so that my route appears as payments/transacti ...