Skip to content

Instantly share code, notes, and snippets.

@mkdizajn
Created April 13, 2021 13:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mkdizajn/5e27baca5fd8839691e0d60de8ccdf75 to your computer and use it in GitHub Desktop.
Save mkdizajn/5e27baca5fd8839691e0d60de8ccdf75 to your computer and use it in GitHub Desktop.
Draggable Move, Rotate and Scale
<div class="container">
<img class="image" width="128" height="128" src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/106114/bee3.svg" alt="">
<div class="outline"></div>
<div class="handle"></div>
</div>
console.clear();
var container = document.querySelector(".container");
var outline = document.querySelector(".outline");
var handle = document.querySelector(".handle");
var image = document.querySelector(".image");
var origSize = {
width: image.width,
height: image.height
};
var origVector = {
x: origSize.width/ 2,
y: -origSize.height / 2
};
// Length/magnitude of vector
var len1 = Math.sqrt(origVector.x * origVector.x + origVector.y * origVector.y);
// Normalized vector
var v1 = {
x: origVector.x / len1,
y: origVector.y / len1
};
// Angle of vector
var angle1 = Math.atan2(v1.y, v1.x);
TweenLite.set([container, image, handle, outline], {
xPercent: -50,
yPercent: -50
});
TweenLite.set(outline, {
width: origSize.width,
height: origSize.height
});
TweenLite.set(handle, {
x: origVector.x,
y: origVector.y
});
Draggable.create(container);
Draggable.create(handle, {
onPress: stopPropagation,
onDrag: transformItems
});
TweenLite.set(container, {
autoAlpha: 1
});
function transformItems() {
// Move vector
var v2 = {
x: this.x,
y: this.y
};
// Length of move vector
var len2 = Math.sqrt(v2.x * v2.x + v2.y * v2.y);
// Normalize move vector
if (len2) {
v2.x /= len2;
v2.y /= len2;
}
var angle = Math.atan2(v2.y, v2.x) - angle1;
var scale = len2 / len1;
TweenLite.set(outline, {
width: origSize.width * scale,
height: origSize.height * scale,
rotation: angle + "_rad"
});
TweenLite.set(image, {
scale: scale,
rotation: angle + "_rad"
});
}
function stopPropagation(event) {
event.stopPropagation();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.2/TweenMax.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.2/utils/Draggable.min.js"></script>
* {
box-sizing: border-box;
}
html, body {
height: 100%;
min-height: 100%;
}
body {
overflow: hidden;
}
.container,
.outline,
.image,
.handle {
position: absolute;
top: 50%;
left: 50%;
}
.container {
visibility: hidden;
}
.outline {
border: 1px dashed black;
}
.handle {
width: 15px;
height: 15px;
background: #000;
border-radius: 50%;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment