8 个版本 (4 个重大变更)

0.5.2 2020年11月12日
0.5.1 2020年11月9日
0.4.0 2020年11月2日
0.3.0 2020年10月31日
0.1.1 2020年10月26日

#951 in WebAssembly

MIT 许可证

27KB
593

kurainai

基于 wasm 和 HTMLCanvas 的 2D 游戏引擎。

示例

https://github.com/yu-hasebe/kurenai_tetris/

文档

https://docs.rs/kurenai/


lib.rs:

此包是一个基于 wasm 和 HTMLCanvas 的 2D 游戏引擎。它允许您使用领域定义轻松创建 2D 游戏。

最小实现如下

use kurenai::game_loop;
use kurenai::game_service::GameService;
use kurenai::key_event::KeyEvent;
use kurenai::{canvas, image};

use std::cell::RefCell;
use std::ops::Deref;
use std::rc::Rc;
use wasm_bindgen_test::*;

// Wrap mutable data with RefCell.
struct TestGameService {
    data: RefCell<i64>,
    image: Rc<web_sys::HtmlImageElement>,
}

// Implement the following three functions.
impl GameService for TestGameService {
    fn key_event(&self, key_event: &KeyEvent) {
        if key_event.enter() {
            let mut data = self.data.borrow_mut();
            *data = 0;
        }
    }

    fn update(&self) {
        let mut data = self.data.borrow_mut();
        *data += 1;
    }

    fn draw(&self, context: &web_sys::CanvasRenderingContext2d) {
        let image = self.image();
        // You can draw various images with CanvasRenderingContext2D. You can find the APIs at
        // https://wasm.rust-lang.net.cn/wasm-bindgen/api/web_sys/struct.CanvasRenderingContext2d.html.
        context
            .draw_image_with_html_image_element_and_sw_and_sh_and_dx_and_dy_and_dw_and_dh(
                image,
                0.0,
                0.0,
                32.0,
                32.0,
                self.data.borrow().clone() as f64,
                self.data.borrow().clone() as f64,
                32.0,
                32.0,
            )
            .expect(format!("Failed to draw image {:?}", image).as_str());
    }
}

impl TestGameService {
    fn new() -> Self {
        let image = image::create_new_html_image_element(&[], "gif");
        Self {
            data: RefCell::new(0),
            image: Rc::new(image),
        }
    }

    fn image(&self) -> &web_sys::HtmlImageElement {
        self.image.deref()
    }
}

#[wasm_bindgen_test]
fn pass() {
    // Pass the GameService implementation and CanvasRenderingContext2D to the game_loop::run()
    // function.
    let test_game_service = TestGameService::new();
    let canvas_rendering_context = canvas::get_canvas_rendering_context_2d("main-canvas");
    game_loop::run(test_game_service, canvas_rendering_context);
}

依赖项

~6.5–9MB
~173K SLoC