我现在有这个工作。
根据我的经验,不要使用 jquery.svg,在不了解其他插件的情况下解决它可能是一种压力,但我发现它比它的价值更麻烦,并导致了兼容性问题。
可以使用 HTML5 画布和excanvas compatibility script 和a great html5 walkthrough 来解决,但是由于 HTML5 画布的工作原理,如果需要删除线条,则需要销毁画布上的所有 linse 并重新绘制或者它的位置需要更新。
我在它们之间画线的元素位于表示关系的父元素内。子元素代表开始和结束,所以我可以通过使用例如获取父母的集合来重绘所有这些关系。 $('.relationshipClass') 并询问集合元素的子元素以获取线的点。
要使用此代码,您必须想出一种方法来轻松获取可用于重绘的线点。
标记:
很好很简单,一个 html <div> 用于保存在两者之间绘制的任何元素(很可能是 JQuery UI 可拖动元素),一个 <canvas> 将位于同一位置
<div id="divCanvasId" class="divCanvasClass"></div>
<canvas id="html5CanvasId"></canvas>
CSS:
不要使用 CSS 控制 <canvas> 元素的宽度,请参阅 Question on Canvas streching。将<canvas> 放置在与<div> 相同的位置并在其后面(带有z-index),这将显示<div> 后面的行并防止<canvas> 阻止任何拖放交互<div> 的孩子们。
canvas
{
background-color: #FFFFFF;
position: absolute;
z-index: -10;
/* control height and width in code to prevent stretching */
}
Javascript 方法:
创建实用方法:示例代码位于 JQuery plugin 内,其中包含:
- 重置画布的辅助函数(更改宽度将删除所有内容
- 在两个元素之间画线的辅助函数
- 一个在所有需要的元素之间画线的函数
添加新线或调整线的位置时,会破坏现有线并绘制所有线。
您可以将下面的代码放入常规函数中或作为插件保留。
Javascript 代码:
注:匿名化后未测试。
$(document).ready(function () {
$.fn.yourExt = {
_readjustHTML5CanvasHeight: function () {
//clear the canvas by readjusting the width/height
var html5Canvas = $('#html5CanvasId');
var canvasDiv = $('#divCanvasId');
if (html5Canvas.length > 0) {
html5Canvas[0].width = canvasDiv.width();
html5Canvas[0].height = canvasDiv.height();
}
}
,
//uses HTML5 <canvas> to draw line representing relationship
//IE support with excanvas.js
_drawLineBetweenElements: function (sourceElement, targetElement) {
//draw from/to the centre, not the top left
//don't use .position()
//that will be relative to the parent div and not the page
var sourceX = sourceElement.offset().left + sourceElement.width() / 2;
var sourceY = sourceElement.offset().top + sourceElement.height() / 2;
var targetX = targetElement.offset().left + sourceElement.width() / 2;
var targetY = targetElement.offset().top + sourceElement.height() / 2;
var canvas = $('#html5CanvasId');
//you need to draw relative to the canvas not the page
var canvasOffsetX = canvas.offset().left;
var canvasOffsetY = canvas.offset().top;
var context = canvas[0].getContext('2d');
//draw line
context.beginPath();
context.moveTo(sourceX - canvasOffsetX, sourceY - canvasOffsetY);
context.lineTo(targetX - canvasOffsetX, targetY - canvasOffsetY);
context.closePath();
//ink line
context.lineWidth = 2;
context.strokeStyle = "#000"; //black
context.stroke();
}
,
drawLines: function () {
//reset the canvas
$().yourExt._readjustHTML5CanvasHeight();
var elementsToDrawLinesBetween;
//you must create an object that holds the start and end of the line
//and populate a collection of them to iterate through
elementsToDrawLinesBetween.each(function (i, startEndPair) {
//dot notation used, you will probably have a different method
//to access these elements
var start = startEndPair.start;
var end = startEndPair.end;
$().yourExt._drawLineBetweenElements(start, end);
});
}
您现在可以从事件处理程序(例如JQuery UI's drag event)调用这些函数来绘制线条。