How to Drag, Drop and Clone an object using interact.js - javascript

I'm have trouble with cloning an object using interact.js. I can do drag and drop, but there is no way to get clone from the objects.
I put here drag and drop code. Can someone modify it to clone objects?
#drag-1, #drag-2 {
width: 20%;
height: 10%;
min-height: 6.5em;
margin: 10%;
background-color: #29e;
color: white;
border-radius: 0.75em;
padding: 4%;
-webkit-transform: translate(0px, 0px);
transform: translate(0px, 0px);
}
#drag-me::before {
content: "#" attr(id);
font-weight: bold;
}
top:35px; left:40px; width:50px; height:50px;
z-index:99; background-color:#44ebfa;
}
<html>
<head>
<title>test 1 </title>
<!--<script type="text/javascript" src="d3-js/d3.min.js"></script>-->
<script type="text/javascript" src="www.googledrive.com/host/0B4A7r4wXVSe-SDdVdlNtbnhFZ2s"></script>
<link rel="stylesheet" type="text/css" href="test1_css1.css">
</head>
<body>
<script>
// target elements with the "draggable" class
interact('.draggable')
.draggable({
// enable inertial throwing
inertia: true,
// keep the element within the area of it's parent
restrict: {
restriction: "parent",
endOnly: true,
elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
},
// call this function on every dragmove event
onmove: dragMoveListener,
// call this function on every dragend event
onend: function (event) {
var textEl = event.target.querySelector('p');
textEl && (textEl.textContent =
'moved a distance of '
+ (Math.sqrt(event.dx * event.dx +
event.dy * event.dy)|0) + 'px');
}
});
function dragMoveListener (event) {
var target = event.target,
// keep the dragged position in the data-x/data-y attributes
x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx,
y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)';
// update the posiion attributes
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
}
// this is used later in the resizing demo
window.dragMoveListener = dragMoveListener;
</script>
<div id="drag-1" class="draggable">
<p> You can drag one element </p>
</div>
<div id="drag-2" class="draggable">
<p> with each pointer </p>
</div>
</body>
</html>

Try this code sample
interact('.draggable').draggable({
inertia: true,
restrict: {
restriction: "#visualizer-panel",
endOnly: true,
elementRect: { top: 0, left: 0, bottom: 1, right: 1 }
},
onmove: function (event) {
var target = event.target;
var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx;
var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy;
target.style.webkitTransform =
target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';
target.setAttribute('data-x', x);
target.setAttribute('data-y', y);
},
onend: function(event) {
console.log(event);
}
}).on('move', function (event) {
var interaction = event.interaction;
if (interaction.pointerIsDown && !interaction.interacting() && event.currentTarget.getAttribute('clonable') != 'false') {
var original = event.currentTarget;
var clone = event.currentTarget.cloneNode(true);
var x = clone.offsetLeft;
var y = clone.offsetTop;
clone.setAttribute('clonable','false');
clone.style.position = "absolute";
clone.style.left = original.offsetLeft+"px";
clone.style.top = original.offsetTop+"px";
original.parentElement.appendChild(clone);
interaction.start({ name: 'drag' },event.interactable,clone);
}
});

Related

Interactjs How To Change Start Position Drag Item

my dragitem initially appears in the upper left. I want to give a space of 100 pixels from the top and left at the opening. but I have to do this with interactjs own code, not css. because if i do it with css the scroll setting is broken
interact('.dragitem')
.draggable({
inertia: true,
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
autoScroll: true,
listeners: {
move: dragMoveListener
}
})
function dragMoveListener (event) {
var target = event.target
var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx
var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy
target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';
target.setAttribute('data-x', x)
target.setAttribute('data-y', y)
}
window.dragMoveListener = dragMoveListener
.drag-container {
width:1000px;
height:1000px;
background:red;
}
.dragitem {
width:100px;
height:100px;
background:blue;
}
<script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>
<div class="drag-container">
<div class="dragitem">drag me</div>
</div>
You have to edit the starting position in style, data-x and data-y directly in HTML
<div class="dragitem" style="transform: translate(100px, 100px);" data-x="100" data-y="100">drag me</div>
interact('.dragitem')
.draggable({
inertia: true,
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
autoScroll: true,
listeners: {
move: dragMoveListener
}
})
function dragMoveListener (event) {
var target = event.target
var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx
var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy
target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';
target.setAttribute('data-x', x)
target.setAttribute('data-y', y)
}
window.dragMoveListener = dragMoveListener
.drag-container {
width:1000px;
height:1000px;
background:red;
}
.dragitem {
width:100px;
height:100px;
background:blue;
}
<script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>
<div class="drag-container">
<div class="dragitem" style="transform: translate(100px, 100px);" data-x="100" data-y="100">drag me</div>
</div>

