简体   繁体   中英

Filling an existing svg rectangle with text

I'm trying to use JavaScript to create an SVG rectangle with text in it. I've already got the rectangle (generated by morris.js, a charting library) but can't seem to be able to get the text in.

The output I want to achieve would look a bit like this:

 <svg> <g> <rect x="0" y="0" width="100" height="100" fill="red"></rect> <text x="0" y="50" font-family="Verdana" font-size="35" fill="blue">Hello</text> </g> </svg> 

This is my code now (snippet will not run because rectangleElement is undefined here):

 console.log(rectangleElement); /* output: <rect x="1205.5019308035712" y="0" width="193.5206919642857" height="307" r="0" rx="0" ry="0" fill="#E5E5E5" stroke="none" fill-opacity="0.8" style="-webkit-tap-highlight-color: rgba(0, 0, 0, 0); fill-opacity: 0;"></rect> */ var t = document.createElementNS('http://www.w3.org/2000/svg', 'text'); var g = document.createElementNS('http://www.w3.org/2000/svg', 'g'); g.appendChild(t); g.appendChild(rectangleElement); console.log(g); /* output: <g><text></text></g> */ 

As you can see, the rectangleElement isn't being added to my group ( g ). I'm also not getting any errors in the console when trying to append the rectangle to the group.

Any ideas on what I could be doing wrong?

I ended up fixing it myself. I'm not at all sure what the issue was, when I added the seemingly unrelated code below, it started working.

var txtElem = document.createElementNS("http://www.w3.org/2000/svg", "text");
txtElem.setAttributeNS(null,"x",20);
txtElem.setAttributeNS(null,"y",40);
var theText = "text";
var theMSG = document.createTextNode(theText);
txtElem.appendChild(theMSG);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM