I am trying to learn how to make a div in an HTML page draggable by pure JavaScript not by using external library so I tried some of mine techniques but I failed to make it a proper draggable object. I am sure I'm missing something important in my code so I want to know what is the basic idea behind draggable object. I was trying to achieve it by setting some startX and startY position and making the Div position absolute and setting the left and top of div by css as
p.style.left = (e.clientX-startX) + 'px';
p.style.top = (e.clientY-startY) + 'px';
// where p is the element i am trying to make draggable
You should not forget to save p's initial position and add it each time to make sure you're doing relative calculations. Currently, you assume p is always at position (0, 0) when starting dragging.
Secondly, cancelling the selectstart event makes for no ugly selection being created when dragging.
I updated your code a bit to this effect: http://jsfiddle.net/rLegF/1/.
var p = document.getElementById("p"),
startX, startY,
origX, origY,
down = false;
document.documentElement.onselectstart = function() {
return false; // prevent selections
};
p.onmousedown = function(e) {
startX = e.clientX;
startY = e.clientY;
origX = p.offsetLeft;
origY = p.offsetTop;
down = true;
};
document.documentElement.onmouseup = function() {
// releasing the mouse anywhere to stop dragging
down = false;
};
document.documentElement.onmousemove = function(e) {
// don't do anything if not dragging
if(!down) return;
p.style.left = (e.clientX - startX) + origX + 'px';
p.style.top = (e.clientY - startY) + origY + 'px';
};
Edit: You could also combine startX and origX since you're basically always doing - startX + origX: http://jsfiddle.net/rLegF/2/.
What you're then doing is calculating the mouse position with respect to the top left-hand corner of the element, and then set the position to the new mouse position minus that old mouse position. Perhaps it's a little more intuitive that way.
I cleaned up some more as well.
Related
I have 2 canvas elements on top of each other and i want to move the canvas element on top on mouse drag but it produces weird results.
This is my code for the events (the variable cvs is the canvas element which is on top of other canvas element)
var drag = false;
cvs.addEventListener('mousedown', function(event) {
drag = true;
});
cvs.addEventListener('mouseup', function(event) {
drag = false;
});
cvs.addEventListener('mousemove', function(event) {
if (drag) {
const rect = cvs.getBoundingClientRect()
const x = event.clientX - rect.left;
const y = event.clientY - rect.top;
cvs.style.left = x + "px";
cvs.style.top = y + "px";
console.log(x, y);
}
});
When I drag the top canvas it starts to flicker back-and-forth between 2 positions
At a glance, it looks like you are using a relative value to set an absolute position.
So, first iteration, the left position updates to x, then the next iteration you subtract the last value of x from the mouse position. I think this is going to move it on and off screen.
say, clientX is at 100, and left is at 10.
T1 -> x = 100 - 10 = 90,
T2 -> x = 100 - 90 = 10.
Hence the "flickering"
What you want to do, is take the relative movement value of the mouse and move the element by the same amount.
So on mouse down, record the mouse initial position and element initial position.
Subtract the initial mouse position from the mouse position on each mouse move iteration, and assign the initial element position plus the relative change to the element.
var initialPosition = null
var initialMouseCoords = null
cvs.addEventListener('mousedown', function(event) {
initialPosition = cvs.getBoundingClientRect()
initialMouseCoords = {clientX: event.clientX, clientY: event.clientY}
});
cvs.addEventListener('mouseup', function(event) {
initialPosition = null
initialMouseCoords = null
});
cvs.addEventListener('mousemove', function(event) {
if (initialMouseCoords) {
const dx = event.clientX - initialMouseCoords.clientX;
const dy = event.clientY - initialMouseCoords.clientY;
cvs.style.left = initialPosition.left + dx;
cvs.style.top = initialPosition.top + dy;
console.log(dx, dy);
}
});
Bare in mind there are drag events depending on your use case, you might want to explore that as an alternative.
I have a <canvas> element that spans the width and height of my webpage, like a background. It has interactive elements that rely on mouse coordinates. When the canvas was in it's own block (i.e. nothing over it) the interactive elements worked fine. But now that it's got divs over it it's not picking up any of the mouse interactions.
Below is my javascript code for the mousemove stuff. Why would items on top affect it picking up mouse xy coordinates, and how do I fix it?
var mouse = {x:-100,y:-100};
var mouseOnScreen = false;
canvas.addEventListener('mousemove', MouseMove, false);
canvas.addEventListener('mouseout', MouseOut, false);
var MouseMove = function(e) {
if (e.layerX || e.layerX == 0) {
//Reset particle positions
mouseOnScreen = true;
mouse.x = e.layerX - canvas.offsetLeft;
mouse.y = e.layerY - canvas.offsetTop;
}
}
var MouseOut = function(e) {
mouseOnScreen = false;
mouse.x = -100;
mouse.y = -100;
}
var update = function(){
var i, dx, dy, sqrDist, scale;
//...... this chunk is the only part of the function that references the mouse
dx = parts[i].x - mouse.x;
dy = parts[i].y - mouse.y;
sqrDist = Math.sqrt(dx*dx + dy*dy);
if (sqrDist < 20){
parts[i].r = true;
}
.....
}
If you don't need the top divs to be mouse-aware then set their CSS pointer-events:none; and the mouse events will filter down to your canvas underneath. Questioner needs responsive buttons placed over the canvas.
If the top divs do need to respond to mouse events, you might have to listen for mouse events on the window and convert those to canvas coordinates that your app can respond to.
You can listen for mousemove events on the window and get all moves -- even when over button elements. Also listen for mouseout events on the window. Since the canvas spans the window, you know mouseout happens when mouseevent.clientX & mouseevent.clientY report the coordinates are outside the window
Solved the issue with this code I found from another SO answer that I modified a bit.
function simulate(e) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("mousemove", true, true, window,
0, e.screenX, e.screenY, e.clientX, e.clientY, false, false, false, false, 0, null);
canvas.dispatchEvent(evt);
console.log("Emulated.");
}
$("body > section, body > header").each(function(){
this.addEventListener("mousemove", simulate);
});
Also, as a side note. Changed original layerX and layerY in mouse code to offsetX and offsetY to work in firefox (in addition to all other browsers)
I need to move the whole canvas by touch like the movement of drag and drop
the position of the canvas is supposed to be from
flattenCanvas.height = canvas.height = SCREEN_HEIGHT - menu.container.offsetHeight;
canvas.style.position = 'absolute';
canvas.style.top = menu.container.offsetHeight+'px';
canvas.style.left = -(menu.container.offsetHeight)/2+'px';
context = canvas.getContext("2d");
and the touches for drawing or scrolling is from this
else if(event.touches.length == 1) ////one finger scrolling
{
canvas.style.top = (((event.touches[0].pageY)))+'px';
canvas.style.left = (((event.touches[0].pageX)))+'px';
}
from the last code i can move the canvas by one touch but it is not really dragging.
how to fix the canvas screen movement?
this is a demo of the webapp demo
Based on these docs, the event you want to handle is touchmove.
The code in your question appears to live inside a touchstart handler; just execute the same code in a touchmove handler to continuously update during the 'drag'.
Update
What you are trying to do is offset a target element (in this case, a canvas element) by the difference between a touch event's "current" (touchmove) and "start" (touchstart) positions. To do so, you should capture the positions of both target and touch in a touchstart handler. Then, in your touchmove handler, take the difference in touch positions, and add them to the target's start position. This might look like:
// Get your draggable element from the DOM
var draggable = document.getElementById('draggable');
// Set initial position.
draggable.style.position = 'relative'; // 'absolute' also works.
draggable.style.top = '0';
draggable.style.left = '0';
var targetStartX, targetStartY, touchStartX, touchStartY;
// Capture original coordinates of target and touch
function dragStart(e) {
targetStartX = parseInt(e.target.style.left);
targetStartY = parseInt(e.target.style.top);
touchStartX = e.touches[0].pageX;
touchStartY = e.touches[0].pageY;
}
function dragMove(e) {
// Calculate touch offsets
var touchOffsetX = e.touches[0].pageX - touchStartX,
touchOffsetY = e.touches[0].pageY - touchStartY;
// Add touch offsets to original target coordinates,
// then assign them to target element's styles.
e.target.style.left = targetStartX + touchOffsetX + 'px';
e.target.style.top = targetStartY + touchOffsetY + 'px';
}
draggable.addEventListener('touchstart', dragStart);
draggable.addEventListener('touchmove', dragMove);
Here's a live demo.
I'm trying to drag an element with just vanilla JavaScript.
When I drag the element I want it to move in sync with where the mouse pointer clicked, I can move it via the elements top left corner which is simple enough but I'm having issues moving it from the exact point of click.
Javascript
function mouseMove(e){
if(dragging){
boxPos(sq,e);
}
}
function boxPos(el,e){
box = el.getBoundingClientRect();
mouse_top = e.clientY;
mouse_left = e.clientX;
diff_x = mouse_left - box.left;
diff_y = mouse_top - box.top;
el.style.top = (mouse_top + diff_y) +"px";
el.style.left = (mouse_left + diff_x) +"px";
}
sq is a div, e is the event.
What im trying to do is calculate the position of the mouse, work out the difference from the top/left and add it to the top left but I'm getting undesired results. See fiddle
I know it has been passed some years but, testing the Fiddle, I figured out that (at least to me) the answer isn't exactly what the OP was looking for. That's because in the response's Fiddle the div is moved perfectly but it's moved always on its origin (0,0) and not where it was exactly clicked.
The solution is actually quite simple.
You are calculating the diff_x and diff_y on every mousemove event. But the mouse pointer position while moving is always fixed in relation to the div at the very start of the mousedown event until firing the mouseup event, right? So, just declare the diffs' variables globally and calculate them on the mousedown event.
Then, change the following code:
function boxPos(el,e){
box = el.getBoundingClientRect();
mouse_top = e.clientY;
mouse_left = e.clientX;
diff_x = mouse_left - box.left;
diff_y = mouse_top - box.top;
el.style.top = (mouse_top + diff_y) +"px";
el.style.left = (mouse_left + diff_x) +"px";
}
To:
function boxPos(el,e){
box = el.getBoundingClientRect();
mouse_top = e.clientY;
mouse_left = e.clientX;
el.style.top = (mouse_top - diff_y) +"px";
el.style.left = (mouse_left - diff_x) +"px";
}
The diffs' math is done on the mousedown event, so we don't need it anymore. Thus, this will stop the flickering.
Besides that, as the diffs will always be positive, we just subtract the diffs from the corresponding mouse coordinates to place the div taking into account the difference calculated (because the mouse pointer must be on top of the div to trigger the mousedown event, then e.clientY >= sq.style.top and e.clientX >= sq.style.left will be always true). This last step is the one that moves the element on exact mouse point.
This logic may be used on other "dragging events", like the dragstart and drag events, touchstart and touchmove events and pointerdown and pointermove events as well (with some adaptation, of course). So, since this kind of behaviour may be relevant, I decided to post this answer. I hope it helps future readers.
Here's the OP's modified Fiddle.
A quick hotfix would be:
change
el.style.top = (mouse_top + diff_y) +"px";
el.style.left = (mouse_left + diff_x) +"px";
to
el.style.top = (Number(el.style.top.split("px")[0]) + diff_y) +"px";
el.style.left = (Number(el.style.left.split("px")[0]) + diff_x) +"px";
or
el.style.top = (Number(el.style.top.replace("px", "")) + diff_y) +"px";
el.style.left = (Number(el.style.left.replace("px", "")) + diff_x) +"px";
You need to move that div from its old position to the new one using the old coordinates and the calculated difference. To get the old position I used the current top and left setting, removed the "px" from it and converted it to a number. This is necessary to avoid string concatenation (top and left are string values).
Your program has another bug ... you currently can't stop the dragging mode.
Edit
To remove the drag "stop" bug you could subtract 1 pixel from the new value, so the mouse pointer would still be inside the div and the mouse up event will be triggered correctly.
You can do that like this:
el.style.top = ((Number(el.style.top.replace("px", "")) - 1) + diff_y) +"px";
el.style.left = ((Number(el.style.left.replace("px", "")) - 1) + diff_x) +"px";
Here is the new Fiddle.
This question already has answers here:
How do I get the coordinates of a mouse click on a canvas element? [duplicate]
(22 answers)
Closed 3 years ago.
Is there a way to get the location mouse inside a <canvas> tag? I want the location relative to to the upper right corner of the <canvas>, not the entire page.
The accepted answer will not work every time. If you don't use relative position the attributes offsetX and offsetY can be misleading.
You should use the function: canvas.getBoundingClientRect() from the canvas API.
function getMousePos(canvas, evt) {
var rect = canvas.getBoundingClientRect();
return {
x: evt.clientX - rect.left,
y: evt.clientY - rect.top
};
}
canvas.addEventListener('mousemove', function(evt) {
var mousePos = getMousePos(canvas, evt);
console.log('Mouse position: ' + mousePos.x + ',' + mousePos.y);
}, false);
Easiest way is probably to add a onmousemove event listener to the canvas element, and then you can get the coordinates relative to the canvas from the event itself.
This is trivial to accomplish if you only need to support specific browsers, but there are differences between f.ex. Opera and Firefox.
Something like this should work for those two:
function mouseMove(e)
{
var mouseX, mouseY;
if(e.offsetX) {
mouseX = e.offsetX;
mouseY = e.offsetY;
}
else if(e.layerX) {
mouseX = e.layerX;
mouseY = e.layerY;
}
/* do something with mouseX/mouseY */
}
Also note that you'll need CSS:
position: relative;
set to your canvas tag, in order to get the relative mouse position inside the canvas.
And the offset changes if there's a border
I'll share the most bulletproof mouse code that I have created thus far. It works on all browsers will all manner of padding, margin, border, and add-ons (like the stumbleupon top bar)
// Creates an object with x and y defined,
// set to the mouse position relative to the state's canvas
// If you wanna be super-correct this can be tricky,
// we have to worry about padding and borders
// takes an event and a reference to the canvas
function getMouse = function(e, canvas) {
var element = canvas, offsetX = 0, offsetY = 0, mx, my;
// Compute the total offset. It's possible to cache this if you want
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
// Add padding and border style widths to offset
// Also add the <html> offsets in case there's a position:fixed bar (like the stumbleupon bar)
// This part is not strictly necessary, it depends on your styling
offsetX += stylePaddingLeft + styleBorderLeft + htmlLeft;
offsetY += stylePaddingTop + styleBorderTop + htmlTop;
mx = e.pageX - offsetX;
my = e.pageY - offsetY;
// We return a simple javascript object with x and y defined
return {x: mx, y: my};
}
You'll notice that I use some (optional) variables that are undefined in the function. They are:
stylePaddingLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingLeft'], 10) || 0;
stylePaddingTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['paddingTop'], 10) || 0;
styleBorderLeft = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderLeftWidth'], 10) || 0;
styleBorderTop = parseInt(document.defaultView.getComputedStyle(canvas, null)['borderTopWidth'], 10) || 0;
// Some pages have fixed-position bars (like the stumbleupon bar) at the top or left of the page
// They will mess up mouse coordinates and this fixes that
var html = document.body.parentNode;
htmlTop = html.offsetTop;
htmlLeft = html.offsetLeft;
I'd recommend only computing those once, which is why they are not in the getMouse function.
For mouse position, I usually use jQuery since it normalizes some of the event attributes.
function getPosition(e) {
//this section is from http://www.quirksmode.org/js/events_properties.html
var targ;
if (!e)
e = window.event;
if (e.target)
targ = e.target;
else if (e.srcElement)
targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
// jQuery normalizes the pageX and pageY
// pageX,Y are the mouse positions relative to the document
// offset() returns the position of the element relative to the document
var x = e.pageX - $(targ).offset().left;
var y = e.pageY - $(targ).offset().top;
return {"x": x, "y": y};
};
// now just make sure you use this with jQuery
// obviously you can use other events other than click
$(elm).click(function(event) {
// jQuery would normalize the event
position = getPosition(event);
//now you can use the x and y positions
alert("X: " + position.x + " Y: " + position.y);
});
This works for me in all the browsers.
EDIT:
I copied the code from one of my classes I was using, so the jQuery call to this.canvas was wrong. The updated function figures out which DOM element (targ) caused the event and then uses that element's offset to figure out the correct position.
GEE is an endlessly helpful library for smoothing out troubles with canvas, including mouse location.
Simple approach using mouse event and canvas properties:
JSFiddle demo of functionality http://jsfiddle.net/Dwqy7/5/
(Note: borders are not accounted for, resulting in off-by-one):
Add a mouse event to your canvas
canvas.addEventListener("mousemove", mouseMoved);
Adjust event.clientX and event.clientY based on:
canvas.offsetLeft
window.pageXOffset
window.pageYOffset
canvas.offsetTop
Thus:
canvasMouseX = event.clientX - (canvas.offsetLeft - window.pageXOffset);
canvasMouseY = event.clientY - (canvas.offsetTop - window.pageYOffset);
The original question asked for coordinates from the upper right (second function).
These functions will need to be within a scope where they can access the canvas element.
0,0 at upper left:
function mouseMoved(event){
var canvasMouseX = event.clientX - (canvas.offsetLeft - window.pageXOffset);
var canvasMouseY = event.clientY - (canvas.offsetTop - window.pageYOffset);
}
0,0 at upper right:
function mouseMoved(event){
var canvasMouseX = canvas.width - (event.clientX - canvas.offsetLeft)- window.pageXOffset;
var canvasMouseY = event.clientY - (canvas.offsetTop - window.pageYOffset);
}
I'd use jQuery.
$(document).ready(function() {
$("#canvas_id").bind( "mousedown", function(e){ canvasClick(e); } );
}
function canvasClick( e ){
var x = e.offsetX;
var y = e.offsetY;
}
This way your canvas can be anywhere on your page, relative or absolute.
Subtract the X and Y offsets of the canvas DOM element from the mouse position to get the local position inside the canvas.