Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
305 views
in Technique[技术] by (71.8m points)

reactjs - How to get coordinates (x,y) from a svg and put a text tag with a value

I'm trying to do a web app on React to write guitar tabs, i'm doing the tabs with SVG. I think i know how to get the coords but the problem is i don't know how to put that text tag with a value, because it doesn't have a value attribute (i think so)

my function:

// Doesn't work
// Suppose that i want to add a 2
const clicked = (evt) =>{
    const { currentTarget: svg, pageX, pageY } = evt
    const coords = svg.getBoundingClientRect()  //<----- get the coords
    const text = document.createElementNS('http://www.w3.org/2000/svg','text') //<--- create the svg
    text.setAttribute('x', `$pageX - coords.x`) //<----- set the attributes X and Y with the mouse coords
    text.setAttribute('y', `$pagey - coords.y`)
    text.setAttribute('value', "2")             //<----- It doesn't work
    svg.appendChild(text)
  }

enter image description here

heres other function, but to put circles:

//IT WORKS
clicked(evt) {
        const {currentTarget: svg, pageX, pageY} = evt;
        const coords = svg.getBoundingClientRect();
        const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
        circle.setAttribute('cx', `${pageX - coords.x}`);
        circle.setAttribute('cy', `${pageY - coords.y}`);
        circle.setAttribute('r', '5');
        svg.appendChild(circle);
    }

enter image description here

question from:https://stackoverflow.com/questions/65910120/how-to-get-coordinates-x-y-from-a-svg-and-put-a-text-tag-with-a-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Text is not an attribute, it's content so you want to replace

text.setAttribute('value', "2")

with

text.appendChild(document.createTextNode("2"))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...