svg的路径功能没有响应

时间:2014-10-20 14:36:49

标签: javascript jquery svg

我一直在尝试实现这个代码来制作一种图形,用户点击画布创建一个节点,然后再次点击任意两个节点,在它们之间绘制一条边,也可以输入与该边缘相关的权重。我不明白为什么路径功能没有响应。 可能语句中可能存在语法错误

pathE1.setAttribute(“d”,“M coord1,coord2 L coord3,coord4”);

然后我无法弄清楚什么是正确的方法。我的代码是:

<!DOCTYPE html>
<html>
<svg id="canvas" height="1260" width="1260">
</svg>
<script src="jquery-1.11.1.min.js">

</script>
<script>
    var check;
var circles = [];

$(document).ready(function() {
    $("#canvas").bind("mousedown", function(e) {
        var coords = getCoords(e);

        var result = inCircle(coords.x, coords.y);

        if (typeof result === "number") {

            check = result + 1;

        } else {
            draw(coords.x, coords.y);
        }

    });
    $("#canvas").bind("mouseup", function(e) {
        if (!check) {
            console.log('hey');
            return;
        }
        var coords = getCoords(e);
        var result = inCircle(coords.x, coords.y);

        console.log(result);
        if (typeof result === "number") {
            //alert('node up');
            drawConnection(check - 1, result);
        }
        check = 0;

    });




    function getCoords(e) {
        var x = e.clientX;
        var y = e.clientY;
        //alert('x:' +x+ ' y:' +y);
        return {
            x: x,
            y: y
        };
    }

    function inCircle(x, y) {

        for (var i = 0; i < circles.length; i++) {
            if (distance(x, y, circles[i].x, circles[i].y) <= 20) {
                return i;
            }
        }
    }

    function draw(x, y) {
        circles.push({
            x: x,
            y: y
        });

        var circle1 = document.createElementNS("http://www.w3.org/2000/svg", "circle");
        circle1.setAttribute("cx", x);
        circle1.setAttribute("cy", y);
        circle1.setAttribute("r", 20);
        circle1.style.fill = 'blue';
        circle1.style.stroke = 'blue';
        circle1.style.strokeWidth = '5';
        $('#canvas').append(circle1);
    }

});


function distance(x, y, cx, cy) {
    return Math.sqrt((cx - x) * (cx - x) + (y - cy) * (y - cy));
}

function drawConnection(circ1, circ2) {
    var dist = prompt("enter weight");
    var coord1 = circles[circ1].x,
        coord2 = circles[circ1].y,
        coord3 = circles[circ2].x,
        coord4 = circles[circ2].y;
    var pathE1 = document.createElementNS("http://www.w3.org/2000/svg", "path");
    pathE1.setAttribute("d", "M  coord1 , coord2  L  coord3 , coord4");

    pathE1.style.stroke = 'red';
    pathE1.style.strokeWidth = '5';

    $('#canvas').append(pathE1);
}
</script>

1 个答案:

答案 0 :(得分:0)

pathE1.setAttribute("d", "M  coord1 , coord2  L  coord3 , coord4");

只是创建一个文本coord1作为x坐标而不是coord1的的路径。你想要的是

pathE1.setAttribute("d", "M " + coord1 + ", " + coord2 + " L " + coord3 + ", " + coord4);