无法向svg追加形状
Unable to append shape to svg
它在元素(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显示的最小代码来渲染svg
和rect
,如果你的代码仍然不能工作,那么它可能与你如何调用代码和在哪里/何时调用代码有关。
相关文章:
- 表追加而不附加最后一个元素
- D3在一个调用中绘制不同的SVG形状,没有可见性
- 如何使用javascript从主svg对象动态创建svg视图框
- 如何更改<svg>标记为<img>用js标记
- 锚点元素不't使用svg时,请打开EDGE上的href
- 带有填充属性的SVG矩形显示在包含元素的上方插入框阴影
- 使用onclick绘制SVG路径
- SVG/JavaScript:尝试选择和更改多边形点
- 顺时针旋转Svg元件
- 禁用SVG拖动
- 在select元素中显示highchart dashstyle(svg)
- 在D3.js中,有没有任何方法可以将x和y方向上的滚动事件绑定到平移svg
- 缩放Raphael/SVG容器以适应所有内容
- JavaScript-动态SVG-onload属性-未触发事件
- 设置动画时,SVG/Raphael大圆圈会变形
- 如何在jquery中停止在更改时追加值
- 将复杂的 SVG 元素追加到选区
- 无法向svg追加形状
- 不能追加到SVG,即使在使用命名空间之后
- 从D3文件追加svg