Skip to main content

cranpose_platform_web/
lib.rs

1#![deny(missing_docs)]
2#![doc = include_str!("../README.md")]
3
4use cranpose_foundation::{PointerEvent, PointerEventKind};
5use cranpose_ui_graphics::Point;
6
7/// Converts browser pointer input into Cranpose pointer events.
8pub struct WebPlatform {
9    scale_factor: f64,
10}
11
12impl WebPlatform {
13    /// Creates a platform adapter for a canvas with the given device pixel ratio.
14    pub fn new(scale_factor: f64) -> Self {
15        Self { scale_factor }
16    }
17
18    /// Sets the device pixel ratio of the canvas.
19    ///
20    /// Pointer positions are not scaled by it, because browser events use CSS pixels.
21    pub fn set_scale_factor(&mut self, factor: f64) {
22        self.scale_factor = factor;
23    }
24
25    /// Returns the canvas position `x`, `y` as a `Point` in logical pixels.
26    ///
27    /// Browser events already use CSS pixels, so the position is not scaled.
28    pub fn pointer_position(&self, x: f64, y: f64) -> Point {
29        Point {
30            x: x as f32,
31            y: y as f32,
32        }
33    }
34
35    /// Builds a pointer event of `kind` at a canvas position given in CSS pixels.
36    ///
37    /// The event carries the same position as its local and its root position.
38    pub fn pointer_event(&self, kind: PointerEventKind, x: f64, y: f64) -> PointerEvent {
39        let logical = self.pointer_position(x, y);
40        PointerEvent::new(kind, logical, logical)
41    }
42}
43
44impl Default for WebPlatform {
45    fn default() -> Self {
46        Self::new(1.0)
47    }
48}