interactive_image.py 2.8 KB

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