无法向svg追加形状

Unable to append shape to svg

本文关键字:追加 svg      更新时间:2023-09-26

它在元素(png图像)上的dragstart事件上的打印id,然而,shape在dragend事件上没有被附加到svg。

window.onload = function ()
            {
                var svg = d3.select("body")
                        .append("svg")
                        .attr("width", 800)
                        .attr("height", 803);
            };
            var shapeId = "";
            function getId(id)
            {
                shapeId = id;
                console.log(shapeId);
            }
            function createShape()
            {
                if (shapeId == 'newTask')
                {
                    createRect();
                }
            }
            function createRect() 
            {
                console.log("createRect function called");
                svg.append("rect")
                        .attr("id", "onRectDragStart")
                        .attr("rx", 10)
                        .attr("width", 51)
                        .attr("height", 41)
                        .attr("x", "100")
                        .attr("y", "100")
                        .attr("stroke-width", 2)
                        .attr("stroke", "#7E7E7E")
                        .style('cursor', 'move')
                        .style("fill", "white")
                        .classed("initialDragRect", true);
            }
HTML:

<div id="content">
            <div style="position: relative; height: 100%;">
            <div><a id="newTask" title="Add new task" draggable="true" ondragstart=getId(this.id) ondragend="createShape(this)"><img src="task.png" /></a></div>
   </div>
    <div id="canvas" tabindex="0"></div>
</div>

createRect()函数在控制台被调用作为其打印消息,但形状没有被附加

createShape(this)在拖拽事件中被调用

您应该在DOM完全加载之后加载脚本,因为您正在使用事件与DOM进行交互。

的例子:

 <!DOCTYPE HTML>
    <html>
    <head>
      <!-- yada yada yada -->
    </head>
    <body>
      <p id='p1'>Line 1</p>
      <script type='text/javascript'>
        document.write("<p>p1 is null? " + (document.getElementById('p1') == null ? "yes" : "no") + "</p>");
        document.write("<p>p2 is null? " + (document.getElementById('p2') == null ? "yes" : "no") + "</p>");
      </script>
      <p id='p2'>Line two</p>
    </body>
    </html>

您看到的输出是:

Line 1
p1 is null? false
p2 is null? true
Line 2

因为在脚本运行时p1存在,而p2不存在。

查看谷歌开发人员提供的链接以获取更多信息。

您正在正确地将var svg设置为svg:

var svg = d3.select("body").append("svg")

但是你把它重新指定为body元素

var svg = d3.select('body');

删除var svg = d3.select('body');,你应该能够添加到你的svg,只要找到:svg.append("rect")

请记住,当您执行:var svg = d3.select("body").append("svg")时,var svg保存您附加到body的svg元素,而不是body本身

的被害者。这是一个jsfiddle显示的最小代码来渲染svgrect,如果你的代码仍然不能工作,那么它可能与你如何调用代码和在哪里/何时调用代码有关。