使用Raphael JS拖动,放下和塑造旋转

Dan*_*Dan 4 drag-and-drop rotation raphael

我正在使用RaphaelJS 2.0在div中创建多个形状.每个形状都需要能够独立地在div的范围内拖放.双击形状后,该形状需要旋转90度.然后可以拖放它并再次旋转.

我已经在fiddler上加载了一些代码:http://jsfiddle.net/QRZMS/.它基本上是这样的:

    window.onload = function () {

        var angle = 0;

        var R = Raphael("paper", "100%", "100%"),
            shape1 = R.rect(100, 100, 100, 50).attr({ fill: "red", stroke: "none" }),
            shape2 = R.rect(200, 200, 100, 50).attr({ fill: "green", stroke: "none" }),
            shape3 = R.rect(300, 300, 100, 50).attr({ fill: "blue", stroke: "none" }),
            shape4 = R.rect(400, 400, 100, 50).attr({ fill: "black", stroke: "none" });
        var start = function () {
            this.ox = this.attr("x");
            this.oy = this.attr("y");
        },
        move = function (dx, dy) {
            this.attr({ x: this.ox + dx, y: this.oy + dy });
        },
        up = function () {

        };
        R.set(shape1, shape2, shape3, shape4).drag(move, start, up).dblclick(function(){
            angle -= 90;
            shape1.stop().animate({ transform: "r" + angle }, 1000, "<>");
        });


    }
Run Code Online (Sandbox Code Playgroud)

拖放工作正常,其中一个形状在双击时旋转.但是,有两个问题/问题:

  1. 如何自动将旋转附加到每个形状上,而无需将每个项目参考硬编码到旋转方法中?即我只想绘制一次形状,然后让它们全部自动暴露于相同的行为,这样它们每个都可以独立地拖放/旋转,而不必将该行为明确地应用于每个形状.

  2. 旋转形状后,它不再正确拖动 - 就好像拖动鼠标移动与形状的原始方向相关,而不是在旋转形状时更新.我怎样才能让它正常工作,以便可以多次拖动和旋转形状,Seamlessley?

非常感谢任何指针!

ama*_*dan 13

我曾多次尝试过围绕新的变换引擎,但无济于事.所以,我已经回到了第一原则.

在尝试计算出不同变换的影响后,我终于设法正确地拖放了经历了几次变换的对象 - t,T,... t,... T,r,R等......

所以,这是解决方案的关键所在

var ox = 0;
var oy = 0;

function drag_start(e) 
{
};


function drag_move(dx, dy, posx, posy) 
{


   r1.attr({fill: "#fa0"});

   //
   // Here's the interesting part, apply an absolute transform 
   // with the dx,dy coordinates minus the previous value for dx and dy
   //
   r1.attr({
    transform: "...T" + (dx - ox) + "," + (dy - oy)
   });

   //
   // store the previous versions of dx,dy for use in the next move call.
   //
   ox = dx;
   oy = dy;
}


function drag_up(e) 
{
   // nothing here
}
Run Code Online (Sandbox Code Playgroud)

而已.愚蠢的简单,我确信已经发生了大量的人,但也许有人可能会觉得它很有用.

这是你玩的小提琴.

...... 是初始问题的有效解决方案.

  • 丹,你必须考虑拉斐尔图书馆正在努力做什么.它将浏览器的SVG(和VML)功能暴露给javascript.因此,它所做的很多事情都是直接暴露底层SVG元素.这正是变革的一部分.如果您正在寻找有关它们如何工作的信息,特别是矩阵变换,您需要谷歌进行"SVG矩阵变换"而不是"拉斐尔矩阵变换".试试http://commons.oreilly.com/wiki/index.php/SVG_Essentials/Matrix_Algebra或http://www.mecxpert.de/svg/transform.html (2认同)