Created
August 10, 2022 09:31
-
-
Save rMazeiks/c0c25f986ab19992776d8e358e406c52 to your computer and use it in GitHub Desktop.
Dioxus example: Dragging to move a red square
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Using `master` version of dioxus | |
// dioxus = { git="https://github.com/DioxusLabs/dioxus.git" } | |
#![allow(non_snake_case)] | |
use dioxus::events::MouseEvent; | |
use dioxus::prelude::*; | |
fn main() { | |
dioxus_desktop::launch(App); | |
} | |
fn App(cx: Scope) -> Element { | |
// Current position of square | |
let position = use_state(&cx, || (0., 0.)); | |
// Position on the square where drag was started | |
// If we are not currently dragging, `None` | |
let drag_start_position = use_state(&cx, || None); | |
// When user starts dragging, track where on the square they started | |
let mouse_down_handler = | |
move |event: MouseEvent| drag_start_position.set(Some(event.data.element_coordinates())); | |
// When the mouse moves on the container | |
let mouse_move_handler = move |event: MouseEvent| { | |
// If we are currently dragging the square | |
if let Some(start_position) = **drag_start_position { | |
// Calculate the new coordinates | |
// (Offset by the square coordinates we started dragging on, otherwise, we would drag the top-left corner) | |
let coordinates = event.page_coordinates() - start_position.cast_unit(); | |
position.set((coordinates.x, coordinates.y)) | |
} | |
}; | |
// When mouse is released, stop dragging | |
let mouse_up_handler = move |_: MouseEvent| drag_start_position.set(None); | |
// Assign variables for easy access in rsx | |
let (x, y) = **position; | |
cx.render(rsx!(div { | |
// make sure the container covers the screen (so that we catch all mouse events) | |
width: "100vw", | |
height: "100vh", | |
onmousemove: mouse_move_handler, | |
onmouseup: mouse_up_handler, | |
div { | |
background: "red", | |
width: "100px", | |
height: "100px", | |
// Set absolute position so we can set exactly where the square should show up | |
position: "absolute", | |
left: "{x}px", | |
top: "{y}px", | |
onmousedown: mouse_down_handler, | |
}, | |
})) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment