Snapsvg - 通过拖动键和箭头键移动元素

时间:2013-12-25 16:49:24

标签: javascript svg

如何在snapsvg中使用箭头键使元素可拖动和移动?目前它无法正常工作。它有时会跳回原点。这是一个例子: http://codepen.io/anon/pen/tFGng

var s = Snap("#svg");

var orig = {
    x: 0,
    y: 0
};

var block = s.rect(0, 0, 6, 6);
block.attr({
    fill: "rgb(0, 0, 0)"
});

block.drag(


function (dx, dy, x, y, e) {
    var xSnap = Snap.snapTo(10, orig.x + dx + 3, 10);
    var ySnap = Snap.snapTo(10, orig.y + dy + 3, 10);

    this.attr({
        x: xSnap,
        y: ySnap
    });
},

function (x, y, e) {
    orig.x = e.toElement.x.baseVal.value;
    orig.y = e.toElement.y.baseVal.value;
    //origTransform = this.transform().local;
},

function (e) {
    console.log('on end');

    orig.x = e.toElement.x.baseVal.value;
    orig.y = e.toElement.y.baseVal.value;
}

);


$(document).on('keydown', function(event){
    var key = event.which;

    if( key === 37 || key === 38 || key === 39 || key === 40 ){
        event.preventDefault();
    }


    if( event.which === 37){
        //left
        orig.x -= 10;
    }

    if( event.which === 38){

        //up
        orig.y -= 10;

    }

    if( event.which === 39){
        //right

        orig.x += 10;
    }

    if( event.which === 40){
        //down

        orig.y += 10;
    }

    block.attr({
        x: orig.x,
        y: orig.y
    });

});

0 个答案:

没有答案