15 javascript jquery canvas graph
我有n <div> s,每个都有<h1>标题和<ul>项目列表.
我想将它们放在画布上,然后从<div id="x">列表项y到<div id="z"> 绘制线条.我正在使用jQuery UI来实现<div> s draggable.
canvas元素是页面的一部分(文本的一段和一些表单元素在它之前)但是我可以在必要时更改它.
[编辑]
我用图表标记了这个问题,但是让我添加这个链接:Graph_(数学) :-)
我会将div的定位设为绝对,然后将它们设置在您想要的位置.然后用这个函数得到他们的位置:
//Get the absolute position of a DOM object on a page
function findPos(obj) {
var curLeft = curTop = 0;
if (obj.offsetParent) {
do {
curLeft += obj.offsetLeft;
curTop += obj.offsetTop;
} while (obj = obj.offsetParent);
}
return {x:curLeft, y:curTop};
}
Run Code Online (Sandbox Code Playgroud)
当你有他们的位置时,将它加到他们的宽度/高度的一半,你将在页面上有他们的中心位置.现在找到画布的位置,并从先前找到的数字中减去它.如果你在这两个点之间画一条线,它应该链接两个div.如果不清楚,这是我将如何编码它:
var centerX = findPos(document.getElementById('x'));
centerX.x += document.getElementById('x').style.width;
centerX.y += document.getElementById('x').style.height;
var centerZ = findPos(document.getElementById('Z'));
centerZ.x += document.getElementById('z').style.width;
centerZ.y += document.getElementById('z').style.height;
//Now you've got both centers in reference to the page
var canvasPos = findPos(document.getElementById('canvas'));
centerX.x -= canvasPos.x;
centerX.y -= canvasPos.y;
centerZ.x -= canvasPos.x;
centerZ.y -= canvasPos.y;
//Now both points are in reference to the canvas
var ctx = document.getElementById('canvas').getContext('2d');
ctx.beginPath();
ctx.moveTo(centerX.x, centerX.y);
ctx.lineTo(centerZ.x, centerZ.y);
ctx.stroke();
//Now you should have a line between both divs. You should call this code each time the position changes
Run Code Online (Sandbox Code Playgroud)
编辑 顺便说一下,使用findPos函数你还可以设置div相对于画布的初始位置(这里是(30; 40)):
var position = {x: 30, y: 40};
var canvasPos = findPos(document.getElementById('canvas'));
var xPos = canvasPos.x + position.x;
var yPos = canvasPos.y + position.y;
document.getElementById('x').style.left = xPos+"px";
document.getElementById('x').style.top = yPos+"px";
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
24555 次 |
| 最近记录: |