我在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中添加跟踪(显示移动头像的路径的行)?当我移动我的头像时,它需要是可见的。如果它不仅是一条线而且也是一种模式,那将是很好的。
答案 0 :(得分: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);
}
});