Returns the 2D rendering context for a given `canvas` element.
(canvas: HtmlCanvasElement)
| 40 | |
| 41 | /// Returns the 2D rendering context for a given `canvas` element. |
| 42 | fn html_canvas_to_2d_context(canvas: HtmlCanvasElement) -> io::Result<CanvasRenderingContext2d> { |
| 43 | let attrs = ContextAttributes2d::new(); |
| 44 | |
| 45 | // We don't use transparency for anything, so disable the alpha channel for performance reasons. |
| 46 | attrs.set_alpha(false); |
| 47 | |
| 48 | // Chrome recommends setting this to true because we read from the canvas to move the cursor |
| 49 | // and to scroll the console, but these operations needn't be fast. It seems better to keep |
| 50 | // this disabled to optimize for the rendering path of graphical applications. |
| 51 | attrs.set_will_read_frequently(false); |
| 52 | |
| 53 | let context = match canvas |
| 54 | .get_context_with_context_options("2d", &attrs) |
| 55 | .map_err(js_value_to_io_error)? |
| 56 | { |
| 57 | Some(context) => context, |
| 58 | None => { |
| 59 | return Err(io::Error::new( |
| 60 | io::ErrorKind::InvalidInput, |
| 61 | "Failed to get 2D context from canvas", |
| 62 | )); |
| 63 | } |
| 64 | }; |
| 65 | |
| 66 | let context = match context.dyn_into::<CanvasRenderingContext2d>() { |
| 67 | Ok(context) => context, |
| 68 | Err(_) => { |
| 69 | return Err(io::Error::new( |
| 70 | io::ErrorKind::InvalidInput, |
| 71 | "Returned 2D context for canvas does not have the correct type", |
| 72 | )); |
| 73 | } |
| 74 | }; |
| 75 | |
| 76 | Ok(context) |
| 77 | } |
| 78 | |
| 79 | /// Implementation of a console that renders on an HTML canvas. |
| 80 | pub(crate) struct CanvasRasterOps { |