Html Canvas lag when Left Mouse is down and moving on Chrome - javascript

I have created a canvas and I have added mouse events to it:
canvas = document.getElementById('canvas');
context = canvas.getContext('2d');
canvas.width = screenWidth;
canvas.height = screenHeight;
...
// CALLED AT START:
function setup() {
// Mouse movement:
document.onmousemove = function(e) {
e.preventDefault();
target.x = e.pageX;
target.y = e.pageY;
angle = Math.atan2((target.y - localPlayer.getY()),
(target.x - localPlayer.getX()));
// Distance to mouse Check:
var dist = Math.sqrt((localPlayer.getX() - target.x)
* (localPlayer.getX() - target.x) + (localPlayer.getY() - target.y)
* (localPlayer.getY() - target.y));
var speedMult = dist / (canvas.height / 4);
socket.emit("update", {
...
});
}
document.onmousedown = function(e) {
e.preventDefault();
}
}
Now the issue is when I hold down the only left mouse button and move the mouse at the same time, my game lags a lot. Simply moving the mouse causes no lag. I have tested this on chrome and on firefox. It seems that I can only recreate the issue on chrome. Using the middle mouse button or right button has the same behaviour in the game and cause no lag. Only when using the left mouse button causes lag.
I have looked around for answers and found that I should prevent default behaviour like so:
e.preventDefault();
But that did not resolve the issue. I have also tried to update a number on the screen that represents the mouse position. And it updated normally. Only the game itself was lagging. Could it be that the onMouseMoved is never called whilst the left button is held down? But then why is it called with the middle and right button?
The issue should be with the code I a calling inside of the move method, because it works fine when I am not holding down the left key, and it works well on firefox. There must be something else going on.
EDIT: I decided to a recording on chrome to see what is going on. Here is the result:
What's really odd, when I press the middle mouse button or the right button, the game does the same thing, but it does not lag at all. What are you doing chrome?
EDIT: Test it out here: www.vertix.io note that not everyone seems to be able to reproduce this issue.
Thank you for your time.

