1
0

interactive_image.py 2.5 KB

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