let bgColor = 200;
let div;
function setup() {
createCanvas(windowWidth, windowHeight);
background(bgColor);
div = createDiv();
div.style("background","rgb(123, 0, 0, 0.1)");
div.style("width", "100px");
div.style("height", "100px");
div.position(0, 0);
div.mouseMoved(goto);
}
function goto() {
div.position(mouseX-50, mouseY-50);
}
I want to move the red square following the mouse when the mouse is over it, but when my mouse moves fastly enough, the event can’t be detected, and the square doesn’t move. So how to resolve it?
The way I understand your program; You create a division of HTML that checks for the mouse inside.
The issue with your program is that it cannot detect mouse outside of itself. To prevent this issue, you can just set the division location to mouseX - 50, mouseY - 50, without waiting for the mouse to move, regardless of it’s position.
Anyway, that’s how I understand your code. Try this, and if doesn’t work, just try something else : P
I think the problem is rather that the mouse can jump over the div - for example the cursor is on the left of the div and next frame it’s on the right because it moved too fast. Maybe you can interpolate mouseX and mouseY between frames.
maybe I misunderstood the problem. Is this what you want?
div is at top left
when mouse is inside div, start following mouse
continue following mouse
If so, I would make a boolean value isFollowing = false to remember if the div is following the mouse or not. Instead of div.mouseMoved, I would use a global function function mouseMoved(){} to track the mouse (because the former only captures mouse when the mouse cursor is inside div, and the latter will track no matter where on the page). Once the mouse is inside div, set isFollowing = true, and as long as it’s true, move the div to mouseX, mouseY.