When you hold down the left mouse button and move it in the same time, you are dragging.
Edit: In some versions of Chrome, there is a bug (when I posted this answer I had it, now I don't), which causing the drag events to be fired even without the element having the draggable attribute. Normally, drag events should only be fierd from elements which have the draggable attribute set to true (except images and anchors who are drragable by default).
According to the MDN, when drag events are being fired, mouse events, such as mousemove, are not, which means that your function isn't being called.
A possible solution are to use the same function for both drag and mousemove events:
function mouseMove(e) {
//do your things here
...
}
document.addEventListener('mousemove', mouseMove);
document.addEventListener('drag', mouseMove);
Note: If you'll use the same function for both events, you should be aware of which properties of the event you're using in the function, because of the difference between the drag and mousemove events. The two events doesn't contains the exact same properties and the behavior of some properties may not be the same in both of them.

Have you considered throttling?
Check out https://blog.toggl.com/2013/02/increasing-perceived-performance-with-_throttle/

You have the mouse event on the document. As we can not see what you have on the document it is hard to know if that is a cause of your problems.
Try moving the mouse event to the canvas only, as that is the only place you need it I presume. No point handling events for the document if its not part of the game, plus document is last on the list if child elements have events attached. They go first and then it bubbles up to yours.
As it looks like you are using a framework of some type there is in all possibility another mouse event listener that is part of the frame work that may be slowing you down by not preventing default. You will have to search the framework to see if it has a listener for any of the mouse events.
And use addEventListener rather than directly attaching the event via .onmousedown = eventHandler
eg canvas.addEventListener("mousedown",eventHandler);
And add the event listener to the element you need it for, not the document.

function mouseMove(e) {
//do your things here
...
}
document.onmousemove = mouseMove;
document.ondrag = function(e) {
mouseMove(e);
//do another things
...
}

Related

Javascript "mousemove" event sometimes doesn't fire

I have a codepen.io example I've been working on to create a pure js collapsible side panel that is also resizable. The example works 70% of the time, but every-so-often resizing the panel will result in no "mousemove" events being emitted and the panel simply freezes (i.e. not tracking the mouse x position). I can't find the issue myself, wondering if anyone can shed some light on this one. Maybe there is a better approach to adding / removing event listeners for this kind of work that I've not thought off.
The meat of the js logic looks like the following:
const divider = document.querySelector(".divider");
const startSlide = event => {
const viewportWidth = window.visualViewport.width;
const width = viewportWidth - event.clientX;
divider.style.width = `${width}px`;
};
const stopSlide = event => {
window.removeEventListener("pointermove", startSlide, true);
window.removeEventListener("pointerup", stopSlide, true);
};
const initSlide = event => {
window.addEventListener("pointermove", startSlide, true);
window.addEventListener("pointerup", stopSlide, true);
};
divider.addEventListener("pointerdown", initSlide, true);
To reproduce the issue just attempt to slide the divider panel left and right a couple of times, eventually, it will bug!
broken codepen example
Looks like it becomes more reproducible if you quickly drag up after selecting the dividing bar. Adding a drag event listener shows that the drag on the divider is consuming the event
divider.addEventListener("drag", function( event ) {
console.log("DRAG");
}, true);
You probably need to prevent the element from consuming the drag event
#kriddy800 put me on the right track with looking at drag events. The fix for this particular issue and many related dragging type problems is to cancel the native onDragStart event, which in turn will stop future onDrag events from firing and masking the wanted onMouseMove events.
divider.ondragstart = () => false;
A great explanation of everything drag related: https://javascript.info/mouse-drag-and-drop

Mousedown triggers event, then when mouse is moved off element and mouseup fires it doesn't work

http://jsfiddle.net/63Y54/2/
In the example above when the user clicks and drags left or right off the canvas while holding the mouse button down and then takes their finger off the mouse the oscillator note hangs. I want to fix this. I am curious if their is a simple way to do something like..
if (mouseup == !htmlElement){
then....
}
In this case the html element would be the canvas element as that is what the user is clicking on.
As an attempt to fix this I made the body element encompass the page by setting its CSS width and height to 100%.
I then created a function that selected the body element with a mouseup click handler that launches the oscillator.stop() method. This only works when the user moved their mouse to the side of the page but when they moved down it still creates a hanging note.
This pseudo solution is here:
http://jsfiddle.net/63Y54/5/
I think this similar question answers yours.
jQuery detect mousedown inside an element and then mouseup outside the element
Here is the code from it from a guy named Mike:
var isDown = false;
$("#element").mousedown(function(){
isDown = true;
});
$(document).mouseup(function(){
if(isDown){
//do something
isDown = false;
}
There is additional code handling fringe cases in thelink as well.

Mousedown and mousemove perform inconsistently in Meteor

I have an one page app in Meteor.
I want to track when whether a bookmarklet (in the form of a <a> tag containing an image) has been dragged towards the bookmarks bar.
I'm using a combination of mousedown, mousemove, and mouseup to try to track the drag.
Template.myTemplate.events = {
'mousedown': function(){
Session.set('dragging', true)
console.log('drag starts')
},
'mouseup': function(){
if (Session.get('dragging') == true && event.y < 10){
// The result i want
}
Session.set('dragging', false)
console.log('drag stops')
}
}
The drag starts well enough, but soon after the mouse leaves the <a> tag it just seems to baulk, and mouseup doesn't register as it should.
The logic works as it should if I return false after mouseup and mousedown - ie. I can move the mouse far and wide after mousedown, and watch for event.y being < 10 and there's no baulk - but then the code does not have the desired effect of the user being able to drag the <a> tag.
Do you have any ideas?
'mousedown': function(){
You're doing mousedown on the template, it should be on the a element.
So, do this instead:
'mousedown a': function(){
Or choose the right a element here.
sorry for the delay, but i could only see now kk
But you can get your event data from the bank with mousedown (I believe you already do that), and add the mousemove where you want to drop your event. It's not quite the right way to implement it, but it can solve

How to find out the actual event.target of touchmove javascript event?

=I am trying to develop a simple drag/drop UI in my web application. An item can be dragged by a mouse or a finger and then can be dropped into one of several drop zones. When an item is dragged over a drop zone (but not yet released), that zone is highlighted, marking safe landing location. That works perfectly fine with mouse events, but I'm stuck with touchstart/touchmove/touchend family on the iPhone/iPad.
The problem is that when an item's ontouchmove event handler is called, its event.touches[0].target always points to the originating HTML element (the item) and not the element which is currently under the finger. Moreover, when an item is dragged by finger over some drop zone, that drop zone's own touchmove handlers isn't called at all. That essentially means I can't determine when a finger is above any of the drop zones, and therefore can't highlight them as needed. At the same time, when using a mouse, mousedown is correctly fired for all HTML elements under the cursor.
Some people confirm that it's supposed to work like that, for instance http://www.sitepen.com/blog/2008/07/10/touching-and-gesturing-on-the-iphone/:
For those of you coming from the normal web design world, in a normal mousemove event, the node passed in the target attribute is usually what the mouse is currently over. But in all iPhone touch events, the target is a reference to the originating node.
Question: is there any way to determine the actual element under a finger (NOT the initially touched element which can be different in many circumstances)?
That's certainly not how event targets are supposed to work. Yet another DOM inconsistency that we're probably all now stuck with forever, due to a vendor coming up with extensions behind closed doors without any review.
Use document.elementFromPoint to work around it.
document.elementFromPoint(event.clientX, event.clientY);
The accepted answer from 2010 no longer works: touchmove does not have a clientX or clientY attribute. (I'm guessing it used to since the answer has a number of upvotes, but it doesn't currently.)
Current solution is:
var myLocation = event.originalEvent.changedTouches[0];
var realTarget = document.elementFromPoint(myLocation.clientX, myLocation.clientY);
Tested and works on:
Safari on iOS
Chrome on iOS
Chrome on Android
Chrome on touch-enabled Windows desktop
FF on touch-enabled Windows desktop
Does NOT work on:
IE on touch-enabled Windows desktop
Not tested on:
Windows Phone
I've encountered the same problem on Android (WebView + Phonegap). I want to be able to drag elements around and detect when they are being dragged over a certain other element.
For some reason touch-events seem to ignore the pointer-events attribute value.
Mouse:
if pointer-events="visiblePainted" is set then event.target will point to the dragged element.
if pointer-events="none" is set then event.target will point to the element under the dragged element (my drag-over zone)
This is how things are supposed to work and why we have the pointer-events attribute in the first place.
Touch:
event.target always points to the dragged element, regardless of pointer-events value which is IMHO wrong.
My workaround is to create my own drag-event object (a common interface for both mouse and touch events) that holds the event coordinates and the target:
for mouse events I simply reuse the mouse event as is
for touch event I use:
DragAndDrop.prototype.getDragEventFromTouch = function (event) {
var touch = event.touches.item(0);
return {
screenX: touch.screenX,
screenY: touch.screenY,
clientX: touch.clientX,
clientY: touch.clientY,
pageX: touch.pageX,
pageY: touch.pageY,
target: document.elementFromPoint(touch.screenX, touch.screenY)
};
};
And then use that for processing (checking whether the dragged object is in my drag-over zone). For some reason document.elementFromPoint() seems to respect the pointer-events value even on Android.
Try using event.target.releasePointerCapture(event.pointerId) in the pointerdown handler.
We're now in 2022, this is intended and specified behavior - it's called "Implict Pointer Capture"
See the W3 spec on Pointer Events
Direct manipulation devices should behave exactly as if setPointerCapture was called on the target element just before the invocation of any pointerdown listeners. The hasPointerCapture API may be used (eg. within any pointerdown listener) to determine whether this has occurred.
elementFromPoint is a possible solution, but it seems you can also use releasePointerCapture as shown in the following demo. Touching and holding on the green div will get mouse move events for targets outside of it, whereas the red div has the default behavior.
const outputDiv = document.getElementById('output-div');
const releaseDiv = document.getElementById('test-release-div');
const noreleaseDiv = document.getElementById('test-norelease-div');
releaseDiv.addEventListener('pointerdown', function(e) {
outputDiv.innerHTML = "releaseDiv-pointerdown";
if (e.target.hasPointerCapture(e.pointerId)) {
e.target.releasePointerCapture(e.pointerId);
}
});
noreleaseDiv.addEventListener('pointerdown', function(e) {
outputDiv.innerHTML = "noreleaseDiv-pointerdown";
});
document.addEventListener('pointermove', function(e) {
outputDiv.innerHTML = e.target.id;
});
<div id="output-div"></div>
<div id="test-release-div" style="width:300px;height:100px;background-color:green;touch-action:none;user-select:none">Touch down here and move around, this releases implicit pointer capture</div>
<div id="test-norelease-div" style="width:300px;height:100px;background-color:red;touch-action:none;user-select:none">Touch down here and move around, this doesn't release implicit pointer capture<div>
So touch events have different "philosophy" when it comes to how they interact:
Mouse moves = "hover" like behavior
Touch moves = "drags" like behavior
This difference comes from the fact that there can not be a touchmove without touchstart event preceding it as a user has to touch screen to start this interaction. With mouse of course a user can mousemove all over the screen without ever pressing buttoon (mousedown event)
This is why basically we can't hope to use things like hover effects with touch:
element:hover {
background-color: yellow;
}
And this is why when user touches the screen with 1 finger the first event (touchstart) acquires the target element and the subsequent events (touchmove) will hold the reference to the original element where touch started. It feels wrong but there is this logic that you might need original target info as well. So ideally in future there should be both (source target and current target) available.
So common practice of today (2018) where screens can be mouse AND touch at the same time is still to attach both listeners (mouse and touch) and then "normalize" event coordinates and use above mentioned browser api to find element in those coordinates:
// get coordinates depending on pointer type:
var xcoord = event.touches? event.touches[0].pageX : event.pageX;
var ycoord = event.touches? event.touches[0].pageY : event.pageY;
// get element in coordinates:
var targetElement = document.elementFromPoint(xcoord, ycoord);
// validate if this is a valid element for our case:
if (targetElement && targetElement.classList.contains("dropZone")) {
}
JSP64's answer didn't fully work since event.originalEvent always returned undefined. A slight modification as follows works now.
var myLocation = event.touches[0];
var realTarget = document.elementFromPoint(myLocation.clientX, myLocation.clientY);

Stop drag-n-drop event with Raphaeljs

I am trying to simulate the swipe event from the iPhone with Raphaeljs.
To do so, I am using the drag and drop event.
To simulate the event in have a method in the move event that calculate the distance between my object and the mouse position. If the mouse goes after that distance I want to stop the drag and drop event. This is where I'm stuck.
Here is the code:
var start = function (event) {
},
move = function (event) {
inrange = self.inRange (circle.attr("cx"), circle.attr("cy"), event.pageX, event.pageY);
if(inrange == false){
//Stop draging!
}
},
up = function () {
circle.animate({ r: 40, "stroke-width": 1 }, 200);
};
circle.drag(move, start, up);
In the move method I need the stop the drag event or simulate a mouseup. How can I do so?
From the documentation:
To unbind events use the same method names with “un” prefix, i.e. element.unclick(f);
and
To unbind drag use the undrag method.
So I would think circle.undrag(); should work.
#Gregory You can use a JS closure to detect if the circle needs to stop dragging. And #apphacker there is a known issue in Raphael that prevents undrag from working. It is scheduled to be fixed in 2.0, but that doesn't have a release date as of yet (and the bug isn't fixed in the beta code, despite the ticket saying it is.
I recommend manually implementing the mousedown, mouseup and mousemove events using jQuery, as per #floyd's recommendation, and add a JS closure check in your move function to see if the circle needs to stop being dragged yet or not.'
It also occurs to me that your original post was last edited in Nov '10, so you might have moved on since then ;)
If you can include jQuery you can use trigger on "mouseup." If you can't include jQuery maybe just take a look at the source and lift that one function?
UPDATE
After some brief googling I came across this implementation. Only tested in in Chrome though:
function fireEvent(element,event){
if (document.createEventObject){
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
} else{
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}

Categories