diff --git a/ipycanvas/canvas.py b/ipycanvas/canvas.py index 3986458..7105bfb 100644 --- a/ipycanvas/canvas.py +++ b/ipycanvas/canvas.py @@ -582,6 +582,7 @@ class Canvas(_CanvasBase): _client_ready_callbacks = Instance(CallbackDispatcher, ()) + _mouse_wheel_callbacks = Instance(CallbackDispatcher, ()) _mouse_move_callbacks = Instance(CallbackDispatcher, ()) _mouse_down_callbacks = Instance(CallbackDispatcher, ()) _mouse_up_callbacks = Instance(CallbackDispatcher, ()) @@ -1507,6 +1508,10 @@ def on_mouse_out(self, callback, remove=False): """Register a callback that will be called on mouse out of the canvas.""" self._mouse_out_callbacks.register_callback(callback, remove=remove) + def on_mouse_wheel(self, callback, remove=False): + """Register a callback that will be called on mouse wheel movement.""" + self._mouse_wheel_callbacks.register_callback(callback, remove=remove) + def on_touch_start(self, callback, remove=False): """Register a callback that will be called on touch start (new finger on the screen).""" self._touch_start_callbacks.register_callback(callback, remove=remove) @@ -1551,6 +1556,8 @@ def _handle_frontend_event(self, _, content, buffers): self._mouse_up_callbacks(content["x"], content["y"]) if content.get("event", "") == "mouse_out": self._mouse_out_callbacks(content["x"], content["y"]) + if content.get("event", "") == "mouse_wheel": + self._mouse_wheel_callbacks(content["x"], content["y"]) if content.get("event", "") == "touch_start": self._touch_start_callbacks( @@ -1749,6 +1756,10 @@ def on_mouse_out(self, callback, remove=False): """Register a callback that will be called on mouse out of the canvas.""" self._canvases[-1].on_mouse_out(callback, remove=remove) + def on_mouse_wheel(self, callback, remove=False): + """Register a callback that will be called on mouse wheel movement.""" + self._canvases[-1].on_mouse_wheel(callback, remove=remove) + def on_touch_start(self, callback, remove=False): """Register a callback that will be called on touch start (new finger on the screen).""" self._canvases[-1].on_touch_start(callback, remove=remove) diff --git a/src/widget.ts b/src/widget.ts index 99772ce..a53bb82 100644 --- a/src/widget.ts +++ b/src/widget.ts @@ -1338,6 +1338,9 @@ export class CanvasView extends DOMWidgetView { this.el.addEventListener('mouseout', { handleEvent: this.onMouseOut.bind(this) }); + this.el.addEventListener('wheel', { + handleEvent: this.onMouseWheel.bind(this) + }); this.el.addEventListener('touchstart', { handleEvent: this.onTouchStart.bind(this) }); @@ -1392,6 +1395,14 @@ export class CanvasView extends DOMWidgetView { this.model.send({ event: 'mouse_out', ...this.getCoordinates(event) }, {}); } + private onMouseWheel(event: WheelEvent) { + this.model.send( + { event: 'mouse_wheel', x: event.deltaX, y: event.deltaY }, + {} + ); + event.preventDefault(); + } + private onTouchStart(event: TouchEvent) { const touches: Touch[] = Array.from(event.touches); this.model.send(