Square drag system
by Nathan Woods
HTML
<div id="canvas"></div>
<!-- note: messed up stuff after smashUs happens -->
JavaScript
var R = Raphael("canvas", 155*2, 155*2);
R.rect(0,0,155*2,155*2);// border
//R.circle(155,155,5); // center marker
R.setStart();
R.rect(100, 100, 50, 50).attr({fill: 'red'});
R.rect(100, 160, 50, 50).attr({fill: 'blue'});
R.rect(160, 100, 50, 50).attr({fill: 'yellow'});
R.rect(160, 160, 50, 50).attr({fill: 'green'});
var c = R.setFinish();
var offsets = [[0,0],[0,60],[0,-60],[60,0],[-60,0]];
var move = function(dx, dy){
moveExact(this,this.o.x+dx,this.o.y+dy);
var pos = [this.getBBox().x,this.getBBox().y]; // is this true
var old = this.dropTarget;
for (var key in this.holder) {
if (dist(this.holder[key], pos)+5<dist(this.dropTarget, pos)){
this.dropTarget = this.holder[key];
}
}
if (old != this.dropTarget) {
if (typeof(old.obj) != 'undefined') old.obj.attr({fill:'none'});
this.dropTarget.obj.attr({fill:'grey'});
}
}, start = function() {
this.o = o = this.getBBox();
this.holder = {};
this.dropTarget = {x:o.x, y:o.y};
c.exclude(this);
c.forEach(function(obj){
var box = obj.getBBox();
var list = Object.keys(this.holder);
for(var i=0; i<offsets.length; i++) {
var x=Math.round(box.x+offsets[i][0]), y=Math.round(box.y+offsets[i][1]);
if (list.indexOf(x+','+y) < 0) {
var temp = R.rect(x,y,50,50);
temp.attr({'stroke-dasharray':'-', 'stroke-width':3, 'opacity':0.7});
this.holder[x+','+y] = {obj:temp, x:x, y:y};
}
if (Math.round(this.dropTarget.x)==x && Math.round(this.dropTarget.y)==y) {
this.dropTarget = this.holder[x+','+y];
this.dropTarget.obj.attr({fill:'grey'});
}
}
}, this);
this.toFront().attr({opacity:0.7});// this needs to be here
}, end = function() {
moveExact(this,this.dropTarget.x,this.dropTarget.y);
c.push(this);
for (var key in this.holder) {
...