2D 画布
使用 2D 画布 API 绘制一个笑脸。这是对 MDN 教程 的一部分的移植到 `web-sys` 的版本。
Cargo.toml
`Cargo.toml` 启用了查询 DOM 和使用 2D 画布所需的特性。
[package]
name = "canvas"
version = "0.1.0"
authors = ["The wasm-bindgen Developers"]
edition = "2018"
rust-version = "1.57"
[lib]
crate-type = ["cdylib"]
[dependencies]
js-sys = "0.3.69"
wasm-bindgen = "0.2.92"
[dependencies.web-sys]
version = "0.3.4"
features = [
'CanvasRenderingContext2d',
'Document',
'Element',
'HtmlCanvasElement',
'Window',
]
src/lib.rs
获取 `<canvas>` 元素,创建一个 2D 渲染上下文,并绘制笑脸。
#![allow(unused)] fn main() { use std::f64; use wasm_bindgen::prelude::*; #[wasm_bindgen(start)] fn start() { let document = web_sys::window().unwrap().document().unwrap(); let canvas = document.get_element_by_id("canvas").unwrap(); let canvas: web_sys::HtmlCanvasElement = canvas .dyn_into::<web_sys::HtmlCanvasElement>() .map_err(|_| ()) .unwrap(); let context = canvas .get_context("2d") .unwrap() .unwrap() .dyn_into::<web_sys::CanvasRenderingContext2d>() .unwrap(); context.begin_path(); // Draw the outer circle. context .arc(75.0, 75.0, 50.0, 0.0, f64::consts::PI * 2.0) .unwrap(); // Draw the mouth. context.move_to(110.0, 75.0); context.arc(75.0, 75.0, 35.0, 0.0, f64::consts::PI).unwrap(); // Draw the left eye. context.move_to(65.0, 65.0); context .arc(60.0, 65.0, 5.0, 0.0, f64::consts::PI * 2.0) .unwrap(); // Draw the right eye. context.move_to(95.0, 65.0); context .arc(90.0, 65.0, 5.0, 0.0, f64::consts::PI * 2.0) .unwrap(); context.stroke(); } }