I'm finding "Object Layout library" on JavaScript

Hello I'm searching "Object Layout library" its working on JavaScript.
I want to implement function for my web app like these feature below (look at this link).
https://imgur.com/mJq3HiV
I already searched information but I couldn't find a good module. Do you know a library something like that?
Okay, you are looking for interact.js here is the npm link.
Read the docs to learn, see the snippet bellow to see if is that what you want.
function dragMoveListener(event) {
var target = event.target
// keep the dragged position in the data-x/data-y attributes
var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx
var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)'
// update the posiion attributes
target.setAttribute('data-x', x)
target.setAttribute('data-y', y)
}
window.onload = () => {
interact('.resize-drag')
.resizable({
// resize from all edges and corners
edges: { left: true, right: true, bottom: true, top: true },
listeners: {
move(event) {
var target = event.target
var x = (parseFloat(target.getAttribute('data-x')) || 0)
var y = (parseFloat(target.getAttribute('data-y')) || 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.webkitTransform = target.style.transform =
'translate(' + x + 'px,' + y + 'px)'
target.setAttribute('data-x', x)
target.setAttribute('data-y', y)
target.textContent = Math.round(event.rect.width) + '\u00D7' + Math.round(event.rect.height)
}
},
modifiers: [
// keep the edges inside the parent
interact.modifiers.restrictEdges({
outer: 'parent'
}),
// minimum size
interact.modifiers.restrictSize({
min: { width: 100, height: 50 }
})
],
inertia: true
})
.draggable({
listeners: {
// call this function on every dragmove event
move: dragMoveListener,
// call this function on every dragend event
end(event) {
var textEl = event.target.querySelector('p')
textEl && (textEl.textContent =
'moved a distance of ' +
(Math.sqrt(Math.pow(event.pageX - event.x0, 2) +
Math.pow(event.pageY - event.y0, 2) | 0))
.toFixed(2) + 'px')
}
},
inertia: true,
modifiers: [
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
]
})
}
.resize-drag {
background-color: #29e;
color: white;
font-size: 20px;
font-family: sans-serif;
border-radius: 8px;
padding: 20px;
touch-action: none;
width: 120px;
/* This makes things *much* easier */
box-sizing: border-box;
}
<script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>
<div class="resize-drag">
Resize from any edge or corner
</div>

How to paste elements dragged by interaction interactjs

The behaviour is: snaps to all other draggable elements
I did as much as I could but I couldn't justify it at the intersection. does not pass to the other while applying any snap.
I want to do the snap event with the possibilities given by interact.
I have created a fiddle here: Fiddle Link
This is my JS Code:
var element = document.getElementById('draggable-element')
var x = 0; var y = 0
var targets = [
//{ x : 500, y : 350 },
//{ x : 500, y : 410 },
//{ x : 620, y : 350 },
//{ x : 620, y : 410 },
{ x : 500 },
{ x : 620 },
{ y : 350 },
{ y : 410 }
];
const mySnap = interact.modifiers.snap({
targets: targets,
range: 20,
relativePoints: [
{ x: 0 , y: 0 }, // snap relative to the element's top-left,
//{ x: 0.5, y: 0.5 }, // to the center
{ x: 1 , y: 1 } // and to the bottom-right
]
});
interact(element)
.draggable({
modifiers: [
mySnap
],
inertia: false
})
.on('dragmove', function (event) {
var target = event.target
// keep the dragged position in the data-x/data-y attributes
var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx
var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy
// translate the element
target.style.webkitTransform =
target.style.transform =
'translate(' + x + 'px, ' + y + 'px)'
// update the posiion attributes
target.setAttribute('data-x', x)
target.setAttribute('data-y', y)
})
.resizable({
// resize from all edges and corners
edges: { left: true, right: true, bottom: true, top: true },
modifiers: [
mySnap
],
inertia: false
})
.on('resizemove', function (event) {
var target = event.target
var x = (parseFloat(target.getAttribute('data-x')) || 0)
var y = (parseFloat(target.getAttribute('data-y')) || 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.webkitTransform = target.style.transform =
'translate(' + x + 'px,' + y + 'px)'
target.setAttribute('data-x', x)
target.setAttribute('data-y', y)
target.textContent = Math.round(event.rect.width) + '\u00D7' + Math.round(event.rect.height)
})
* {
margin: 0;
padding: 0;
}
#draggable-element {
width: 72px;
height: 72px;
background: yellowgreen;
position: absolute;
left: 0px;
top: 0px;
touch-action: none;
}
#guide-box {
width: 120px;
height: 60px;
background: wheat;
position: absolute;
left: 500px;
top: 350px;
}
.line-x{
position: absolute;
height: 1px;
width: 100%;
background-color: tomato;
}
.line-y{
position: absolute;
width: 1px;
height: 100%;
background-color: teal;
}
.line-x.xT-line{ top: 350px; }
.line-x.xB-line{ top: 410px; }
.line-y.yL-line{ left: 500px; }
.line-y.yR-line{ left: 620px; }
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="guide-box"></div>
<div id="draggable-element"></div>
<div class="xT-line line-x"></div>
<div class="xB-line line-x"></div>
<div class="yL-line line-y"></div>
<div class="yR-line line-y"></div>
<script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>
<script src="script.js"></script>
</body>
</html>

