I am currently trying to rotate this div toward the mouse pointer, and it hasnt worked. I even tried going to a chat room about it. Currently, It sorta rotates toward the mouse...here is my code so far:
var x = 0;
var y = 0;
document.addEventListener("mousemove", function(event){
x = Number(event.pageX);
y = Number(event.pageY);
}, false);
setInterval(function(){
var boxX = document.getElementById('temp').style.left;
boxX = Number(boxX.substring(0, boxX.length - 1));
var boxX = screen.width * ((boxX)/100);
var boxY = document.getElementById('temp').style.top;
boxY = Number(boxY.substring(0, boxY.length - 1));
var boxY = screen.width * ((boxY)/100);
var slope = [Math.round(x - boxX),Math.round(y - boxY)];
//x,y
var angle = Math.round(Math.atan(slope[1]/slope[0]) *100) ;
document.getElementById('temp').style.transform = "translate(-50%,-50%) rotate(0deg)";
document.getElementById('temp').style.transform = "translate(-50%,-50%) rotate("+angle+"deg)";
}, 500);
Related
Icon moves when I move the mouse, but it doesn't move to the last position when I stop moving.
I used Paper.js for this.
My code:
function setMousePosition(data) {
var yyy;
var deltaX;
for (var i = 0; i < playersData.length; i++) {
var element = playersData[i];
if (element.playerName == data.playerName) {
// element.cursor.position = new Point(data.position[1], data.position[2]);
deltaX = (data.position[1] - element.cursor.position.x) / (100);
yyy = (data .position[2] - element.cursor.position.y) / (100);
var lastx = element.cursor.position.x + deltaX;
var lasty = element.cursor.position.y + yyy;
element.cursor.position = new Point(lastx,lasty);
}
}
}
Icon doesn't move to cursor end position.
//VARIABLES
//Drag Object Size
dragRadius = 100;
//Destination Size
destHeight = 434;
destWidth = 220;
var RosieDrag = new lib.RosieDrag();
//Drag Object Creation
//Placed inside a container to hold both label and shape
var test = new lib.test();
stage.addChild(test);
test.x = 525;
test.y = 1035;
var dragger = new createjs.Container();
dragger.x = 250;
dragger.y = 460;
dragger.addChild(RosieDrag);
dragger.setBounds(100, 100, dragRadius*2, dragRadius*2);
//DragRadius * 2 because 2*r = width of the bounding box
var RosieDrop = new lib.RosieDrop();
var destination = new createjs.Container();
destination.x = 900;
destination.y = 240;
destination.setBounds(950, 350, 100, 100);
destination.addChild(RosieDrop);
//DRAG FUNCTIONALITY =====================
dragger.on("pressmove", function(evt){
evt.currentTarget.x = evt.stageX;
evt.currentTarget.y = evt.stageY;
stage.update(); //much smoother because it refreshes the screen every pixel movement instead of the FPS set on the Ticker
if(intersect(evt.currentTarget, destination)){
evt.currentTarget.alpha=0.2;
}else{
evt.currentTarget.alpha=1;
}
});
//Mouse UP and SNAP====================
dragger.on("pressup", function(evt) {
if(intersect(evt.currentTarget, destination)){
test.gotoAndPlay(5);
dragger.x = destination.x + destWidth/2;
dragger.y = destination.y + destHeight/2;
dragger.alpha = 1;
stage.update(evt);
}
});
//Tests if two objects are intersecting
//Sees if obj1 passes through the first and last line of its
//bounding box in the x and y sectors
//Utilizes globalToLocal to get the x and y of obj1 in relation
//to obj2
//PRE: Must have bounds set for each object
//Post: Returns true or false
function intersect(obj1, obj2){
var objBounds1 = obj1.getBounds().clone();
var objBounds2 = obj2.getBounds().clone();
var pt = obj1.globalToLocal(objBounds2.x, objBounds2.y);
var h1 = -(objBounds1.height / 2 + objBounds2.height);
var h2 = objBounds2.width / 2;
var w1 = -(objBounds1.width / 2 + objBounds2.width);
var w2 = objBounds2.width / 2;
if(pt.x > w2 || pt.x < w1) return false;
if(pt.y > h2 || pt.y < h1) return false;
return true;
}
//Adds the object into stage
stage.addChild(destination, dragger);
stage.mouseMoveOutside = true;
stage.update();
Hi,
I've made a simple drag and drop in a canvas. It works fine but when the canvas resizes to the window it changes the position of the object when it is picked up and also of the drop area (Interestingly it still draws things in the right position and places the object in the right position after it is dropped.
I'm sure I'm missing something simple, here's my code:
I'm stuck using Raphael JS : I want to make a basic animation that draws concentric lines while loading some stuff.
So, I made this function :
function loadingButton(width, height) {
width = width ? width : 240;
height = height ? height : 240;
var loadingButton = Raphael("loading-button", width, height);
var center = 120,
xloc = center,
yloc = center,
R = 120,
imgW = 124,
imgH = 140;
var lines;
var percent = loadingButton.text(center, center, '0');
percent.attr({'font-size': 36, 'fill': '#fff'});
var count = 0;
var interval = setInterval(function(){
if( count <= 100){
var start_x = center+Math.round((center-30)*Math.cos(4*count*Math.PI/200));
var start_y = center+Math.round((center-30)*Math.sin(4*count*Math.PI/200));
var end_x = center+Math.round((center-10)*Math.cos(4*count*Math.PI/200));
var end_y = center+Math.round((center-10)*Math.sin(4*count*Math.PI/200));
lines = loadingButton.path("M"+start_x+" "+start_y+"L"+end_x+" "+end_y).attr({"stroke":"#FFF","stroke-width":"1"});
percent.attr({text: count});
count++;
}
else {
clearInterval(interval);
}
}, 50);
};
With live demo here : http://jsfiddle.net/rfuqjL65/
The thing is, as you can see on the fiddle, the animation is starting on the first quarter (90°), not on the top (0°).
And well, the problem is : I want the animation starts on the top.
Any ideas ?
I can't get your fiddle running, but:
You can add/substract Math.PI/2 to the angle argument (in radians) for Math.cos and Math.sin in your coordinate variables, that should do the trick!
http://jsfiddle.net/rfuqjL65/2/
I change your code. And this worked.
And also
var start_x = center+Math.round((center-30)*Math.sin(4*count*Math.PI/200));
var start_y = center-Math.round((center-30)*Math.cos(4*count*Math.PI/200));
var end_x = center+Math.round((center-10)*Math.sin(4*count*Math.PI/200));
var end_y = center-Math.round((center-10)*Math.cos(4*count*Math.PI/200));
For a project of big "text map" BigPicture, I need to have more than 1000 text inputs.
When you click + drag, you can "pan" the displayed area.
But the performance is very poor (both on Firefox and Chrome) : rendering 1000+ DOM elements is not fast at all.
Of course, another solution with better performance would be : work on a <canvas>, render text as bitmap on it, and each time we want to edit text, let's show a unique DOM <textarea>, that disappears what editing is finished, and text is rendered as bitmap again... It works (I'm currently working in this direction) but it needs much more code in order to provide editing on a canvas.
Question : Is it possible to improve performance for rendering of 1000+ DOM elements on a HTML page, so that I don't need to use <canvas> at all ?
Or will it be impossible to have good performance when panning a page with 1000+ DOM elements ?
Notes :
1) In the demo here I use <span contendteditable="true"> because I want multiline input + autoresize, but the rendering performance is the same with standard <textarea>.*
2) For reference, this is how I create the 1000 text elements.
for (i=0; i < 1000; i++)
{
var blax = (Math.random()-0.5)*3000;
var blay = (Math.random()-0.5)*3000;
var tb = document.createElement('span');
$(tb).data("x", blax / $(window).width());
$(tb).data("y", blay / $(window).height());
$(tb).data("size", 20 * currentzoom);
tb.contentEditable = true;
tb.style.fontFamily = 'arial';
tb.style.fontSize = '20px';
tb.style.position = 'absolute';
tb.style.top = blay + 'px';
tb.style.left = blax + 'px';
tb.innerHTML="newtext";
document.body.appendChild(tb);
}
For something like this you could make use of document fragment, these are DOM nodes that are not part of the actually DOM tree (more info can be found here https://developer.mozilla.org/en-US/docs/Web/API/document.createDocumentFragment), so you can do all your setup on the fragment and then append the fragment which will only be causing the one re flow rather than 1000.
So here is an example -http://jsfiddle.net/leighking2/awzoz7bj/ - a quick check on run time it takes around 60-70ms to run
var currentzoom = 1;
var docFragment = document.createDocumentFragment();
var start = new Date();
for (i=0; i < 1000; i++)
{
var blax = (Math.random()-0.5)*3000;
var blay = (Math.random()-0.5)*3000;
var tb = document.createElement('span');
$(tb).data("x", blax / $(window).width());
$(tb).data("y", blay / $(window).height());
$(tb).data("size", 20 * currentzoom);
tb.contentEditable = true;
tb.style.fontFamily = 'arial';
tb.style.fontSize = '20px';
tb.style.position = 'absolute';
tb.style.top = blay + 'px';
tb.style.left = blax + 'px';
tb.innerHTML="newtext";
docFragment.appendChild(tb);
}
document.body.appendChild(docFragment);
var end = new Date();
console.log(end-start)
compared to the original which took around 645ms to run http://jsfiddle.net/leighking2/896pusex/
UPDATE So for improving the dragging speed again keep the individual edits out of the DOM to avoid the cost of the reflow 1000 times every mouse drag
so here is one way using jquery's detach() method (example http://jsfiddle.net/sf72ubdt/). This will remove the elements from the DOM but give them to you with all their properties so you can manipulate them and reinsert them later on
redraw = function(resize) {
//detach spans
var spans = $("span").detach();
//now loop other them, because they are no longer attached to the DOM any changes are
//not going to cause a reflow of the page
$(spans).each(function(index) {
var newx = Math.floor(($(this).data("x") - currentx) / currentzoom * $(window).width());
var newy = Math.floor(($(this).data("y") - currenty) / currentzoom * $(window).height());
if (resize) {
displaysize = Math.floor($(this).data("size") / currentzoom);
if (displaysize) {
$(this).css({
fontSize: displaysize
});
$(this).show();
} else
$(this).hide();
}
//changed this from offset as I was getting a weird dispersing effect around the mouse
// also can no longer test for visible but i assume you want to move them all anyway.
$(this).css({
top: newy + 'px',
left: newx + 'px'
});
});
//reattach to the body
$("body").append(spans);
};
UPDATE 2 -
So to get a little more performance out of this you can cache the window width and height, use a vanilla for loop, use vanilla js to change the css of the span. Now each redraw (on chrome) takes around 30-45 ms (http://jsfiddle.net/leighking2/orpupsge/) compared to my above update which saw them at around 80-100ms (http://jsfiddle.net/leighking2/b68r2xeu/)
so here is the updated redraw
redraw = function (resize) {
var spans = $("span").detach();
var width = $(window).width();
var height = $(window).height();
for (var i = spans.length; i--;) {
var span = $(spans[i]);
var newx = Math.floor((span.data("x") - currentx) / currentzoom * width);
var newy = Math.floor((span.data("y") - currenty) / currentzoom * height);
if (resize) {
displaysize = Math.floor(span.data("size") / currentzoom);
if (displaysize) {
span.css({
fontSize: displaysize
});
span.show();
} else span.hide();
}
spans[i].style.top = newy + 'px',
spans[i].style.left = newx + 'px'
}
$("body").append(spans);
};
SNIPPET EXAMPLE -
var currentzoom = 1;
var docFragment = document.createDocumentFragment();
var start = new Date();
var positions = []
var end = new Date();
console.log(end - start);
var currentx = 0.0,
currenty = 0.0,
currentzoom = 1.0,
xold = 0,
yold = 0,
button = false;
for (i = 0; i < 1000; i++) {
var blax = (Math.random() - 0.5) * 3000;
var blay = (Math.random() - 0.5) * 3000;
var tb = document.createElement('span');
$(tb).data("x", blax / $(window).width());
$(tb).data("y", blay / $(window).height());
$(tb).data("size", 20 * currentzoom);
tb.contentEditable = true;
tb.style.fontFamily = 'arial';
tb.style.fontSize = '20px';
tb.style.position = 'absolute';
tb.style.top = blay + 'px';
tb.style.left = blax + 'px';
tb.innerHTML = "newtext";
docFragment.appendChild(tb);
}
document.body.appendChild(docFragment);
document.body.onclick = function (e) {
if (e.target.nodeName == 'SPAN') {
return;
}
var tb = document.createElement('span');
$(tb).data("x", currentx + e.clientX / $(window).width() * currentzoom);
$(tb).data("y", currenty + e.clientY / $(window).height() * currentzoom);
$(tb).data("size", 20 * currentzoom);
tb.contentEditable = true;
tb.style.fontFamily = 'arial';
tb.style.fontSize = '20px';
tb.style.backgroundColor = 'transparent';
tb.style.position = 'absolute';
tb.style.top = e.clientY + 'px';
tb.style.left = e.clientX + 'px';
document.body.appendChild(tb);
tb.focus();
};
document.body.onmousedown = function (e) {
button = true;
xold = e.clientX;
yold = e.clientY;
};
document.body.onmouseup = function (e) {
button = false;
};
redraw = function (resize) {
var start = new Date();
var spans = $("span").detach();
var width = $(window).width();
var height = $(window).height();
for (var i = spans.length; i--;) {
var span = $(spans[i]);
var newx = Math.floor((span.data("x") - currentx) / currentzoom * width);
var newy = Math.floor((span.data("y") - currenty) / currentzoom * height);
if (resize) {
displaysize = Math.floor(span.data("size") / currentzoom);
if (displaysize) {
span.css({
fontSize: displaysize
});
span.show();
} else span.hide();
}
spans[i].style.top = newy + 'px',
spans[i].style.left = newx + 'px'
}
$("body").append(spans);
var end = new Date();
console.log(end - start);
};
document.body.onmousemove = function (e) {
if (button) {
currentx += (xold - e.clientX) / $(window).width() * currentzoom;
currenty += (yold - e.clientY) / $(window).height() * currentzoom;
xold = e.clientX;
yold = e.clientY;
redraw(false);
}
};
$(function () {
$('body').on('mousedown', 'span', function (event) {
if (event.which == 3) {
$(this).remove()
}
})
});
zoomcoef = function (coef) {
middlex = currentx + currentzoom / 2
middley = currenty + currentzoom / 2
currentzoom *= coef
currentx = middlex - currentzoom / 2
currenty = middley - currentzoom / 2
redraw(true)
}
window.onkeydown = function (event) {
if (event.ctrlKey && event.keyCode == 61) {
zoomcoef(1 / 1.732);
event.preventDefault();
}
if (event.ctrlKey && event.keyCode == 169) {
zoomcoef(1.732);
event.preventDefault();
}
if (event.ctrlKey && event.keyCode == 48) {
zoomonwidget(1 / 1.732);
event.preventDefault();
}
};
html, body {
height: 100%;
width: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
A solution was given by #Shmiddty which is much faster to all previous attempts : all elements should be wrapped, and only the wrapper has to be moved (instead of moving each element) :
http://jsfiddle.net/qhskacsw/
It runs smooth and fast even with 1000+ DOM elements.
var container = document.createElement("div"),
wrapper = document.createElement("div"),
dragging = false,
offset = {x:0, y:0},
previous = {x: 0, y:0};
container.style.position = "absolute";
wrapper.style.position = "relative";
container.appendChild(wrapper);
document.body.appendChild(container);
for (var i = 1000, span; i--;){
span = document.createElement("span");
span.textContent = "banana";
span.style.position = "absolute";
span.style.top = (Math.random() * 3000 - 1000 | 0) + 'px';
span.style.left = (Math.random() * 3000 - 1000 | 0) + 'px';
wrapper.appendChild(span);
}
// Don't attach events like this.
// I'm only doing it for this proof of concept.
window.ondragstart = function(e){
e.preventDefault();
}
window.onmousedown = function(e){
dragging = true;
previous = {x: e.pageX, y: e.pageY};
}
window.onmousemove = function(e){
if (dragging){
offset.x += e.pageX - previous.x;
offset.y += e.pageY - previous.y;
previous = {x: e.pageX, y: e.pageY};
container.style.top = offset.y + 'px';
container.style.left = offset.x + 'px';
}
}
window.onmouseup = function(){
dragging = false;
}
IMHO, I would go with your current thinking to maximize performance.
Reason: 1000+ DOM elements will always limit performance.
Yes, there is slightly more coding but your performance should be much better.
create one large offscreen canvas containing all 1000 texts.
Use context.textMeasure to calculate the bounding box of all 1000 texts relative to the image.
Save the info about each text in an object
var texts=[];
var texts[0]={ text:'text#0', x:100, y:100, width:35, height:20 }
...
context.drawImage that image on a canvas using an offset-X to 'pan' the image. This way you only have 1 canvas element instead of 1000 text elements.
In the mousedown handler, check if the mouse position is inside the bounding box of any text.
If the mouse is clicked inside a text bounding box, absolutely position an input-type-text directly over the text on the canvas. This way you only need 1 input element which can be reused for any of the 1000 texts.
Use the abilities of the input element to let the user edit the text. The canvas element has no native text editing abilities so don't "recreate the wheel" by coding canvas text editing.
When the user is done editing, recalculate the bounding box of the newly edited text and save it to the text object.
Redraw the offscreen canvas containing all 1000 texts with the newly edited text and draw it to the onscreen canvas.
Panning: if the user drags the onscreen canvas, draw the offscreen canvas onto the onscreen canvas with an offset equal to the distance the user has dragged the mouse. Panning is nearly instantaneous because drawing the offscreen canvas into the onscreen canvas-viewport is much, much faster than moving 1000 DOM input elements
[ Addition: full example with editing and panning ]
**Best Viewed In Full Screen Mode**
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var $canvas=$("#canvas");
var canvasOffset=$canvas.offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
var texts=[];
var fontSize=12;
var fontFace='arial';
var tcanvas=document.createElement("canvas");
var tctx=tcanvas.getContext("2d");
tctx.font=fontSize+'px '+fontFace;
tcanvas.width=3000;
tcanvas.height=3000;
var randomMaxX=tcanvas.width-40;
var randomMaxY=tcanvas.height-20;
var panX=-tcanvas.width/2;
var panY=-tcanvas.height/2;
var isDown=false;
var mx,my;
var textCount=1000;
for(var i=0;i<textCount;i++){
var text=(i+1000);
texts.push({
text:text,
x:parseInt(Math.random()*randomMaxX),
y:parseInt(Math.random()*randomMaxY)+20,
width:ctx.measureText(text).width,
height:fontSize+2,
});
}
var $textbox=$('#textbox');
$textbox.css('left',-200);
$textbox.blur(function(){
$textbox.css('left',-200);
var t=texts[$textbox.textsIndex]
t.text=$(this).val();
t.width=ctx.measureText(t.text).width;
textsToImage();
});
textsToImage();
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUpOut(e);});
$("#canvas").mouseout(function(e){handleMouseUpOut(e);});
// create one image from all texts[]
function textsToImage(){
tctx.clearRect(0,0,tcanvas.width,tcanvas.height);
for(var i=0;i<textCount;i++){
var t=texts[i];
tctx.fillText(t.text,t.x,t.y)
tctx.strokeRect(t.x,t.y-fontSize,t.width,t.height);
}
redraw();
}
function redraw(){
ctx.clearRect(0,0,canvas.width,canvas.height);
ctx.drawImage(tcanvas,panX,panY);
}
function handleMouseDown(e){
e.preventDefault();
e.stopPropagation();
mx=parseInt(e.clientX-offsetX);
my=parseInt(e.clientY-offsetY);
// is the mouse over a text?
var hit=false;
var x=mx-panX;
var y=my-panY;
for(var i=0;i<texts.length;i++){
var t=texts[i];
if(x>=t.x && x<=t.x+t.width && y>=t.y-fontSize && y<=t.y-fontSize+t.height){
$textbox.textsIndex=i;
$textbox.css({'width':t.width+5, 'left':t.x+panX, 'top':t.y+panY-fontSize});
$textbox.val(t.text);
$textbox.focus();
hit=true;
break;
}
}
// mouse is not over any text, so start panning
if(!hit){isDown=true;}
}
function handleMouseUpOut(e){
e.preventDefault();
e.stopPropagation();
isDown=false;
}
function handleMouseMove(e){
if(!isDown){return;}
e.preventDefault();
e.stopPropagation();
var mouseX=parseInt(e.clientX-offsetX);
var mouseY=parseInt(e.clientY-offsetY);
panX+=mouseX-mx;
panY+=mouseY-my;
mx=mouseX;
my=mouseY;
redraw();
}
body{ background-color: ivory; padding:10px; }
#wrapper{position:relative; border:1px solid blue; width:600px; height:600px;}
#textbox{position:absolute;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<h4>Click on #box to edit.<br>Tab to save changes.<br>Drag on non-text.</h4><br>
<div id=wrapper>
<input type=text id=textbox>
<canvas id="canvas" width=600 height=600></canvas>
</div>
<button></button>
I just run couple tests and it seems that moving absolutely positioned (position:absolute;) DOM elements (divs) with CSS transform:translate is even faster (by about 30%) than doing it via Canvas. But I was using CreateJS framework for the canvas job so my results may not hold for other use cases.
I'm attempting to have a draggable element snap back to the position of another element in Rapheal after dragging it. The problem I'm experiencing is that the .mouseup() function only executes the functions within it once. After you drag or move the element again, it will not longer execute the positioning functions I have within it.
My end goal is:
Drag the red square
When the red square is let go off (mouseup), snap square back to the blue square position.
Here is the code I've tried using, but I can't seem to get it to function correctly:
JSfiddle: http://jsfiddle.net/4GWEU/3/
Javascript:
//Makes elements Draggable.
Raphael.st.draggable = function() {
var me = this,
lx = 0,
ly = 0,
ox = 0,
oy = 0,
moveFnc = function(dx, dy) {
lx = dx + ox;
ly = dy + oy;
me.transform('t' + lx + ',' + ly);
},
startFnc = function() {
//window.draggedElement = this;
},
endFnc = function() {
ox = lx;
oy = ly;
};
this.drag(moveFnc, startFnc, endFnc);
};
var container = document.getElementById('container');
var paper = Raphael(container, '539', '537');
var shape1 = paper.rect(50,50, 50,50);
shape1.attr({x: '50',y: '50',fill: 'red','stroke-width': '0','stroke-opacity': '1'});
shape1Set = paper.set(shape1);
shape1Set.draggable();
var shape2 = paper.rect(50,50, 50,50);
shape2.attr({x: '150',y: '50',fill: 'blue','stroke-width': '0','stroke-opacity': '1'});
shape1Set.mousedown(function(event) {
console.log('mousedown');
});
shape1Set.mouseup(function(event) {
console.log('mouseup');
positionElementToElement(shape1, shape2);
});
$('#runPosition').click(function () {
positionElementToElement(shape1, shape2);
});
$('#runPosition2').click(function () {
positionElementToElement2(shape1, shape2);
});
function positionElementToElement(element, positionTargetElement)
{
var parentBBox = positionTargetElement.getBBox();
parent_x = parentBBox.x;
parent_y = parentBBox.y;
parent_width = parentBBox.width;
parent_height = parentBBox.height;
var elementBBox = element.getBBox();
element_width = elementBBox.width;
element_height = elementBBox.height;
var x_pos = parent_x + (parent_width / 2) - (element_width / 2) + 100;
var y_pos = parent_y + (parent_height / 2) - (element_height / 2) + 100;
console.log('Positioning element to: '+x_pos+' '+y_pos);
element.animate({'x' : x_pos, 'y' : y_pos}, 100);
}
function positionElementToElement2(element, positionTargetElement)
{
var parentBBox = positionTargetElement.getBBox();
parent_x = parentBBox.x;
parent_y = parentBBox.y;
parent_width = parentBBox.width;
parent_height = parentBBox.height;
var elementBBox = element.getBBox();
element_width = elementBBox.width;
element_height = elementBBox.height;
var x_pos = parent_x + (parent_width / 2) - (element_width / 2);
var y_pos = parent_y + (parent_height / 2) - (element_height / 2);
console.log('Positioning element to: '+x_pos+' '+y_pos);
element.animate({'x' : x_pos, 'y' : y_pos}, 100);
}
HTML:
Run Position
Run Position2
<div id="container"></div>
Notes:
I've duplicated the positionElementToElement() function and set one of them with an offset. I've binded both functions to the Run Position 1 and Run Position 2 links.
After dragging the item, clicking the Run Position 1 link no longer sets the square back where it should go (even though the function is logging the same x/y coordinates as when it worked.
I've figured out how to do this properly.
You have to modify the x and y attributes of the element directly.
It's also important to note that when retrieving the x and y attributes from an element using element.attr('x'); or element.attr('y'); it returns a string value, not an integer. Because of this, you have to use parseInt() on these returned values to properly add up the movement x and y values to apply to the element when it moves.
The following code will snap the red square to the blue square, when the red square is moved.
Working Example: http://jsfiddle.net/naQQ2/2/
window.onload = function () {
var R = Raphael(0, 0, "100%", "100%"),
shape1 = R.rect(50,50, 50,50);
shape1.attr({x:'50',y:'50',fill: 'red','stroke-width': '0','stroke-opacity': '1'});
shape2 = R.rect(50,50, 50,50);
shape2.attr({x:'150',y:'50',fill: 'blue','stroke-width': '0','stroke-opacity': '1'});
var start = function () {
console.log(this);
this.ox = parseInt(this.attr('x'));
this.oy = parseInt(this.attr('y'));
this.animate({opacity: .25}, 500, ">");
},
move = function (dx, dy) {
this.attr({x: this.ox + dx, y: this.oy + dy});
},
up = function () {
//Snap to shape2 on mouseup.
var snapx = parseInt(shape2.attr("x"));
snapy = parseInt(shape2.attr("y"));
this.animate({x: snapx, y: snapy}, 100);
this.animate({opacity: 1}, 500, ">");
};
R.set(shape1, shape2).drag(move, start, up);
};