web-sys: canvas hello world
Not working in Firefox anymore . ??? Chrome = Ok
Drawing a smiley face with the 2D canvas API. This is a port of part of this MDN tutorial to web-sys. _ [wasm-bindgen Guide]
Original [web-sys: canvas hello world]
setup the project
cargo new canvas --lib
cd canvas
mkdir -p www/js www/htmlhttp -a 127.0.0.1 -p 8080 www
cargo add wasm-bindgen js-sys
cargo add web-sys -F "CanvasRenderingContext2d, Document, Element, HtmlCanvasElement, Window"
edit Cargo.toml to add crate-type
& put web-sys
in its own dependecy section
[lib]
crate-type = ["cdylib",]
...
[dependencies.web-sys]
version = "0.3.66"
features = [
'CanvasRenderingContext2d',
'Document',
'Element',
'HtmlCanvasElement',
'Window',
]
in www/html/index.html
we have
<!doctype html>
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type"/>
<title>canvas hello: nobundle</title>
</head>
<body>
<canvas id="canvas" height="150" width="150"></canvas>
<script type="module" src="../js/index.js"></script>
</body>
</html>
and in www/js/index.js
import init from "../pkg/canvas.js"
async function run() {
const wasm = await init();
}
run();
Everything happens in src
#![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(); } }
build and serve
wasm-pack build --target web --no-typescript --out-dir www/pkg
http www
open index.html
firefox http://localhost:8000/html/