JSFiddle - React, Tailwind, and code Playground
HTML
<html>
<body>
<div id="canvas"></div>
</body>
</html>
CSS
#canvas
{
height: 500px;
width: 500px;
margin: 0 auto;
border: 1px dashed black;
}
JavaScript
window.onload = function () {
var height = 500;
var width = 500;
var rectSize = 50;
var R = Raphael("canvas", height, width);
// Build Rects
var rect1 = R.rect((width / 2) - (rectSize/2), 0, rectSize, rectSize).attr({
fill: "hsb(.8, 1, 1)",
stroke: "none",
opacity: .5,
cursor: "move"
});
var rect2 = R.rect(100, 100, rectSize, rectSize).attr({
fill: "hsb(0, 0, 0)",
stroke: "none",
opacity: .5,
cursor: "move"
});
// start, move, and end are the drag functions
var start = function () {
// storing original coordinates
this.ox = this.attr("x");
this.oy = this.attr("y");
this.attr({ opacity: 1 });
};
var move = function (dx, dy) {
// cache rect properties
var r2_x = rect2.attr('x'),
r2_y = rect2.attr('y'),
r1_x = this.attr('x'),
r1_y = this.attr('y');
// keeps Rect in boarder
var x = this.ox + dx;
x = x < 0 ? 0 : x > width - rectSize ? width - rectSize : x;
var y = this.oy + dy;
y = y < 0 ? 0 : y > height - rectSize ? height - rectSize : y;
// check the x and y directions separately
var x_collide = rect_collision(r2_x, r2_y, rectSize, x, r1_y, rectSize),
y_collide = rect_collision(r2_x, r2_y, rectSize, r1_x, y, rectSize);
...