svg.rs 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //! Thanks to @japsu and their project https://github.com/japsu/jatsi for the example!
  2. //!
  3. //! This example shows how to create a simple dice rolling app using SVG and Dioxus.
  4. //! The `svg` element and its children have a custom namespace, and are attached using different methods than regular
  5. //! HTML elements. Any element can specify a custom namespace by using the `namespace` meta attribute.
  6. //!
  7. //! If you `go-to-definition` on the `svg` element, you'll see its custom namespace.
  8. use dioxus::prelude::*;
  9. use rand::{thread_rng, Rng};
  10. fn main() {
  11. dioxus::launch(|| {
  12. rsx! {
  13. div { user_select: "none", webkit_user_select: "none", margin_left: "10%", margin_right: "10%",
  14. h1 { "Click die to generate a new value" }
  15. div { cursor: "pointer", height: "100%", width: "100%", Dice {} }
  16. }
  17. }
  18. });
  19. }
  20. #[component]
  21. fn Dice() -> Element {
  22. const Y: bool = true;
  23. const N: bool = false;
  24. const DOTS: [(i64, i64); 7] = [(-1, -1), (-1, -0), (-1, 1), (1, -1), (1, 0), (1, 1), (0, 0)];
  25. const DOTS_FOR_VALUE: [[bool; 7]; 6] = [
  26. [N, N, N, N, N, N, Y],
  27. [N, N, Y, Y, N, N, N],
  28. [N, N, Y, Y, N, N, Y],
  29. [Y, N, Y, Y, N, Y, N],
  30. [Y, N, Y, Y, N, Y, Y],
  31. [Y, Y, Y, Y, Y, Y, N],
  32. ];
  33. let mut value = use_signal(|| 5);
  34. let active_dots = use_memo(move || &DOTS_FOR_VALUE[(value() - 1) as usize]);
  35. rsx! {
  36. svg {
  37. view_box: "-1000 -1000 2000 2000",
  38. onclick: move |event| {
  39. event.prevent_default();
  40. value.set(thread_rng().gen_range(1..=6))
  41. },
  42. rect { x: -1000, y: -1000, width: 2000, height: 2000, rx: 200, fill: "#aaa" }
  43. for ((x, y), _) in DOTS.iter().zip(active_dots.read().iter()).filter(|(_, &active)| active) {
  44. circle {
  45. cx: *x * 600,
  46. cy: *y * 600,
  47. r: 200,
  48. fill: "#333"
  49. }
  50. }
  51. }
  52. }
  53. }