FIrst piece of code. Have a few questions

Hi there, I have been looking at Rust for some time, and I decided to have a look, learning it a little while also playing with WebAssembly, which is also an interesting subject for me.
I started with an example that I found in the documentation and I modified it a little, to get some basic concepts. This is what I have:

use std::rc::Rc;
use wasm_bindgen::prelude::Closure;
use wasm_bindgen::prelude::wasm_bindgen;
use wasm_bindgen::JsCast;
use wasm_bindgen::JsValue;
use web_sys::{CanvasRenderingContext2d, HtmlCanvasElement, MouseEvent, Window};

#[wasm_bindgen(start)]
#[allow(non_snake_case)]
pub fn start() {

	let window: Window = web_sys::window().unwrap();
	let document = window.document().unwrap();
	let canvas: HtmlCanvasElement = document
		.get_element_by_id("canvas")
		.unwrap()
		.dyn_into::<HtmlCanvasElement>()
		.unwrap();

	let context: CanvasRenderingContext2d = canvas
		.get_context("2d")
		.unwrap()
		.unwrap()
		.dyn_into::<CanvasRenderingContext2d>()
		.unwrap();
		
	let blackRc: Rc<JsValue> = Rc::new(JsValue::from_str("#000000"));
	let whiteRc: Rc<JsValue> = Rc::new(JsValue::from_str("#FFFFFF"));
	
	draw(&context, &*whiteRc);

	let mut colorRc = whiteRc.clone();
    let closure = Closure::wrap(Box::new(move |_event: MouseEvent| {
		if Rc::ptr_eq(&colorRc, &blackRc) {
			colorRc = whiteRc.clone();
		}
		else {
			colorRc = blackRc.clone();
		}

		draw(&context, &*colorRc)
    }) as Box<dyn FnMut(_)>);
    canvas.add_event_listener_with_callback("mousedown", closure.as_ref().unchecked_ref()).unwrap();
    closure.forget();
}

fn draw(context: &CanvasRenderingContext2d, color: &JsValue) {
	context.begin_path();
	context.move_to(95.0, 75.0);

	// Draw the inner circle.
	context
		.arc(75.0, 75.0, 20.0, 0.0, std::f64::consts::PI * 2.0)
		.unwrap();

	context.set_fill_style(color);
	context.fill();
	context.stroke();
}

Now, I have a few questions:

  • is the code correct? Any improvement I can make?
  • can we make this a little simpler? I think I have some problems with the fact that I have to clone those black and white things. It would be much easier if I could make them static, but I can't. Is there a reason why JsValue::from() is not static?
  • I tried 3 environments: Eclipse, IntelliJ, Visual Studio Code. Of this ones, only Visual Studio Code seems to have a working code completion. IntelliJ works somehow, Eclipse not at all (but I do have syntax highlighting). It seems to be related to web_sys.
    Is Visual Studio Code the only environment currently working properly?

Many thanks

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.