mirror of
https://github.com/fluencelabs/wasm-bindgen
synced 2025-06-22 17:21:35 +00:00
This commit implements the first half of [RFC #5] where the `Deref` trait is implemented for all imported types. The target of `Deref` is either the first entry of the list of `extends` attribute or `JsValue`. All examples using `.as_ref()` with various `web-sys` types have been updated to the more ergonomic deref casts now. Additionally the `web-sys` generation of the `extends` array has been fixed slightly to explicitly list implementatoins in the hierarchy order to ensure the correct target for `Deref` is chosen. [RFC #5]: https://github.com/rustwasm/rfcs/blob/master/text/005-structural-and-deref.md
74 lines
2.4 KiB
Rust
74 lines
2.4 KiB
Rust
extern crate js_sys;
|
|
extern crate wasm_bindgen;
|
|
extern crate web_sys;
|
|
|
|
use std::cell::Cell;
|
|
use std::rc::Rc;
|
|
use wasm_bindgen::prelude::*;
|
|
use wasm_bindgen::JsCast;
|
|
|
|
#[wasm_bindgen]
|
|
pub fn main() -> Result<(), JsValue> {
|
|
let document = web_sys::window().unwrap().document().unwrap();
|
|
let canvas = document
|
|
.create_element("canvas")?
|
|
.dyn_into::<web_sys::HtmlCanvasElement>()?;
|
|
document.body().unwrap().append_child(&canvas)?;
|
|
canvas.set_width(640);
|
|
canvas.set_height(480);
|
|
canvas.style().set_property("border", "solid")?;
|
|
let context = canvas
|
|
.get_context("2d")?
|
|
.unwrap()
|
|
.dyn_into::<web_sys::CanvasRenderingContext2d>()?;
|
|
let context = Rc::new(context);
|
|
let pressed = Rc::new(Cell::new(false));
|
|
{
|
|
let context = context.clone();
|
|
let pressed = pressed.clone();
|
|
let closure = Closure::wrap(Box::new(move |event: web_sys::MouseEvent| {
|
|
context.begin_path();
|
|
context.move_to(event.offset_x() as f64, event.offset_y() as f64);
|
|
pressed.set(true);
|
|
}) as Box<FnMut(_)>);
|
|
canvas.add_event_listener_with_callback(
|
|
"mousedown",
|
|
closure.as_ref().unchecked_ref(),
|
|
)?;
|
|
closure.forget();
|
|
}
|
|
{
|
|
let context = context.clone();
|
|
let pressed = pressed.clone();
|
|
let closure = Closure::wrap(Box::new(move |event: web_sys::MouseEvent| {
|
|
if pressed.get() {
|
|
context.line_to(event.offset_x() as f64, event.offset_y() as f64);
|
|
context.stroke();
|
|
context.begin_path();
|
|
context.move_to(event.offset_x() as f64, event.offset_y() as f64);
|
|
}
|
|
}) as Box<FnMut(_)>);
|
|
canvas.add_event_listener_with_callback(
|
|
"mousemove",
|
|
closure.as_ref().unchecked_ref(),
|
|
)?;
|
|
closure.forget();
|
|
}
|
|
{
|
|
let context = context.clone();
|
|
let pressed = pressed.clone();
|
|
let closure = Closure::wrap(Box::new(move |event: web_sys::MouseEvent| {
|
|
pressed.set(false);
|
|
context.line_to(event.offset_x() as f64, event.offset_y() as f64);
|
|
context.stroke();
|
|
}) as Box<FnMut(_)>);
|
|
canvas.add_event_listener_with_callback(
|
|
"mouseup",
|
|
closure.as_ref().unchecked_ref(),
|
|
)?;
|
|
closure.forget();
|
|
}
|
|
|
|
Ok(())
|
|
}
|