Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

161
Visualizações
Append a <tspan> into svg text element with vanilla javascript

I'm trying to use javascript to create a bunch of SVG elements. I've got a lot of it working, and the below code is all working except for one part...

function newPerkLabel (x, y, name) {
    var newLabel = document.createElementNS("http://www.w3.org/2000/svg", "text");
    newLabel.setAttribute("font-size", "0.8em");
    newLabel.setAttribute("x", x);
    newLabel.setAttribute("y", y+25);
    newLabel.setAttribute('fill', '#000');
    newLabel.setAttribute("text-anchor", "middle");
    newLabel.textContent = name;
    svgBox.appendChild(newLabel);
}
function newPerkLabel2 (x, y, name, parent) {
    var newLabel = document.createElementNS("http://www.w3.org/2000/svg", "tspan");
    newLabel.setAttribute("font-size", "0.8em");
    newLabel.setAttribute("x", x);
    newLabel.setAttribute("y", y+25);
    newLabel.setAttribute('fill', '#000');
    newLabel.setAttribute("text-anchor", "middle");
    newLabel.textContent = name;
    parent.appendChild(newLabel);
}
function drawSkillTree(skillTree) {
//Get SVG area
let svgBoxRect = svgBox.getBoundingClientRect();

//Run through each perk in skillTree
for (let i = 0; i < activeSkillTree.perks.length; i++) {

    let perk  = activeSkillTree.perks[i];
    let curXPos = perk.xPos / 100 * svgBoxRect.width;
    let curYPos = perk.yPos / 100 * svgBoxRect.height;

    //Create perk labels
    let perkName = perk.name;
    if (perkName.indexOf('<br>') != -1) {
        let perkNameLines = perkName.split('<br>');
        let line1 = newPerkLabel(curXPos, curYPos, perkNameLines[0]); 
        newPerkLabel2(curXPos, curYPos, perkNameLines[1], line1);

    } else {
        newPerkLabel(curXPos, curYPos, perkName); 
    }

}

}

I'm trying to have the option of adding in line breaks, and to do that, I need a <tspan> element into the svg <text> element. How would I go about doing that?

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda