Snap.svg draggin Path Element - javascript

I'm trying to drag a Path element with Snap.SVG, I'm using drag method
when method is called without parmeteres it seems to work ok, but when I add the listeners I cant make it work, It's looks like is not posible to change to position x,y attributes
start = () ->
console.log("Stop move, ox=" + this.ox + ", oy=" + this.oy);
moveFunc = (dx, dy, posx, posy) ->
this.attr( { cx: posx , cy: posy } )
stop = () ->
console.log("Stop move, ox=" + this.ox + ", oy=" + this.oy);
p.drag( moveFunc, start, stop)
The previos code doesnt work with path element, but it does with circle.
Next code can move it but when drag it again loose the last position
moveFunc = (dx, dy, posx, posy) ->
this.transform( "translate("+dx+", "+dy+")")
So guessing, last method do the trick for translate it, but it doesnt really change the position.

To move a path, you will need to transform it, try this format.
this.transform('t' + dx + ',' + dy );
However, as mentioned it won't keep the last position. For that you need to store the transform on the mouse down....
var move = function(dx,dy) {
this.attr({
transform: this.data('origTransform') + (this.data('origTransform') ? "T" : "t") + [dx, dy]
});
}
var start = function() {
this.data('origTransform', this.transform().local );
}
example

Related

Raphael.js attr function sets wrong value

I'm implementing a drag and drop system with Raphael.js. For this, i'm storing the original x and y position on mousedown, and if there is a collision on mouseup, I want to reset the position to the original one. Here's the bit of code that does the resetting ("this" refers to the raphael object here):
var transformString = "t" + this.original_x + "," + this.original_y;
this.attr("transform", transformString);
What's weird is that after setting the attribute, the transform string changes by a couple pixels. I debugged this with:
var transformString = "t" + this.original_x + "," + this.original_y;
this.attr("transform", transformString);
console.log("transformString: " + transformString);
console.log("transformAttrib: " + this.attr("transform"));
AFAIK, both logged values should be equal in any case. But they are sometimes off by as much as 20px. Does anyone know what's going on here?
E: Here is a simplified version, without the collision testing, which still reproduces the bug: http://jsfiddle.net/6ozsfdaf
I'm not sure why this is happening. I tried even capturing the co-ordinates before onstart using onmousedown event, even that didnt work. Also different methods provided by Raphael to get the co-ordinates using getBBox(), accessing x and y directly, didnt help.
So what I thought is, we should Maintain and Track the coordinates manually. So I have used your original_x and original_y variables which captures the position of the <path> after you create and set with some transform value. Below is the code of the same
Here is the working fiddle.
this.raph = R.path(svgPath).attr({
stroke: "hsb(0, 1, 1)",
fill: "#fff",
opacity: 1.0,
cx: 100,
cy: 900
}).transform("t" + x + "," + y);
this.raph.original_x = x;
this.raph.original_y = y;
//comment the lines in start method which captures original_x and original_y
//this.original_x = Raphael.parseTransformString(this.attr("transform"))[0][1];
//this.original_y = Raphael.parseTransformString(this.attr("transform"))[0][2];
More info regarding tracking the co-ordinates:
We will have one more coordinate say updated_x and updated_y, which will be updated in the move method. onFinish/onUp method, we can have the check whether we should update the new position or not. Here, it just asks whether new position should be updated or not and based on our input, it sets the final result.
Check this fiddle:
this.start = function() {
if (this.reference.static) return;
//this.original_x = Raphael.parseTransformString(this.attr("transform"))[0][1];
//this.original_y = Raphael.parseTransformString(this.attr("transform"))[0][2];
this.animate({r: 70, opacity: 0.25}, 500, ">");
this.updated_x = this.original_x;
this.updated_y = this.original_y;
};
this.move = function(dx, dy) {
//var ts = Raphael.parseTransformString(this.attr("transform"));
this.updated_x = this.original_x + dx;
this.updated_y = this.original_y + dy;
//ts[0][1] = this.original_x + dx;
//ts[0][2] = this.original_y + dy;
this.attr({transform: 't' + this.updated_x + ',' + this.updated_y});
};
this.up = function() {
if(confirm("Shall I update the new position??")) {
this.original_x = this.updated_x;
this.original_y = this.updated_y;
}
var transformString = "t" + this.original_x + "," + this.original_y;
this.attr("transform", transformString);
this.attr({fill: "#fff"});
this.animate({r: 50, opacity: 1}, 500, ">");
};
I'm not quite sure why that problem happens yet, but I'm wondering if this may be a better solution anyway. Rather than parsing the strings each time, just store the transform and use that.
I've also switched it to use the transform() method, rather than the attr(transform:..) method. Whilst I think that would normally work, its not quite right logically, as SVG attributes don't take a Raphael transform string, but I assume Raph would intercept that and deal with it (but maybe more error prone).
Its also worth bearing in mind in a transform string that 't' is a relative transform and 'T' is an absolute transform (I don't think thats the issue as there's no preceding transform, but I was wondering if its also related).
this.start = function() {
if (this.reference.static) return;
this.original_t = this.transform();
this.animate({r: 70, opacity: 0.25}, 500, ">");
};
this.move = function(dx, dy) {
this.transform( this.original_t + 't' + dx + ',' + dy);
};
this.up = function() {
this.transform( this.original_t );
console.log("transformString: " + this.original_t);
console.log("transformAttrib: " + this.transform());
this.attr({fill: "#fff"});
this.animate({r: 50, opacity: 1}, 500, ">");
};
jsfiddle
Found an interesting fix: you can avoid the situation if you add an epsilon to both this.original_x and this.original_y. The problem seems to disappear if this.original_x and this.original_y are not exactly the same as the starting coordinates. Check out: http://jsfiddle.net/6ozsfdaf/13/
this.up = function() {
var ts;
this.original_x += 0.0000000001;
this.original_y += 0.0000000001;
var transformString = "t" + this.original_x + "," + this.original_y;
this.attr("transform", transformString);
console.log("transformString: " + transformString);
console.log("transformAttrib: " + this.attr("transform"));
this.attr({fill: "#fff"});
this.animate({r: 50, opacity: 1}, 500, ">");
};
EDIT
Found the problem. In Raphael, Raphael.parseTransformString()'s output is cached and reused. In your move() method, you modify the output of Raphael.parseTransformString(), and Raphael tries to use your modified array when you supply it with the same string. This happens when the first drag() event is registered. You ask it to parse the current place, and then update the output array of arrays with the new location. And then, way later, when this.up() is called, you supply the Raphael.parseTransformString() with the same string. Raphael then uses your modified array of arrays. This is the fixed fiddle: http://jsfiddle.net/6ozsfdaf/16/
And here is the code (use a new array of arrays to transform when moved each time):
this.move = function(dx, dy) {
var ts = [];
ts.push(new Array('t'));
ts[0][1] = this.original_x + dx;
ts[0][2] = this.original_y + dy;
this.attr({transform: ts.toString()});
};

