Trying to replicate the MNIST ONNX runtime example on Yew rust. I found the code on github github code, I am stuck trying to replicate the drawing component.
I'm encountering difficulties with a specific section of my Rust code, particularly within the draw function. Below is the problematic segment:
let draw = Callback::from(move |e: MouseEvent| {
let mut canvas = canvas_node_ref.cast::<HtmlCanvasElement>();
log::info!("draw");
if let Some(canvas) = canvas {
let ctx = match canvas.get_context("2d") {
Ok(Some(ctx)) => ctx,
_ => return,
}
.dyn_into::<web_sys::CanvasRenderingContext2d>()
.unwrap();
ctx.set_line_width(20.0);
ctx.set_line_join("round");
ctx.set_line_cap("round");
ctx.set_stroke_style(&JsValue::from_str("#393E46"));
ctx.clear_rect(0.0, 0.0, canvas.width() as f64, canvas.height() as f64);
let strokes = draw_context_clone.state().strokes;
//log::info!("the number of strokes is {}", strokes.len());
let mut points = strokes.last().and_then(|p| Some(p.clone())).unwrap_or_else(|| Vec::new());
points.push(math_utils::get_coordinates(e));
let len = points.len();
//log::info!("the size is {}", len);
for s in 0..len-1 {
points = strokes[0].clone();
let p1 = points[s];
let p2 = points[s + 1];
log::info!("inside for loopp {}", p1.0);
ctx.begin_path();
ctx.move_to(p1.0 as f64, p1.1 as f64);
let midpoint = math_utils::get_midpoint(p1, p2);
ctx.quadratic_curve_to(p1.0 as f64, p1.1 as f64, midpoint.0 as f64, midpoint.1 as f64);
ctx.stroke();
}
}
});
let draw_clone = draw.clone();
let activate_draw = Callback::from(move |e: MouseEvent| {
log::info!("activate_draw");
drawing.set(!*drawing); //= true;
draw_context.new_stroke();
let strokes = draw_context.state().strokes;
//let mut points = strokes.last().unwrap().clone();
let mut points = strokes.last().and_then(|p| Some(p.clone())).unwrap_or_else(|| Vec::new());
log::info!("{}", points.len());
points.push(math_utils::get_coordinates(e.clone()));
draw_clone.emit(e);
});
Here is how it is being used in the html elements
html! {
<div>
<div class="input-column">
<div class="input-container">
<div class="input-label">{"Draw any digit"}</div>
<div class="canvas-container">
<canvas
ref={canvas_node_ref_clone}
id="input-canvas"
width="300"
height="300"
onmousedown={activate_draw}
onmousemove={draw}
></canvas>
</div>
</div>
</div>
</div>
}
I've been grappling with Rust's ownership model, hence resorting to multiple clones. The issue arises specifically in this line:let mut points = strokes.last().and_then(|p| Some(p.clone())).unwrap_or_else(|| Vec::new());
Here, a new vector is created, causing the for loop within the draw function to never execute as expected.
Any insights or suggestions on how to address this issue would be greatly appreciated. Thank you.