gpt4 book ai didi

javascript - 如何使用 JS 动态创建 SVG 文本元素

转载 作者:行者123 更新时间:2023-11-28 02:25:47 24 4
gpt4 key购买 nike

所以,我有一个 SVG 元素,它是一个文本。我想使用 javascript 动态创建更多完全相同类型的 SVG 文本元素。 (最好使用某种 for 循环)。一种选择是对值进行硬编码,但我宁愿不这样做。这是我的代码:

var overlapThreshold = "50%";
var name_count = 0;
Draggable.create(".seat_name", {
bounds: "svg",
onDrag: function(e) {
if (this.hitTest("#test1", overlapThreshold)) {
document.getElementById("test1").setAttribute('fill', 'url(#gradRed)');
} else {
document.getElementById("test1").setAttribute('fill', 'url(#gradGreen)');
}
}
});

function change_name(event) {
var name = prompt("Enter a New Name:");
if (name != null && name != "") {
event.target.textContent = name;
}
}
  <button id="test_button" onclick="create_name_tags()">Test</button> <svg height="1000" width="1000">
<defs>
<lineargradient id="gradGreen" x1="0%" x2="100%" y1="0%" y2="0%">
<stop offset="0%" style="stop-color:rgb(152, 251, 152);stop-opacity:1"></stop>
<stop offset="100%" style="stop-color:rgb(0, 128, 0);stop-opacity:1"></stop>
</lineargradient>
<lineargradient id="gradRed" x1="0%" x2="100%" y1="0%" y2="0%">
<stop offset="0%" style="stop-color:rgb(255, 0, 0);stop-opacity:1"></stop>
<stop offset="100%" style="stop-color:rgb(178, 34, 34);stop-opacity:1"></stop>
</lineargradient>
</defs>
<g class="circle_seat" id="circle_seats">
<circle cx="70" cy="200" fill="url(#gradGreen)" id="test1" id="seat1" r="40" stroke="black" stroke-width="1"></circle>
</g>
<g class="seat_name" id="seat_name1">
<text fill="#black" font-family="Verdana" font-size="20" id="seat1_details" ondblclick="change_name(event)" x="250" y="210">
BLANK
</text>
</g>
</svg>

最佳答案

简化示例(可选择使用 Google 字体)

addText("Your Text Here", 20, 50);

function addText(txt, x, y) {
var el = document.createElementNS("http://www.w3.org/2000/svg", "text");
el.textContent = txt;
el.setAttributeNS(null, 'x', x);
el.setAttributeNS(null, 'y', y);
document.getElementById('svg').appendChild(el);
}
#svg{ width:100vw; height:100vw; font-family:'Crafty Girls'; font-size:50px;
stroke:red; fill:yellow; }
<link href="https://fonts.googleapis.com/css2?family=Crafty+Girls&display=swap" rel="stylesheet">

<svg id='svg'></svg>


文档:

关于javascript - 如何使用 JS 动态创建 SVG 文本元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54081437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com