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?