Snap SVG: Dragging group doesn't update elements

JSFiddle here: JSFiddle
When dragging a group of objects, the individual objects' location attributes don't seem to be getting updated. This occurs whether I use the default drag() handler or define my own. Even the group BBox operation doesn't seem to update. Code:
var s = Snap("#svg");
var move = function (dx, dy, posx, posy) {
this.attr({
x: posx,
y: posy
});
//this.transform("t" + dx + "," + dy);
};
var block = s.rect(100, 100, 100, 100);
var circle = s.circle(100, 100, 50);
var group = s.g(block, circle);
//group.drag(move, function () {}, function () {});
group.drag();
//block.drag(move, function () {}, function () {});
//just a way to keep info coming w/o an interminable script
document.addEventListener('mousemove', function (e) {
bbox = block.getBBox();
block_x = block.attr("x");
block_y = block.attr("y");
gbbox = group.getBBox();
console.log("block is at " + block_x + "," + block_y,
" Block Bbbox is at " + bbox.x + "," + bbox.y,
" Group Bbbox is at " + gbbox.x + "," + gbbox.y);
}, false);
If I define only one object (say, a rect) and leave it out of a group, and pass my own "move" function to the call to drag, and include setting the "x" and "y" attributes explicitly, then that works. But if I include the rect in a group, then...I can't figure out how to do it, and I've tried a few ways (see the multiple commented-out lines showing things I've tried). I need to know where the rect sub-group element ends up after the drag, or at least the BBox of the whole group. Neither of these seem to be getting updated -- i.e. the console log I put in shows the same numbers forever, no matter where I move the object(s).
Can anyone help?
JSFiddle here: JSFiddle
I think this is because they are two different things, so they aren't actually interchangable.
The drag handler uses transforms. A transform doesn't affect any other attributes, its just an attribute on an element (in this case the group element).
getBBox will work in its current transform space, note this may be different to the clients (eg if the svg were zoomed in/out). So they are two slightly different methods, that do different things.
Use getBoundingClientRect if you need a bounding box relative to the client window. Use getBBox if you need a bounding box in the elements current coordinate space.
Code is using snap.svg.zpd as well, so zoom is possible. Problem is at onStopMove function. Events are fired when group is moved arround. In group is one circle(this.select('#main-inner-circle')) which does not have predefined location inside group. Im trying to get correct cx and cy of that inner circle after moving group.
self.onMove = function (dx, dy, ev, x, y) {
var clientX, clientY;
var tdx, tdy;
if ((typeof dx == 'object') && (dx.type == 'touchmove')) {
clientX = dx.changedTouches[0].clientX;
clientY = dx.changedTouches[0].clientY;
dx = clientX - this.data('ox');
dy = clientY - this.data('oy');
}
var snapInvMatrix = this.transform().diffMatrix.invert();
snapInvMatrix.e = snapInvMatrix.f = 0;
tdx = snapInvMatrix.x(dx, dy);
tdy = snapInvMatrix.y(dx, dy);
this.transform("t" + [tdx, tdy] + this.data('ot'));
}
self.onStartMove = function (x, y, ev) {
if ((typeof x == 'object') && (x.type == 'touchstart')) {
x.preventDefault();
this.data('ox', x.changedTouches[0].clientX);
this.data('oy', x.changedTouches[0].clientY);
}
this.data('ot', this.transform().local);
if (callbacks.onStartMove) {
callbacks.onStartMove();
}
}
self.onStopMove = function () {
var self = this.select('#main-inner-circle');
this.data('ot', this.transform().local);
//self.data('ot', self.transform().local);
console.log(self.getTransformedBBox());
console.log(this.getBBox());
//console.log($(self.node).offset().left - $(self.node).parent().offset().left);
var bBox = this.getBBox();
//var x = bBox.x + $(self.node).offset().left - $(self.node).parent().offset().left + self.getBBox().width / 2;
//var y = bBox.y + $(self.node).offset().top - $(self.node).parent().offset().top + self.getBBox().height / 2;
model.updateElementCoordinates(index, $(this.node).attr("rel"), { x: self.getTransformedBBox().cx, y: self.getTransformedBBox().cy });
if (callbacks.onStopMove) {
callbacks.onStopMove();
}
}
In order to post this question, I'd created the JSFiddle but left out the crucial snap.svg definitions...
<script src="http://snapsvg.io/assets/js/snap.svg-min.js"></script>
...with that, then indeed the group.getBBox() method actually works. However:
Apparently, using getBBox() is incredibly slow -- much slower than just accessing a "x" attribute of something like I was doing before grouping objects. All I know is that my code slows to a crawl if I use getBBox() (I have a lot of objects on the screen).
Further down in the same post mentioned earier ["Get coordinates of svg group on drag with snap.svg"1 recommended getBoundingClientRect(), which also works fine AND is fast enough! My new, working Fiddle showing all of these methods is here: New JSFiddle.
So, future users: use .node.getBoundingClientRect().

How to constrain a text element within an square with RaphaelJS?

I'm trying to constrain a text element with custom font within a square. I'm having difficulties to let the constrainment take place.
My code looks like this for the move function:
if (this.attr("y") > offsetY || this.attr("x") > offsetX) { // keep dragging & storing original x and y
this.attr({
x : this.ox + dx,
y : this.oy + dy
});
} else {
nowX = Math.min(offsetX, this.ox + dx);
nowY = Math.min(offsetY, this.oy + dy);
nowX = Math.max(0, nowX);
nowY = Math.max(0, nowY);
this.attr({
x : nowX,
y : nowY
});
}
The constrainment never takes place. However, if I use two squares with this code, it works. What am I overlooking here?
Thanks for your answers :)
If you used the default text-anchor value of 'middle' when you called paper.text(), the x and y attrs will return the coordinates of the center of the text span -- not its upper left corner, as it would with a rect.
Rather than using the x and y attributes, you should get your coordinates via element.getBBox(), and then use the x and y from the resulting object. That should enable your existing logic to work unimpeded.

Strange behaviour of GestureEvent.rotation on iOS webkit

I am using javascript Gesture events to detect multitouch pan/scale/rotation applied to an element in a HTML document.
Visit this URL with an iPad:
http://www.merkwelt.com/people/stan/rotate_test/
You can touch the element with two finger and rotate it, but sometimes the rotation property goes go astray and my element flips around many full rotations.
Here is part of my code, I am really only taking the value directly from the event object:
...bind("gesturechange",function(e){
e.preventDefault();
curX = e.originalEvent.pageX - startX;
curY = e.originalEvent.pageY - startY;
node.style.webkitTransform = "rotate(" + (e.originalEvent.rotation) + "deg)" +
" scale(" + e.originalEvent.scale + ") translate3D(" + curX + "px, " + curY + "px, 0px)";
}...
What happens is that the value gets either 360 degrees added or subtracted, so I could monitor the value and react to sudden large changes, but this feels like a last resort.
Am I missing something obvious?
I found a solution.
In order to avoid sudden changes in the rotation that don't reflect real finger moves you need to test for that. I do that testing if the rotation changed more then 300 degrees in either direction, if it does then you need to add or subtract 360 depending on the direction. Not really intuitive, but it works.
Fixed page is here:
http://www.merkwelt.com/people/stan/rotate_test/index2.html
Here is the code
<script type="text/javascript">
var node;
var node_rotation=0;
var node_last_rotation=0;
$('.frame').bind("gesturestart",function(e){
e.preventDefault();
node=e.currentTarget;
startX=e.originalEvent.pageX;
startY=e.originalEvent.pageY;
node_rotation=e.originalEvent.rotation;
node_last_rotation=node_rotation;
}).bind("gesturechange",function(e){
e.preventDefault();
//whats the difference to the last given rotation?
var diff=(e.originalEvent.rotation-node_last_rotation)%360;
//test for the outliers and correct if needed
if( diff<-300)
{
diff+=360;
}
else if(diff>300)
{
diff-=360;
}
node_rotation+=diff;
node_last_rotation=e.originalEvent.rotation;
node.style.webkitTransform = "rotate(" + (node_rotation) + "deg)" +
" scale(" + (e.originalEvent.scale) +
") translate3D(" + (e.originalEvent.pageX - startX) + "px, " + (e.originalEvent.pageY - startY) + "px, 0px)";
}).bind("gestureend",function(e){
e.preventDefault();
});
</script>

SVG dragging for group

I am trying to achieve group and individual dragging inside the group. In the group there are 3 circles. Blue and grey circles has to drag individually (by onmousedown), and orange one is for group moving (by onclick).
The problem is that after dragging whole group, but you have to try at http://www.atarado.com/stackOF/drag-with%20problems.svg and see code.
Any help would be appreciate. Thanks.
I think I've fixed your problem: https://codepen.io/petercollingridge/full/djBjKm/
The issue was that the single dragging was altering the circle's cx and cy attributes, but the group drag was effecting the transformation of the whole group. I've simplified things so it all works using transformations and you only need a single set of functions for both:
function startMove(evt, moveType){
x1 = evt.clientX;
y1 = evt.clientY;
document.documentElement.setAttribute("onmousemove","moveIt(evt)")
if (moveType == 'single'){
C = evt.target;
}
else {
C = evt.target.parentNode;
}
}
function moveIt(evt){
translation = C.getAttributeNS(null, "transform").slice(10,-1).split(' ');
sx = parseInt(translation[0]);
sy = parseInt(translation[1]);
C.setAttributeNS(null, "transform", "translate(" + (sx + evt.clientX - x1) + " " + (sy + evt.clientY - y1) + ")");
x1 = evt.clientX;
y1 = evt.clientY;
}
function endMove(){
document.documentElement.setAttributeNS(null, "onmousemove",null)
}
Now you call startMove(evt, 'single') to move an single object, or startMove(evt, 'group') to move the group it belongs to.

Categories