我正在使用Raphael库来旋转和拖动图像。我正确拖动它,我有一个按钮,每按一次就能正确旋转90度。但是,当我旋转图像,拖动它然后再次尝试旋转它时,我遇到了问题。
HTML中唯一的元素是用于存放Raphael画布的div和用于旋转图像的按钮。 JavaScript在这里:
var gboard;
var piece;
window.onload = function ()
{
gboard = Raphael("gameboard", 800, 500);
// piece = gboard.rect(100, 100, 50, 50).attr({fill: "#0CF", "fill-opacity": 1, stroke: "none", cursor: "move"});
piece = gboard.image("piece.gif", 100, 100, 50, 50).attr({cursor: "move"});
piece.drag(dragMove, dragStart, dragStop);
var angle = 0;
document.getElementById('btn').onclick = function () {
angle += 90;
var cx = piece.attr('x') + 25;
var cy = piece.attr('y') + 25;
piece.animate({transform: "R" + angle + ", " + cx + ", " + cy + ""}, 500, "<>");
// piece.transform("R90," + cx + "," + cy);
};
}
// Set up the object for dragging
function dragStart()
{
this.ox = this.attr("x");
this.oy = this.attr("y");
}
// Clean up after dragging ends
function dragStop() {}
/**
* Handle the moving of objects when dragging
* Check the current angle to compensate for rotated coordinate system.
*/
function dragMove(dx, dy)
{
var angle = getAngle(this._['deg']);
if (angle == 90)
this.attr({x: this.ox + dy, y: this.oy - dx});
else if (angle == 180)
this.attr({x: this.ox - dx, y: this.oy - dy});
else if (angle == 270)
this.attr({x: this.ox - dy, y: this.oy + dx});
else // angle == 0
this.attr({x: this.ox + dx, y: this.oy + dy});
}
/**
* Get the simplified equivalent angle (0 <= angle <= 360) for the given angle.
*
* @param deg The angle in degrees
* @return The equivalent angle between 0 and 360
*/
function getAngle(deg)
{
if (deg % 360 == 0)
return 0;
else if (deg < 0)
{
while (deg < 0)
deg += 360;
}
else if (deg > 360)
{
while (deg > 360)
deg -= 360;
}
return deg;
}
答案 0 :(得分:3)
我通过在值更改时重新应用所有转换来解决此问题。
答案 1 :(得分:1)
不是使用x / y属性操作位置,而是使用变换操作旋转,而是使用变换工具来处理两者,从而简化项目。
由于我们在翻译中使用大写'T',忽略了同一字符串中的先前翻译命令,因此我们不再需要担心拖动时的当前角度。
var gboard,
piece;
gboard = Raphael("gameboard", 800, 500);
var angle = 0,
x = 100,
y = 100;
//note that this now starts at 0,0 and is immediately translated to 100,100
piece = gboard.image("piece.gif", 0, 0, 50, 50).attr({cursor: "move", transform: "R" + angle + "T" + x + "," + y });
piece.drag(dragMove, dragStart, dragStop);
document.getElementById('btn').onclick = function () {
angle += 90;
piece.animate({transform: "R" + angle + "T" + x + "," + y}, 500, "<>");
};
// Set up the object for dragging
function dragStart()
{
this.ox = x;
this.oy = y;
}
// Clean up after dragging ends
function dragStop() {}
//Since we're using a capital 'T' in the translation, which ignores previous translation commands in the same string, we no longer have to worry about the current angle here
function dragMove(dx, dy) {
x = this.ox + dx;
y = this.oy + dy;
piece.attr({ transform: "R" + angle + "T" + x + "," + y });
}
答案 2 :(得分:0)
好奇;它看起来像旋转实际上改变了x和y值。因此,如果您旋转90度,将框向右移动100像素实际上会将其移动100像素向上,然后将其转换为向右移动。这会抛出cx和cy值,这决定了旋转盒子的点。
要查看我的意思,请旋转一次,然后在检查器中观察X和Y值的同时拖动该框。
我可以看到两种方法来解决它:你可以做数学运算来重新计算每次旋转的“真实”x和y,或者你可以通过附加数据属性(你自己跟踪x和y)是我推荐的)。祝你好运!