Click And Drag function in javascript

I'm trying to create my own click and drag function in JavaScript without the use of jquery. I know that jquery is easy to implement, but I prefer my own code. What I have, as i click the div, then move the mouse, the div moves to the same spot and doesn't implement a "dragging" look to it. I'm not sure why this is. I want my outcome to be able to move the div over the image that way I can "crop" the image based on the div, etc. My code is:
index.js
function _(element) {
return document.getElementById(element);
}
index.css
body {
background-color: rgb(33, 66, 99);
margin: 0px;
padding: 0px;
}
img {
position:absolute;
}
.selection {
width: 200px;
height: 200px;
background-color: rgb(255,255,255);
position: absolute;
}
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8"/>
<title>Image Cropping</title>
<link rel = "stylesheet" href = "index.css"/>
<script src = "index.js"></script>
</head>
<body>
<div class = "image">
<img src = "model.jpg" alt = "Model" id = "theImage"/>
<div class = "selection" id = "selection"/>
</div>
<script>
_("theImage").ondragstart = function() { return false; };
var m = _("selection");
m.addEventListener("mousedown", mouseDown, false);
window.addEventListener("mouseup", mouseUp, false);
function mouseUp() {
window.removeEventListener("mousemove", move, true);
}
function mouseDown(e) {
window.addEventListener("mousemove", move, true);
}
function move(e) {
var x = m.style.left;
var y = m.style.top;
var mouseX = e.clientX;
var mouseY = e.clientY;
m.style.top += (mouseX - x) + "px";
m.style.left += (mouseY - y) + "px";
// Also tried: m.style.top = (mouseX - x) + "px";
// And : m.style.left = (mouseY - y) + "px";
}
</script>
</body>
</html>
To add the "dragging look to it", you can:
change the cursor (cursor: move;)
keep the cursor's offset relative to the mouse
For the second one, I reused a function I created for one of my projects, for which I implemented drag and drop for mobile, not wanting to use a big library:
/*
* Returns the given element's offset relative to the document.
*/
function realOffset(elem) {
var top = 0, left = 0;
while (elem) {
top = top + parseInt(elem.offsetTop, 10);
left = left + parseInt(elem.offsetLeft, 10);
elem = elem.offsetParent;
}
return { top: top, left: left };
}
Using this function, the math becomes simple:
m.style.left = (mouseX - offset.left) + "px";
m.style.top = (mouseY - offset.top) + "px";
Full demo
_("theImage").ondragstart = function () { return false; };
var m = _("selection"), offset;
m.addEventListener("mousedown", mouseDown, false);
window.addEventListener("mouseup", mouseUp, false);
function mouseUp() { window.removeEventListener("mousemove", move, true); }
function mouseDown(e) {
// SAVE THE OFFSET HERE
offset = {
left: e.pageX - realOffset(m).left,
top: e.pageY - realOffset(m).top
};
window.addEventListener("mousemove", move, true);
}
function move(e) {
// REUSE THE OFFSET HERE
m.style.left = (e.pageX - offset.left) + "px";
m.style.top = (e.pageY - offset.top) + "px";
}
/*
* Returns the given element's offset relative to the document.
*/
function realOffset(elem) {
var top = 0, left = 0;
while (elem) {
top = top + parseInt(elem.offsetTop, 10);
left = left + parseInt(elem.offsetLeft, 10);
elem = elem.offsetParent;
}
return { top: top, left: left };
}
function _(element) { return document.getElementById(element); }
body {
background-color: rgb(33, 66, 99);
margin: 0px;
padding: 0px;
}
img {
position:absolute;
}
.selection {
width: 200px;
height: 200px;
background-color: rgba(255,255,255,.5);
position: absolute;
cursor: move;
}
<div class="image">
<img src="http://i.imgur.com/vxkljMP.jpg" alt="Model" id="theImage" />
<div class="selection" id="selection"></div>
</div>

