JSFiddle - React, Tailwind, and code Playground
by Vitaly Volovich
HTML
<div class="drag drag-1"></div>
<div class="drag drag-2"></div>
<div class="drag drag-3"></div>
CSS
body {
margin: 0;
}
.drag {
position: absolute;
width: 150px;
height: 150px;
}
.drag-1 {
background: #f93;
transform: translate(100px, 100px) rotate(60deg);
}
.drag-2 {
background: #69c;
transform: translate(300px, 100px) rotate(45deg) translate(100px, 100px) scale(1.5, 1.5);
}
.drag-3 {
background: #369;
transform: rotate(30deg);
}
JavaScript
$(document).on('mousedown', '.drag', function (e) {
var elem = $(this),
matrix = elem.css('transform').replace(/^.+\(/, '').replace(/\).*$/, '').split(/\s*,\s*/),
startX = matrix[4] * 1 - e.clientX,
startY = matrix[5] * 1 - e.clientY,
current = matrix.slice(0, 4);
$(document)
.on('mousemove', move)
.on('mouseup', up);
function move (e) {
current[4] = startX + e.clientX;
current[5] = startY + e.clientY;
$(elem).css({
transform: 'matrix(' + current.join() + ')'
});
}
function up (e) {
$(document)
.off('mousemove', move)
.off('mouseup', up);
}
});