0

我在 SVG 中有使用键盘移动的对象。

var svg = $('svg');
var avatar = svg.find('#avatar');
var left, top, right, bottom;
$(document).keydown(function(e) {
    var svg = avatar[0].ownerSVGElement;
    var matrix = avatar[0].getCTM();
    if (e.which === 37 || left) { //left
        matrix.translate(-1, 0);
        e.preventDefault();
        left = true;
    }
    if (e.which === 38 || top) { // top
        matrix.translate(0, -1);
        e.preventDefault();
        top = true;
    }
    if (e.which === 39 || right) { // right
        matrix.translate(1, 0);
        e.preventDefault();
        right = true;
    }
    if (e.which === 40 || bottom) { // bottom
        matrix.translate(0, 1);
        e.preventDefault();
        bottom = true;
    }
    avatar.attr('transform', matrix.asString());
}).keyup(function(e) {
    if (e.which === 37) {
        left = false;
    } else if (e.which === 38) {
        top = false;
    } else if (e.which === 39) {
        right = false;
    } else if (e.which === 40) {
        bottom = false;
    }
});

如何在 SVG 中添加轨迹(显示移动头像的路径的线)?当我移动我的头像时,它需要可见。如果它不仅可以是一条线,而且可以是一个图案,那就太好了。

4

1 回答 1

0

我找到了一种方法,我可以只放置一条路径并在 keydown 上添加线条(将其附加到 d 属性),以简化我每 5 次移动放置一条线的路径。

var trace;
(function() {
    var start = $('#start')[0].getBBox();
    var x = start.x+(start.width/2);
    var y = start.y+(start.height/2);
    trace = $('<path/>').attr({
        id: 'trace',
        stroke: '#000',
        fill: 'none',
        d: 'M ' + x + ' ' + y
    }).appendTo(svg);
    // in normal case trace path need to be added before svg is inserted to the DOM
    // in my case I modify jquery library to use document.createElementNS instead of
    // document.createElement
    avatar.setPosition(x, y);
})();

var i = 0;
$(document).keydown(function(e) {

   ...
   if (++i % 5 === 0) {
        var avatar_size = avatar.size(); // size if jquery plugin that return width and height using BBox
        var x = matrix.matrix[0][2];
        var y = matrix.matrix[1][2];
        trace.attr('d', trace.attr('d') + ', ' + x + ' ' + y);
    }
});
于 2013-06-19T12:43:31.253 回答