interactive_image.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. from __future__ import annotations
  2. from pathlib import Path
  3. from typing import Any, Callable, List, Optional, Union
  4. from ..events import GenericEventArguments, MouseEventArguments, handle_event
  5. from .mixins.content_element import ContentElement
  6. from .mixins.source_element import SourceElement
  7. class InteractiveImage(SourceElement, ContentElement, component='interactive_image.js'):
  8. CONTENT_PROP = 'content'
  9. def __init__(self,
  10. source: Union[str, Path] = '', *,
  11. content: str = '',
  12. on_mouse: Optional[Callable[..., Any]] = None,
  13. events: List[str] = ['click'],
  14. cross: bool = False,
  15. ) -> None:
  16. """Interactive Image
  17. Create an image with an SVG overlay that handles mouse events and yields image coordinates.
  18. It is also the best choice for non-flickering image updates.
  19. If the source URL changes faster than images can be loaded by the browser, some images are simply skipped.
  20. Thereby repeatedly updating the image source will automatically adapt to the available bandwidth.
  21. See `OpenCV Webcam <https://github.com/zauberzeug/nicegui/tree/main/examples/opencv_webcam/main.py>`_ for an example.
  22. :param source: the source of the image; can be an URL, local file path or a base64 string
  23. :param content: SVG content which should be overlayed; viewport has the same dimensions as the image
  24. :param on_mouse: callback for mouse events (yields `type`, `image_x` and `image_y`)
  25. :param events: list of JavaScript events to subscribe to (default: `['click']`)
  26. :param cross: whether to show crosshairs (default: `False`)
  27. """
  28. super().__init__(source=source, content=content)
  29. self._props['events'] = events
  30. self._props['cross'] = cross
  31. def handle_mouse(e: GenericEventArguments) -> None:
  32. if on_mouse is None:
  33. return
  34. arguments = MouseEventArguments(
  35. sender=self,
  36. client=self.client,
  37. type=e.args.get('mouse_event_type'),
  38. image_x=e.args.get('image_x'),
  39. image_y=e.args.get('image_y'),
  40. button=e.args.get('button', 0),
  41. buttons=e.args.get('buttons', 0),
  42. alt=e.args.get('alt', False),
  43. ctrl=e.args.get('ctrl', False),
  44. meta=e.args.get('meta', False),
  45. shift=e.args.get('shift', False),
  46. )
  47. return handle_event(on_mouse, arguments)
  48. self.on('mouse', handle_mouse)