我尝试应用一些转换作为对一组元素的用户输入的反应,我很确定我做错了:
var SVG_WIDTH = window.innerWidth,
SVG_HEIGHT = window.innerHeight,
SVG_CENTER_X = Math.floor(SVG_WIDTH / 2),
SVG_CENTER_Y = Math.floor(SVG_HEIGHT / 2),
s = Snap(SVG_WIDTH, SVG_HEIGHT),
obj = new myObj(SVG_CENTER_X, SVG_CENTER_Y);
obj.drawIt();
function myObj( x, y ) {
var that = this;
this.x = x;
this.y = y;
this.is_scaled = false;
this.angle = 0;
this.g = s.group();
this.drawIt = function() {
var a = s.rect(this.x, this.y, 50, 50, 0, 0).attr({'fill':'#E82941'});
a.appendTo(this.g);
};
this.moveIt = function( dx, dy ) {
var relative_dx = dx,
relative_dy = dy;
switch ( that.angle ) {
case 0: {
break;
}
case 90: {
relative_dx = dy;
relative_dy = -dx;
break;
}
case 180: {
relative_dx = -dx;
relative_dy = -dy;
break;
}
case 270: {
relative_dx = -dy;
relative_dy = dx;
break;
}
}
var old_matrix = that.g.transform().localMatrix,
new_matrix = old_matrix.translate(relative_dx, relative_dy),
new_string = new_matrix.toTransformString();
that.g.animate({'transform':new_string}, 200, mina.linear);
};
this.rotateIt = function( angle ) {
var old_matrix = that.g.transform().localMatrix,
new_matrix = old_matrix.rotate(angle, that.x + 25, that.y + 25),
new_string = new_matrix.toTransformString();
that.g.animate({'transform':new_string}, 200, mina.linear);
that.angle = Math.abs((that.angle + angle) % 360);
};
this.scaleIt = function() {
var factor = 2;
if (that.is_scaled) {
factor = 0.5;
that.is_scaled = false;
} else {
that.is_scaled = true;
}
var old_matrix = that.g.transform().localMatrix,
new_matrix = old_matrix.scale(factor, factor, that.x + 25, that.y +25),
new_string = new_matrix.toTransformString();
that.g.animate({'transform':new_string}, 200, mina.linear);
};
}
document.onkeypress = function ( e ) {
switch ( e.charCode ) {
case 97: { // A
obj.moveIt(-50, 0);
break;
}
case 100: { // D
obj.moveIt(50, 0);
break;
}
case 114: { // R
obj.rotateIt(90);
break;
}
case 115: { // S
obj.moveIt(0, 50);
break;
}
case 119: { // W
obj.moveIt(0, -50);
break;
}
case 122: { // Z
obj.scaleIt(2);
break;
}
}
};
这是一个codepen:http://codepen.io/GeMir/pen/GJMPQP?editors=001
WASD-Translations工作得很好。 缩放也很有效(以对象中心为原点放大/缩小)。 旋转工作几乎很好,但只有在一些缩放后(???)。
矩形应绕其中心顺时针旋转,不应该跳过"跳跃"从270度旋转到360度(现在逆时针旋转到0度)。