I want to rotate 2 circles around each other in a circular motion by mouse drag like in this code using jQuery
When I drag the white ball it rotates correctly and makes red ball rotate also and that what I need.
My problem is that when I click on red ball it doesn't rotate and doesn't make as the white ball.
I want to make a red ball like a white ball exactly that when drag red ball the red ball and white ball rotate with mouse like in white-ball case.
https://jsfiddle.net/Sarah_Lotfy/h1ye8Ld3/4/
If there is a code that does the same thing please share it with me
var circle = document.getElementById('circle'),
picker = document.getElementById('picker'),
pickerCircle = picker.firstElementChild,
rect = circle.getBoundingClientRect(),
center = {
x: rect.left + rect.width / 2,
y: rect.top + rect.height / 2
},
transform = (function(){
var prefs = ['t', 'WebkitT', 'MozT', 'msT', 'OT'],
style = document.documentElement.style,
p;
for (var i = 0, len = prefs.length; i < len; i++){
if ( (p = prefs[i] + 'ransform') in style ) return p
}
alert('your browser doesnt support css transforms!')
})(),
rotate = function(x, y){
var deltaX = x - center.x,
deltaY = y - center.y,
angle = Math.atan2(deltaY, deltaX) * 180 / Math.PI
return angle
},
// DRAGSTART
mousedown = function(event){
event.preventDefault()
document.body.style.cursor = 'move'
mousemove(event)
document.addEventListener('mousemove', mousemove)
document.addEventListener('mouseup', mouseup)
},
// DRAG
mousemove = function(event){
picker.style[transform] = 'rotate(' + rotate(event.x, event.y) + 'deg)'
},
// DRAGEND
mouseup = function(){
document.body.style.cursor = null;
document.removeEventListener('mouseup', mouseup)
document.removeEventListener('mousemove', mousemove)
}
// DRAG START
pickerCircle.addEventListener('mousedown', mousedown)
// ENABLE STARTING THE DRAG IN THE BLACK CIRCLE
circle.addEventListener('mousedown', function(event){
if(event.target == this) mousedown(event)
})
#circle{
position: relative;
width: 300px;
height: 300px;
border-radius: 50%;
background: #000;
}
#circle-in{
position: absolute;
top: 35px;
left: 35px;
width: 230px;
height: 230px;
border-radius: 50%;
background: #fff;
}
#picker{
position: absolute;
top: 50%;
left: 50%;
height: 30px;
margin-top: -15px;
width: 50%;
transform-origin: center left;
}
#picker-circle{
width: 30px;
height: 30px;
border-radius: 50%;
background: #fff;
margin: 0 3px 0 auto;
cursor: move;
}
#picker2{
position: absolute;
top: -200%;
left: -100%;
height: 30px;
margin-top: -10px;
width: 50%;
transform-origin: center right ;
}
#picker-circle2{
width: 30px;
height: 30px;
border-radius: 50%;
background: red;
margin: 0 3px 0 auto;
cursor: move;
}
<div id="circle">
<div id="circle-in"></div>
<div id="picker">
<div id="picker-circle"></div>
</div>
<div id="picker2">
<div id="picker-circle2"></div>
</div>
</div>
Related
I understand that we need to use transform: rotate(ndeg); in order to rotate a specific element in CSS. In this case, I want to do it dynamically. Using jQuery, I want to rotate the box/container div when the user drags the handle (the red background) on n degrees as the user wishes. Is it possible in jQuery?
body {
padding: 50px;
}
.box_element {
border: 1px solid black;
width: 200px;
height: 200px;
position: relative;
z-index: -1;
}
.handle {
position: absolute;
bottom: -10px;
right: -10px;
width: 10px;
height: 10px;
border: 1px solid;
background: red;
z-index: 10;
}
<body>
<div class="box_element">
THIS IS TEST
<div class="handle"></div>
</div>
</body>
Here you need to write few code to make it possible, try live code https://codepen.io/libin-prasanth/pen/xxxzbLg
var stop,
active = false,
angle = 0,
rotation = 0,
startAngle = 0,
center = {
x: 0,
y: 0
},
R2D = 180 / Math.PI;
function start(e) {
e.preventDefault();
var bb = this.getBoundingClientRect(),
t = bb.top,
l = bb.left,
h = bb.height,
w = bb.width,
x,
y;
center = {
x: l + w / 2,
y: t + h / 2
};
x = e.clientX - center.x;
y = e.clientY - center.y;
startAngle = R2D * Math.atan2(y, x);
return (active = true);
}
function rotate(e) {
e.preventDefault();
var x = e.clientX - center.x,
y = e.clientY - center.y,
d = R2D * Math.atan2(y, x);
rotation = d - startAngle;
return (rot.style.webkitTransform = "rotate(" + (angle + rotation) + "deg)");
}
function stop() {
angle += rotation;
return (active = false);
}
rot = document.getElementById("draggable");
rot.addEventListener("mousedown", start, false);
window.addEventListener("mousemove", function(event) {
if (active === true) {
event.preventDefault();
rotate(event);
}
});
window.addEventListener("mouseup", function(event) {
event.preventDefault();
stop(event);
});
#draggable {
left: 50px;
top: 50px;
width: 100px;
height: 100px;
position: relative;
border: 1px solid #000;
}
#draggable:before{
content: "";
position: absolute;
bottom: -5px;
right: -5px;
width: 10px;
height: 10px;
background: #f00;
}
<div id="draggable">
</div>
You can make use of a css-variable and then change the value of the variable when clicked.
const box_element = document.getElementById('box_element');
const handle = document.getElementById('handle');
handle.addEventListener('click', function() {
let currentVal = getComputedStyle(box_element).getPropertyValue('--rotate_deg');
box_element.style.setProperty(
'--rotate_deg', ((parseInt(currentVal.replace('deg', '')) + 90) % 360) + 'deg');
});
:root {
--rotate_deg: 0deg;
}
.box_element {
margin: 1em;
border: 1px solid black;
width: 100px;
height: 100px;
position: relative;
z-index: -1;
transform: rotate(var(--rotate_deg))
}
.handle {
position: absolute;
bottom: -10px;
right: -10px;
width: 10px;
height: 10px;
border: 1px solid;
background: red;
z-index: 10;
cursor: pointer;
}
<div class="box_element" id="box_element">
THIS IS TEST
<div class="handle" id="handle"></div>
</div>
I'm using a small script to follow the cursor with a div element.
This script makes the element strictly follow the cursor.
What I'm trying to do is to add some kind of duration to the process of "following" the cursor. I tried CSS transitions but the animation always ended up breaking. Can somebody please help me with this?
Let's say mouse is somewhere, and then it changes position by around 100px. I want to specify the duration like if i was using CSS... But the thing is that I can not use any transitions but only some javascript magic instead...
document.body.addEventListener("mousemove", function(e) {
var curX = e.clientX;
var curY = e.clientY;
document.querySelector('mouse').style.left = curX - 10 + 'px';
document.querySelector('mouse').style.top = curY - 10 + 'px';
});
body {
background: #333;
height: 500px;
width: 500px;
}
mouse {
display: block;
position: fixed;
height: 20px;
width: 20px;
background: #fff;
border-radius: 50%;
}
<body>
<mouse></mouse>
</body>
I was wondering how to add a transition without using the CSS but I'm not the most advanced when it comes to JavaScript.
[edit] : I don't wanna use window.setTimeout.
[edit 2] : I wanted to use transition: 0.1s; but as I said it broke the effect when user moved the mouse too quickly.
There's a whole bunch of ways to do this, as you can see in the other answers, each with its own "feel". I'm just adding one more, where the dot approaches the cursor by a percentage of the remaining distance.
let curX = 0, curY = 0, elemX = null, elemY = null;
document.body.addEventListener("mousemove", function(e) {
curX = e.clientX;
curY = e.clientY;
if (elemX === null) [ elemX, elemY ] = [ curX, curY ];
});
let amt = 0.1; // higher amount = faster tracking = quicker transition
let elem = document.querySelector('mouse');
let frame = () => {
requestAnimationFrame(frame);
elemX = (elemX * (1 - amt)) + (curX * amt);
elemY = (elemY * (1 - amt)) + (curY * amt);
elem.style.left = `${elemX}px`;
elem.style.top = `${elemY}px`;
};
frame();
body {
position: absolute;
background: #333;
left: 0; top: 0; margin: 0; padding: 0;
height: 100%;
width: 100%;
}
mouse {
display: block;
position: absolute;
height: 20px; margin-left: -10px;
width: 20px; margin-top: -10px;
background: #fff;
border-radius: 50%;
}
<body>
<mouse></mouse>
</body>
You can use setTimeout() function, to introduce a delay:
document.body.addEventListener("mousemove", function(e) {
var delay=250 //Setting the delay to quarter of a second
setTimeout(()=>{
var curX = e.clientX;
var curY = e.clientY;
document.querySelector('mouse').style.left = curX - 10 + 'px';
document.querySelector('mouse').style.top = curY - 10 + 'px';
},delay)
});
body {
background: #333;
height: 500px;
width: 500px;
}
mouse {
display: block;
position: fixed;
height: 20px;
width: 20px;
background: #fff;
border-radius: 50%;
}
<body>
<mouse></mouse>
</body>
Or, to avoid trailing, use an interval and move the cursor to the correct direction (change ratio to set the speed ratio):
var curX,curY
document.body.addEventListener("mousemove", function(e) {
curX = e.clientX;
curY = e.clientY;
});
setInterval(()=>{
var ratio=5
var x=document.querySelector('mouse').offsetLeft+10
var y=document.querySelector('mouse').offsetTop+10
document.querySelector('mouse').style.left=((curX-x)/ratio)+x-10+"px"
document.querySelector('mouse').style.top=((curY-y)/ratio)+y-10+"px"
},16)
body {
background: #333;
height: 500px;
width: 500px;
}
mouse {
display: block;
position: fixed;
height: 20px;
width: 20px;
background: #fff;
border-radius: 50%;
}
<body>
<mouse></mouse>
</body>
I tried this:
function getPosition(e) {
var rect = e.target.getBoundingClientRect();
var x = e.clientX - rect.left;
var y = e.clientY - rect.top;
return {
x,
y
}
}
window.addEventListener("click", function(event) {
document.getElementById("info").innerHTML = "ID: " + event.target.id + "<br> X: " + getPosition(event).x + " Y: " + getPosition(event).y;
});
body {
perspective: 400px;
margin: 0;
}
#test {
width: 400px;
height: 400px;
background-color: red;
transform: rotateY(45deg);
position: absolute;
left: 40%;
}
#info {
position: absolute;
right: 0;
top: 0;
box-shadow: 0px 0px 10px black;
width: 200px;
border-radius: 10px;
padding: 5px;
}
<div id="info"></div>
<div style="margin-top: 10%;">
<div id="test">
</div>
</div>
Link to jsfiddle
but it does just work without a 3D Rotation. If I click for example in the bottom right corner of the red div, then it should give me back something arround (because you never hit the corner exact) X: 300px and Y: 300px. But this works just when the element is with no rotation. So how can I get the clicked Position with 3d rotation? (if the rotation changes, then it must work too!)
I have created a div inside a container that points to the cursor. The issue is that the accuracy is off and I need to change the angle.
HTML
<div class="shooting_container">
<div class="shooter">
<div class="shooting_arm">
</div>
</div>
</div>
CSS
.shooter {
height: 480px;
width: 200px;
background-color: white;
bottom: 150px;
margin: 0 100px;
position: absolute;
.shooting_arm {
height: 245px;
width: 166px;
bottom: 500px;
position: absolute;
top: calc(50% - 40px);
transform: translateY(-50%) rotate(-12deg);
z-index: 500;
transform-origin: 156px 8px;
left: -43px;
background-color: red;
// Where the transform origin lies
&::after {
position: absolute;
top: 8px;
left: 156px;
width: 5px;
height: 5px;
content: '';
background-color: #f0f;
border-radius: 50%;
transform: translate(-50%, -50%);
}
}
}
JS
$(document).on('mousemove', moveCursor);
function moveCursor(e) {
var box = $(".shooter .shooting_arm");
var boxCenter = [box.offset().left+box.width()/2, box.offset().top+box.height()/2];
var angle = Math.atan2(e.pageX - boxCenter[0], - (e.pageY - boxCenter[1]) )*(180/Math.PI) - 180;
if (angle < -160) {
angle = -0;
}
setArm(box, angle);
}
function setArm(arm, angle) {
arm.css({ "-webkit-transform": 'translateY(-50%) rotate(' + angle + 'deg)'});
arm.css({ '-moz-transform': 'translateY(-50%) rotate(' + angle + 'deg)'});
}
CodePen:
https://codepen.io/anon/pen/vrWJwZ
Problem 1: Angle is incorrect and differs as you move
Incorrect angle. I need the top of the container to align with the cursor, not the center. I tried adjusting:
var boxCenter = [box.offset().left+box.width()/2, box.offset().top+box.height()/2];
to
var boxCenter = [box.offset().left+box.width()/2, box.offset().top+box.height()/2/2];
But it still was not in line with the top of the container.
Problem 2: Glitches when cursor is within the div itself
For some reason it returns two different angle values when the cursor is within the container and causes it to jiggle. Why does it do this?
I have spent many days trying to make an item resizable that is rotated with interact.js.
This is the code that I have at this moment, I will try to explain the concept.
We have a selector item for two reasons, because the container could be scaled with css transform (like a zoom), and we need to have the selector outside and because we have a multiselection, and the selector grow if I have two rectangle selected, but in this case this is not the main problem and we have calculated the scaled proportion without problems and other things.
When the selector is resize, it take the rectangle, and make the same with the width, height, left, top and rotation.
Javascript:
// TAP - CLICK EVENT (just for positioning the selector)
interact('#rectangle').on('tap', event => {
console.log('Tap Box!');
event.stopPropagation();
const $rectangleCloned = $('#rectangle').clone();
const previousTransform = $rectangleCloned.css('transform');
$rectangleCloned.css('transform', 'none');
$rectangleCloned.css('opacity', '0');
$rectangleCloned.css('display', 'block');
$('#container').append($rectangleCloned);
const values = $rectangleCloned[0].getBoundingClientRect();
// This is just a trick for fast implementation:
$('#selector').css('top', values.y);
$('#selector').css('left', values.x);
$('#selector').css('width', values.width);
$('#selector').css('height', values.height);
$('#selector').css('transform', previousTransform);
$rectangleCloned.remove();
return values;
});
interact('.pointer9').draggable({
max: 1,
onmove: event => {
const angleDeg =
Math.atan2(
centerRotate.posY - event.pageY,
centerRotate.posX - event.pageX
) *
180 /
Math.PI;
console.log(this.rotate);
const prevAngle = this.rotate - angleInitial;
const angle = parseInt(angleDeg) + prevAngle;
this.$rectangle.css({
transform: 'rotate(' + angle + 'deg)'
});
this.$selector.css({
transform: 'rotate(' + angle + 'deg)'
});
},
onstart: event => {
const data = event.interactable.getRect(event.target.parentNode);
this.centerRotate = {
posX: data.left + data.width / 2,
posY: data.top + data.height / 2
};
this.angleInitial =
Math.atan2(
centerRotate.posY - event.pageY,
centerRotate.posX - event.pageX
) *
180 /
Math.PI;
this.$rectangle = $('#rectangle');
this.$selector = $('#selector');
this.rotate = $rectangle.attr('angle') || 0;
},
onend: event => {
const $box = $('#selector');
const matrix = $box.css('transform');
const values = matrix
.split('(')[1]
.split(')')[0]
.split(',');
var a = values[0];
var b = values[1];
var angle = Math.round(Math.atan2(b, a) * (180 / Math.PI));
$rectangle.attr('angle', angle);
}
});
interact('#selector')
.resizable({
// resize from all edges and corners
edges: {
left: true,
right: true,
bottom: true,
top: true
},
// keep the edges inside the parent
restrictEdges: {
outer: 'parent',
endOnly: true,
},
// minimum size
restrictSize: {
min: {
width: 100,
height: 50
},
},
inertia: true,
})
.on('resizemove', function(event) {
var target = event.target,
x = parseFloat($(target).offset().left) || 0,
y = parseFloat($(target).offset().top) || 0;
// update the element's style
target.style.width = event.rect.width + 'px';
target.style.height = event.rect.height + 'px';
// translate when resizing from top or left edges
x += event.deltaRect.left;
y += event.deltaRect.top;
target.style.left = x + 'px';
target.style.top = y + 'px';
$('#rectangle')[0].style.left = target.style.left;
$('#rectangle')[0].style.top = target.style.top;
$('#rectangle')[0].style.width = target.style.width;
$('#rectangle')[0].style.height = target.style.height;
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
});
CSS:
#container {
width: 500px;
height: 400px;
top: 0;
left: 0;
position: absolute;
background-color: #CCC;
}
#rectangle {
top: 50px;
left: 50px;
width: 120px;
height: 60px;
background-color: red;
position: absolute;
}
#selector {
display: inline-block;
position: absolute;
pointer-events: none;
z-index: 9999;
top: -1000px;
/*Not showing at start*/
}
#selector .pointers {
display: inline-block;
position: absolute;
z-index: 2;
width: 10px;
height: 10px;
pointer-events: all;
}
#selector .pointers .point {
width: 10px;
height: 10px;
background-color: #fff;
border: 2px solid rgba(0, 0, 0, 0.9);
border-radius: 50%;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
#selector .pointers.pointer1 {
top: -5px;
left: -5px;
}
#selector .pointers.pointer2 {
bottom: -5px;
left: -5px;
}
#selector .pointers.pointer3 {
top: -5px;
right: -5px;
}
#selector .pointers.pointer4 {
bottom: -5px;
right: -5px;
}
#selector .pointers.pointer-north {
top: -5px;
left: calc(50% - 5px);
}
#selector .pointers.pointer-south {
bottom: -5px;
left: calc(50% - 5px);
}
#selector .pointers.pointer-east {
right: -5px;
top: calc(50% - 5px);
}
#selector .pointers.pointer-west {
left: -5px;
top: calc(50% - 5px);
}
#selector .pointer-rotate {
border: 2px solid rgba(0, 0, 0, 0.9);
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
border-radius: 50%;
cursor: rotate;
}
#selector .pointer9 {
bottom: -70px;
left: calc(50% - 11px);
display: inline-block;
width: 20px;
height: 20px;
background-color: #fff;
pointer-events: all;
position: absolute;
}
#selector .rotate-line {
border-left: 1px dashed #5f5f5f;
height: 40px;
position: absolute;
top: -40px;
left: calc(50% - 1px);
width: 1px;
}
HTML:
<div id="container">
<div id="rectangle">
</div>
<div id="selector">
<div class="pointers pointer1">
<div class="point"></div>
</div>
<div class="pointers pointer2">
<div class="point">
</div>
</div>
<div class="pointers pointer3">
<div class="point">
</div>
</div>
<div class="pointers pointer4">
<div class="point">
</div>
</div>
<div class="pointers pointer-north">
<div class="point">
</div>
</div>
<div class="pointers pointer-east">
<div class="point">
</div>
</div>
<div class="pointers pointer-south">
<div class="point">
</div>
</div>
<div class="pointers pointer-west">
<div class="point">
</div>
</div>
<span class="topline lines-resize" />
<span class="rightline lines-resize" />
<span class="botline lines-resize" />
<span class="leftline lines-resize" />
<div class="pointer-rotate pointer9" />
<div class="rotate-line" />
</div>
</div>
Fiddle for testing:
https://jsfiddle.net/ub70028c/46/
I have read about other people trying to make the same without not results...
Thanks!
I checked your code and a similar library for resizable and rotatable and I figure out your problem.
First, checking similar library:
Please see this fiddle that I created by jquery.freetrans.js.
If you inspect on <div class="shape">, you can see
transform: matrix(1, 0, 0, 1, 0, 0);
If you rotate it, transform changed like below:
transform: matrix(0.997373, -0.0724379, 0.0724379, 0.997373, 0, 0);
In similar case, your code uses transform that at first, it doesn't transform and after rotating, it has like below:
transform: rotate(-2.49576deg);
If you can use matrix instead of rotate in transform, your code will work properly. If you can't change it, you can use similar library like jquery.freetrans.jsthat work properly with rotate and resize together.
https://github.com/taye/interact.js/issues/569
https://github.com/taye/interact.js/issues/499
https://github.com/taye/interact.js/issues/394
I am afraid you have chosen a library whose author has clearly stated his intent
There's no built-in way. As I mentioned in #137 I'm not really interested in handling scaled or rotated elements
So the question you should ask yourself is
Do I want to find a workaround to make this library work or choose a different library perhaps?
Update-1: 28-Apr-2018
In case you want to do it in canvas instead of normal elements then I found fabric.js a good option
we are very close to finish the work after five days... we need to optimice all the mathematical calculations... but yes, this is what I was looking for:
Sorry, but we don't have the code ready... I will post all with comments for other people.
Comments: For a mathematician, this task is not very complex because all the angles are rectangular (90ยบ). I will try to make a PR to the Interact.js, even to other libraries to implement this feature by default. Hope this work help to other developers ;)