Follow the Mouse Cursor | KIRUPA


#22

You learn something new every day.
Thank you so much! :smile: -)


#23

Thank you for this. I will see if I can make it work for my situation.


#24

Hey!

Thank you soo much Kirupa for sharing such an amazing thing… I tried your code it works Great!

I just wanna know… Can We place the moving object at any place we want to on the canvas and after that stop follow mouse cursor?

Also Can we do similar thing in the Konva React Canvas?


#25

Can you clarify what you mean by placing the object anywhere and stopping the follow effect?


#26

For example, When cursor came to the canvas then the shape will follow mouse moves… And when I click on any where in the canvas then on click event the shape will place on the canvas and no movements will occur after that…

How can we do that ?


#27

Ah, gotcha! What you need is a variable that determines whether the shape should follow the mouse or not. You can use that variable to stop the requestAnimationFrame call from looping and animating the shape. Here is a rough example:

var toAnimate = true;

function update() {
  context.clearRect(0, 0, canvas.width, canvas.height);
 
  context.beginPath();
  context.arc(mouseX, mouseY, 50, 0, 2 * Math.PI, true);
  context.fillStyle = "#FF6A6A";
  context.fill();

  if (toAnimate) {
    requestAnimationFrame(update);
  }
}

When you click, you can set toAnimate to false. That will do the trick.

Cheers,
Kirupa


#28

Yeah! it works Great!

Thanks! :slight_smile: :+1:


#29

Hii Kirupa,

Can we do mouse follow thing with the konva canvas ?

I have tried your example with HTML5 canvas… It works Awesome!
But, When I implement it in konva… I am facing issues.

If possible can you please share same example with the konva canvas please?


#30

I haven’t used konva canvas before. I wouldn’t even know where to begin!


#31

No worries :blush:
I have implemented the functionality in konva :+1: