在RaphaelJS中绘制连接线

时间:2010-08-27 08:06:26

标签: javascript svg line raphael

我将如何在Raphael中绘制一条连接线,其中mousedown启动线的起点,鼠标移动终点而不移动起点,鼠标按原样离开它?

2 个答案:

答案 0 :(得分:22)

查看http://www.warfuric.com/taitems/RaphaelJS/arrow_test.htm的来源。

这可能会让你开始。

修改

我做了一个快速的例子,它将为您提供一个良好的开端(但仍需要一些工作:参数验证,添加注释等)。

注意:您仍需要调整raphael.js的路径

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<meta http-equiv="edit-Type" edit="text/html; charset=utf-8">


<!-- Update the path to raphael js -->
<script type="text/javascript"src="path/to/raphael1.4.js"></script>
<script type='text/javascript'
    src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<style type='text/css'>
svg {
    border: solid 1px #000;
}
</style>

</head>
<body>
<div id="raphaelContainer"></div>
<script type='text/javascript'> 
    //<![CDATA[ 

function Line(startX, startY, endX, endY, raphael) {
    var start = {
        x: startX,
        y: startY
    };
    var end = {
        x: endX,
        y: endY
    };
    var getPath = function() {
        return "M" + start.x + " " + start.y + " L" + end.x + " " + end.y;
    };
    var redraw = function() {
        node.attr("path", getPath());
    }

    var node = raphael.path(getPath());
    return {
        updateStart: function(x, y) {
            start.x = x;
            start.y = y;
            redraw();
            return this;
        },
        updateEnd: function(x, y) {
            end.x = x;
            end.y = y;
            redraw();
            return this;
        }
    };
};



$(document).ready(function() {
    var paper = Raphael("raphaelContainer",0, 0, 300, 400);
    $("#raphaelContainer").mousedown(

    function(e) {
        x = e.offsetX;
        y = e.offsetY;
        line = Line(x, y, x, y, paper);
        $("#raphaelContainer").bind('mousemove', function(e) {
            x = e.offsetX;
            y = e.offsetY;
            line.updateEnd(x, y);
        });
    });

    $("#raphaelContainer").mouseup(

    function(e) {
        $("#raphaelContainer").unbind('mousemove');
    });
});
    //]]> 
    </script>
</body>
</html>

参见示例:http://jsfiddle.net/rRtAq/9358/

答案 1 :(得分:9)

您可以将自己的line方法添加到Paper类...

Raphael.fn.line = function(startX, startY, endX, endY){
    return this.path('M' + startX + ' ' + startY + ' L' + endX + ' ' + endY);
};

...稍后您可以使用它,就像Paper类(圆圈等)中的任何其他已知方法一样:

var paper = Raphael('myPaper', 0, 0, 300, 400);
paper.line(50, 50, 250, 350);
paper.line(250, 50, 50, 150).attr({stroke:'red'});

(见http://jsfiddle.net/f4hSM/