在RaphaelJS中绘制连接线

16

我该如何在Raphael中绘制连接线,使鼠标按下时成为线的起点,鼠标移动时移动线的终点而不移动起点,鼠标松开时保持原样?

2个回答

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/


3
在 Raphael 前面不需要加上 new。 同样,在 Line 前面也不需要加上。 - Dmitry Baranovskiy

10

你可以向 Paper 类中添加自己的 line 方法...

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

...你可以像使用Paper类中的其他已知方法(如circle等)一样,稍后使用它:

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/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接