0

I'm learning Javascript / Raphael and got stuck in what should be something really simple to solve. I need to move and rotate a number of figures with the mouse, but when I rotate them (with doubleclick) as:

rect1.dblclick(function() {
    this.rotate('90');
});

the reference points I am using to keep track of the mouse also get rotated. In Processing I would use pushMatrix() and popMatrix(), but I can't find something similar for Raphael nor any simple examples using save() and restore() canvas (...not sure if they can be used here either).

Here is a working example.

var canvas = document.getElementById("the_canvas");
var paper = Raphael(canvas, '500', '500');

var rect1 = paper.rect(380,10,100,50).attr({fill: '#ddd', 'stroke': 'none', opacity: '0.8'});

var startX, startY;
function onstart() {
    startX = this.attr('x');
    startY = this.attr('y');
}
function onend() {
}

function onmove(dx, dy) {
    this.attr({
        x: startX + dx,
        y: startY + dy
    }); 
}
rect1.drag(onmove, onstart, onend);

//// ... problem here
rect1.dblclick(function() {
    this.rotate('90');
});

Cheers,

vabm
  • 285
  • 7
  • 16
  • Its not that simple as you have rotated the coordinate space, so you need to account for that. I would be tempted to not drag via x,y but via a translate transformation. There's a few examples on SO, eg this may help you get part of the way http://stackoverflow.com/questions/4224359/making-paths-and-images-dragable-in-raphael-js – Ian Jan 09 '15 at 14:49
  • Thanks. Why use transform? any advantages? – vabm Jan 10 '15 at 13:41
  • It does partly depend on overall aims. Advantages of transforms are that it will work for any element, a circle for example doesn't have an x,y it has cx, cy, so straight away dragging a circle won't work. If you were to move from Raphael to Snap, you will find that you may want to drag a group which doesn't have xy, only way is transformations. Then you can also combine matrices fairly easily. If its just a case of a quick drag on a basic rect, no need. But if you want to design something that will work for more cases longer term, I suspect transformations will be the way to go. – Ian Jan 10 '15 at 13:55

0 Answers0