I am trying to make an HTML5 game that as long as the player is pressing the LMB, the bullets keep spawning, and once LMB is released, the shooting stops. This is my function:
document.onclick = function(mouse){
console.log("Shoot");
}
Only once the LMB is released, that message is showing up in the console log.
I did look over stackoverflow and found this:
Qt mouseMoveEvent only when left mouse button is pressed
But I failed to integrate it into my canvas... it just won't do anything.
Thank you for your time.
If you need to execute code when the mouse is pressed you should be using mousedown instead of onclick.
Check the Mouse Events examples on w3c. http://www.w3schools.com/js/js_events_examples.asp
"onclick" calls the function on mouse click up. You need a more specific event listener.
What your looking for, assuming your use case is accurate, is "onmousedown".
See this link for more info: http://www.w3schools.com/jsref/event_onmousedown.asp
Simply replace "onclick" with "onmousedown".
Hope that helps!!
The onclick method is invoked when you release the mouse button instead of being held down. What you need is the mousedown method.
Also, you need to reword your question a bit. As I understand,
you want something to happen while the mouse key is being held
down.
To do that, you need to invoke the mousedown activity in some reasonable interval.
var mousedownID = -1; //Global ID of mouse down interval
function mousedown(event) {
if(mousedownID==-1) //Prevent multimple loops!
mousedownID = setInterval(whilemousedown, 100 /*execute every 100ms*/);
}
function mouseup(event) {
if(mousedownID!=-1) { //Only stop if exists
clearInterval(mousedownID);
mousedownID=-1;
}
}
function whilemousedown() {
/*put your code here*/
/* i.e, whatever you what to keep on happening while the button is down*/
}
//Assign events
document.addEventListener("mousedown", mousedown);
document.addEventListener("mouseup", mouseup);
//Also clear the interval when user leaves the window with mouse
document.addEventListener("mouseout", mouseup);
Related
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
...
}
I am creating a basic text window in easeljs. The text window has up and down scroll arrows to enable the scrolling of the text. I do this simply by listening for a click on the up or down button and then moving the y coordinates of the text box on the click.
The problem I have is that it only moves once per click. If I have a lot of text to scroll, I have to click a lot of times. What I want is to be able to click and hold the button and have the listener repeat the action whilst the mouse is down?
Here's my simplified code attached to the down button:
btn_down.on("mousedown", function(evt) {
content.y -= 20;
game.stage.update();
});
I have tried mousedown and click, but it still only seems to fire once.
The mousedown event fires once (when you press your mouse button). If you want to loop an event while the mouse is down, either set an interval when the mouse is pressed (and clear it when it is released), or toggle a property that causes an update during a tick.
http://jsfiddle.net/lannymcnie/t7uz2v6m/
shape.on("mousedown", handlePress);
shape.on("pressup", handleRelease);
var pressed = false;
function handlePress(event) { pressed = true; }
function handleRelease(event) { pressed = false; }
function tick(event) {
if (pressed) { shape2.x += 1; }
stage.update(event);
}
Note that I use the "pressup" event instead of the mouseup equivalent (click), because if you roll out and release, the "pressup" event still fires.
Cheers.
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.
I've downloaded a JQuery plugin for a mousehold event.
http://remysharp.com/2006/12/15/jquery-mousehold-event/
I have this div that calls for mousemove event:
div.addEventListener('mousemove',function() {
//things
});
whenever I call the mousehold event like this:
var value = 0;
$(div).mousehold(function() {
value += 20;
$(div).html(value);
});
it would work. But if I start moving (thus, calling the mousemove event) while onmousehold, the value does not increase anymore, meaning, it stopped calling the mousehold event even if I got my left click still on hold.
How can I make it happen that when I do a mousemove, the mousehold event still works? tnx!
What you're asking (at least, what I think you're asking), is simple enough with some basic logic.
By binding the mousedown, mousemove, and mouseup and setting a flag for the "down" state of the mouse, this can easily be done: JSFiddle
You could use the event object like so:
div.addEventListener('mousemove', function(event) {
// `event.buttons` gets the state of the mouse buttons
// 0 = not pressed, 1 = left click pressed, 2 = right click pressed
if (event.buttons === 1) {
value += 20;
}
});
I have this div that listens to mouse clicks, when it receives a mouse click it does some animation, my question is, how can I disable the mouse click event's it receives when until the animation is done?
You can check whether the animation is still running in the handler.
For more details, please supply more details.
// Grab the object
var obj = document.getElementById('theObject');
// Disable any clicking
obj.onclick = function() { return false; }
You can apply the same .onclick method when you're ready to use it again.