interact js with guide line

Interact.js has a snap option to snapping element. But I don't know how to show those guide lines. I was thinking about there might be some events trggered when snapping happened, and I might use them to show those lines, but I didn't find them in the documentation.
interact doesn't support those guidelines out of the box, but you can build them relatively easy for yourself.
I built this fiddle to show the process.
The important part is this:
interact(element)
.draggable({
snap: {
targets: [
function (x, y) {
var newX = Math.round(x / 50) * 50;
var newY = Math.round(y / 50) * 50;
someFunction(newX, newY);
return {
x: newX,
y: newY
};
}],
As you can see, you can build the function that determines the snapping position (newX and newY) in regard to your current mouse position.
In this function you can also call another function. In this case I called a function to show one line if the object is at this position. Here you can get creative. You could set the position of one line Element to the current position, you could set some predefined lines and calculate which is the closest to only show that one, this depends on you business problem.
For more information about interact - snapping, look in here in the docs
might be a bit late but it still can be useful for those who struggle with alignment. Here is my complete approach:
Codepen: https://codepen.io/lakers19/pen/ZEoPpKL
const targets = []
const cleanXLine = () => {
const guideLineX = document.querySelector('.guide-line-x')
guideLineX.style.left = 0
guideLineX.style.top = 0
guideLineX.style.width = 0
guideLineX.style.height = 0
}
const cleanYLine = () => {
const guideLineY = document.querySelector('.guide-line-y')
guideLineY.style.left = 0
guideLineY.style.top = 0
guideLineY.style.width = 0
guideLineY.style.height = 0
}
const resetGuideLine = () => {
cleanXLine()
cleanYLine()
}
const handleStart = (event) => {
// get all interactive elements
targets.length = 0
const elements = document.querySelectorAll('.draggable')
elements.forEach((element) => {
const rect = element.getBoundingClientRect()
const { x, y, width, height } = rect
if (element === event.target) return
const actualX = x + window.scrollX
const actualY = y + window.scrollY
const range = 4
targets.push({
x: actualX,
range,
rect,
element,
})
targets.push({
x: actualX + width,
range,
rect,
element,
})
targets.push({
x: actualX + width / 2,
range,
rect,
element,
})
targets.push({
y: actualY,
range,
rect,
element,
})
targets.push({
y: actualY + height,
range,
rect,
element,
})
targets.push({
y: actualY + height / 2,
range,
rect,
element,
})
})
}
const drawGuideLine = (event) => {
const inRange = event.modifiers.length ? event.modifiers[0]?.inRange : false
if (inRange) {
const guideLineX = document.querySelector('.guide-line-x')
const guideLineY = document.querySelector('.guide-line-y')
const {
x: xModifier,
y: yModifier,
rect,
} = event.modifiers[0].target.source
const { x, y } = event.target.getBoundingClientRect()
if (xModifier) {
guideLineX.style.left = `${xModifier}px`
guideLineX.style.top = `${Math.min(rect.y, y)}px`
guideLineX.style.width = '1px'
guideLineX.style.height = `${Math.abs(rect.y - y)}px`
cleanYLine()
}
if (yModifier) {
console.log(rect.x - x)
guideLineY.style.left = `${Math.min(rect.x, x)}px`
guideLineY.style.top = `${yModifier - window.scrollY}px`
guideLineY.style.width = `${Math.abs(rect.x - x)}px`
guideLineY.style.height = '1px'
cleanXLine()
}
} else {
resetGuideLine()
}
}
interact('.draggable')
.draggable({
// enable inertial throwing
inertia: false,
// keep the element within the area of it's parent
modifiers: [interact.modifiers.snap({
targets: targets,
relativePoints: [
{ x: 0, y: 0 }, // snap relative to the element's top-left,
{ x: 0.5, y: 0.5 }, // to the center
{ x: 1, y: 1 }, // and to the bottom-right
],
}),
interact.modifiers.restrictRect({
restriction: 'parent',
endOnly: true
})
],
// enable autoScroll
autoScroll: true,
listeners: {
// call this function on every dragmove event
move: dragMoveListener,
start: handleStart,
// call this function on every dragend event
end (event) {
resetGuideLine()
}
}
})
function dragMoveListener (event) {
drawGuideLine(event)
var target = event.target
// keep the dragged position in the data-x/data-y attributes
var x = (parseFloat(target.getAttribute('data-x')) || 0) + event.dx
var y = (parseFloat(target.getAttribute('data-y')) || 0) + event.dy
// translate the element
target.style.transform = 'translate(' + x + 'px, ' + y + 'px)'
// update the posiion attributes
target.setAttribute('data-x', x)
target.setAttribute('data-y', y)
}
// this function is used later in the resizing and gesture demos
window.dragMoveListener = dragMoveListener
#canvas{
width: 100vw;
height: 100vh;
background: rgb(22, 197, 180);
}
.draggable {
background: rgb(71, 44, 113);
width: 60px;
height: 60px;
}
.draggable:nth-child(1){
translate: 20px 10px;
}
.draggable:nth-child(2){
translate: 50px 60px;
}
body {
display: grid;
place-items: center;
place-content: center;
height: 100%;
}
html{
height: 100%;
}
.guide-line {
pointer-events:none;
background:red;
position:fixed;
display: flex;
justify-items:space-between;
width: 0;
height:0;
left:0;
right:0;
}
.guide-line > span {
font-size: 9px;
line-height: 0;
color: red;
position: absolute;
}
.guide-line-x > span {
transform: translateX(-50%);
left: 50%;
}
.guide-line-y{
flex-direction:row;
}
.guide-line-x {
flex-direction:column;
}
.guide-line-y > span{
transform: translateY(-50%);
top: 50%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/interact.js/1.10.17/interact.min.js"></script>
<div id="canvas">
<div class="draggable" ></div>
<div class="draggable"> </div>
<div class="guide-line-y guide-line">
<span style="opacity:0" >x</span>
<span>x</span>
</div>
<div class="guide-line-x guide-line">
<span style="opacity:0">x</span>
<span>x</span>
</div>
</div>

Categories

Resources