Skip to main content

neco_view2d_svg_wasm/
lib.rs

1//! WebAssembly bindings for `neco-view2d-svg` via `wasm-bindgen`.
2
3use neco_view2d::View2d;
4use neco_view2d_svg::{world_points_to_polyline, world_points_to_svg_d, world_transform_attr};
5use wasm_bindgen::prelude::*;
6
7/// Emit an SVG `transform` attribute value for the given view and canvas size.
8#[wasm_bindgen]
9pub fn emit_transform(
10    center_x: f64,
11    center_y: f64,
12    view_size: f64,
13    canvas_w: f64,
14    canvas_h: f64,
15) -> String {
16    let view = View2d {
17        center_x,
18        center_y,
19        view_size,
20    };
21    world_transform_attr(&view, canvas_w, canvas_h)
22}
23
24/// Emit an SVG `polyline` `points` attribute from a flat `[x0, y0, x1, y1, ...]` array of world coordinates.
25#[wasm_bindgen]
26pub fn emit_polyline(
27    center_x: f64,
28    center_y: f64,
29    view_size: f64,
30    points: Vec<f64>,
31    canvas_w: f64,
32    canvas_h: f64,
33) -> String {
34    let view = View2d {
35        center_x,
36        center_y,
37        view_size,
38    };
39    let pairs = decode_points(points);
40    world_points_to_polyline(&view, &pairs, canvas_w, canvas_h)
41}
42
43/// Emit an SVG `path` `d` attribute from a flat `[x0, y0, x1, y1, ...]` array of world coordinates.
44#[wasm_bindgen]
45pub fn emit_path(
46    center_x: f64,
47    center_y: f64,
48    view_size: f64,
49    points: Vec<f64>,
50    canvas_w: f64,
51    canvas_h: f64,
52) -> String {
53    let view = View2d {
54        center_x,
55        center_y,
56        view_size,
57    };
58    let pairs = decode_points(points);
59    world_points_to_svg_d(&view, &pairs, canvas_w, canvas_h)
60}
61
62fn decode_points(points: Vec<f64>) -> Vec<(f64, f64)> {
63    points
64        .chunks(2)
65        .filter_map(|chunk| chunk.first().zip(chunk.get(1)).map(|(x, y)| (*x, *y)))
66        .collect()
67}