Accessing mouse position on canvas element

I got started with some basic animations based on @jashkenas’s Simple Canvas Animation and I’m now wondering how I could access the mouse position.

I had a look at the approaches to change a value from multiple controls of this notebook:

However, I haven’t figured out yet how to combine this with an event handler that listens for mousemove on my canvas element.

Would it be possible to somehow define a handler to let mousemove events affect the value of a mousePos object?

This notebook contains some of my trials so far:

I’m afraid we can’t see your private (draft) notebook with your trials in it … if you want anyone to take a look, you’ll have to publish it first.

But in any case, from your description, I think it’s pretty clear what you’re after.

Here’s a notebook that combines a simple canvas with a mousemove listener to update a mutable mousePos value:

Note that the canvas cell depends on mousePos, and uses the value of this (the previous value of the canvas), to avoid creating a new canvas every time the mouse position changes. In this way, the canvas is only created once, and the event listener is only set up once.

1 Like

Thanks @jashkenas I’ll have a look at that tomorrow.

My link should be updated to a published notebook now…

Here’s another take using Generators.observe to define a mouse position cell:

It has the added benefit that the mouse can be outside the canvas element and movement is still captured.

1 Like

Thanks a lot @mbostock and @jashkenas
I got the mousePos working based on your tips:

I’m a beginner at Generators, and am trying to wrap my head around the what happens in the block that executes yield canvas;

I see how the conditional statement prevents creating a new canvas every frame, but in my code I am still instantiating let vehicle1 = new Vehicle(50, 50); every time the mouse changes. How could I restructure that such that I create vehicle1 once and then update its state after that?

Sorry for shifting this thread away from the original mousePos question :blush:

Like so: https://beta.observablehq.com/@jashkenas/trying-out-boids-fork-for-the-forums

All that I did, was move vehicle1 out of the rendering cell, and into its own cell. Now it’s just evaluated once.

ah, that makes sense, thanks!