![](/img/trans.png)
[英]draw an arrow or line between two divs using canvas, SVG and js
[英]Draw an arrow between two divs
我正在寻找我希望已经解决的问题的解决方案。 但我只看到了具有很多功能但没有简单解决方案的大型项目。
其实我需要得到这样的东西:
因此,要在包含一些正方形(div)的 div 上绘制箭头
<div id="container">
<div class="white_field"></div>
<div id="1" class="black_field">
<br style="clear:both;">
<div id="2" class="black_field">
<div class="white_field"></div>
<br style="clear:both;">
<div id="3" class="black_field">
<div class="white_field"></div>
</div>
我查看了 canvas 方向,但偶然发现 canvas 在我的 div 后面不可见(也许一些 z-index 应该有帮助)但仍然很奇怪,我找不到一些现成的解决方案来解决我似乎经常出现的问题. (解释网站上的一些东西箭头几乎是必须的)
您可能会考虑使用 SVG。
特别是,您可以使用带有箭头路径形状的标记端的线。
确保设置 orient=auto 以便箭头将旋转以匹配线的斜率。
由于SVG是一个DOM元素,你可以在javascript中控制行的开始/结束位置。
这是代码和小提琴: http : //jsfiddle.net/m1erickson/9aCsJ/
<svg width="300" height="100">
<defs>
<marker id="arrow" markerWidth="13" markerHeight="13" refx="2" refy="6" orient="auto">
<path d="M2,2 L2,11 L10,6 L2,2" style="fill:red;" />
</marker>
</defs>
<path d="M30,150 L100,50"
style="stroke:red; stroke-width: 1.25px; fill: none;
marker-end: url(#arrow);"
/>
</svg>
我不知道是否有人再看这个线程,但这是我使用的解决方案,它与@markE 的答案仅略有不同,因为此答案可以更轻松地准确指定该行需要开始和停止的位置。
<head>
<style>
.arrow{
stroke:rgb(0,0,0);
stroke-width:2;
marker-end:url(#markerArrow)
}
</style>
</head>
<body>
<svg height="210" width="500">
<defs>
<marker id="markerArrow" markerWidth="13" markerHeight="13" refX="2" refY="6"
orient="auto">
<path d="M2,2 L2,11 L10,6 L2,2" style="fill: #000000;" />
</marker>
</defs>
<line x1="0" y1="0" x2="200" y2="100" class="arrow" />
</svg>
</body>
您所要做的就是更改线的 x 和 y 坐标! 我在我的 React 应用程序中使用了这个答案,并且效果很好。 这是小提琴。
.arrow { stroke: rgb(0, 0, 0); stroke-width: 2; marker-end: url(#markerArrow) }
<svg height="210" width="500"> <defs> <marker id="markerArrow" markerWidth="13" markerHeight="13" refX="2" refY="6" orient="auto"> <path d="M2,2 L2,11 L10,6 L2,2" style="fill: #000000;" /> </marker> </defs> <line x1="0" y1="0" x2="200" y2="100" class="arrow" /> </svg>
使用库,如JSPlumb : https : //jsplumbtoolkit.com/
创建箭头相当简单。 请参阅 CSS Tricks 上的此示例。 也许在带有箭头线的容器中使用它可能会做到。
我建议使用这个:
https://www.cssscript.com/connect-elements-directional-arrow/
使用非常简单:)
你可以这样做:
<connection from="#id_1" to="#id_2" color="red" tail></connection>
如何包含它:
您将 .zip 文件解压缩到您的项目文件夹。 要么将 CSS 和 JavaScript 复制到您的项目中,要么在您的项目中添加对这些文件的引用:
<head>
<!-- Your head-codes here -->
<link rel = "stylesheet" type = "text/css" href = "../plugins/domarrow.js-master/domarrow.css"/>
</head>
<body>
<!-- Your body-codes here -->
<script src="../plugins/domarrow.js-master/domarrow.js"></script>
</body>
在我的情况下,文件结构是:
C/MyProject/:.
│
├───css
│ start.css
│
├───html
│ start.html <--- write here
│
├───js
│ start.js
│
└───plugins
│
└───domarrow.js-master
domarrow.css
domarrow.js
这就是为什么我需要相对路径开头的“../”,它的意思是“走出一级”,例如:“../plugins”退出“html”文件夹并进入“plugins”文件夹代替。
根据您的文件布局调整文件路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.