Add ability to track mouse clicks

This commit is contained in:
Yash Karandikar 2021-11-26 20:34:52 -06:00
parent e94573fc30
commit abc59c37e0
Signed by: karx
GPG key ID: A794DA2529474BA5
6 changed files with 80 additions and 2 deletions

2
drawrs/Cargo.lock generated
View file

@ -35,7 +35,9 @@ checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
name = "drawrs"
version = "0.1.0"
dependencies = [
"js-sys",
"sycamore",
"wasm-bindgen",
]
[[package]]

View file

@ -6,4 +6,6 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
sycamore = "0.6.3"
sycamore = "0.6.3"
wasm-bindgen = "0.2.78"
js-sys = "0.3.55"

View file

@ -7,6 +7,7 @@
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/8.0.1/normalize.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/milligram/1.4.1/milligram.css">
<link rel="css" data-trunk href="style.css">
<link rel="inline" data-trunk href="script.js">
</head>
<body></body>
</html>

11
drawrs/script.js Normal file
View file

@ -0,0 +1,11 @@
function test(str) {
console.log(str);
}
function getCanvas() {
return document.getElementById("canvas");
}
function getContext() {
return getCanvas().getContext("2d");
}

View file

@ -1,10 +1,62 @@
use sycamore::prelude::*;
use wasm_bindgen::prelude::*;
macro_rules! wasm_import {
($name:ident()) => {
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen]
pub fn $name();
}
};
($name:ident( $( $arg:ident: $type:ty ),* )) => {
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen]
pub fn $name($($arg: $type),*);
}
};
($name:ident($($arg:ident: $type:ty),* > $ret:ty)) => {
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen]
pub fn $name($($arg: $type)*) -> $ret;
}
}
}
macro_rules! read_js_value {
($target:expr, $key:expr) => {js_sys::Reflect::get(&$target, &wasm_bindgen::JsValue::from_str($key))}
}
wasm_import!(test(s: &str));
wasm_import!(addEventListener(name: &str, cb: &Closure<dyn Fn(MouseEvent)>));
#[wasm_bindgen]
extern "C" {
pub type MouseEvent;
}
fn main() {
let clicked = Signal::new(false);
let cb = Closure::wrap(Box::new(cloned!((clicked) => move |e: MouseEvent| {
let val = read_js_value!(e.obj, "buttons").unwrap().as_f64().unwrap() as u8;
if val == 1 {
clicked.set(true);
}
})) as Box<dyn Fn(MouseEvent)>);
addEventListener("mousedown", &cb);
cb.forget();
sycamore::render(||
template! {
div(class="wrapper") {
p { "Hello, world!" }
canvas(id="canvas")
}
}
);

View file

@ -3,4 +3,14 @@
margin: auto;
width: 60%;
padding: 10px;
}
#canvas {
border: 1px solid #000000;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 75%;
height: 75%;
}