元素

Canvas

canvas 是一个由你自己用 2D 绘图 API(即 HTML Canvas 2D API)绘制的视图:图表、仪表盘、圆环、签名、自定义形状都可以用它来画。绘制代码记录操作,平台在原生侧以屏幕分辨率回放这些操作(iOS 和 Mac Catalyst 上是 Core Graphics,Android 上是 android.graphics.Canvas)。Rust 用 canvas(painter) 创建,Painter 记录绘制内容;TSX 用从 nsh 导入的 <Canvas> 及其 draw 函数。

el-canvas.tsx
el-canvas.tsx运行中
import { Canvas, mount, signal, Text, View } from "nsh";
import { createAnimatedValue, Easing } from "nsh";
import { platform, windowSize } from "nsh";
import { button, buttonText, tint, ui } from "./palette";

const TAU = Math.PI * 2;

// Twelve months of made-up values, 0–100.
const values = [32, 41, 38, 52, 47, 63, 58, 71, 66, 80, 74, 88];
const months = "JFMAMJJASOND";

function Button(props: { label: string; onPress: () => void }) {
  return (
    <View onPress={props.onPress} {...button()}>
      <Text style={buttonText()}>{props.label}</Text>
    </View>
  );
}

function App() {
  // The month under the finger or pointer: `draw` reads it, so moving redraws.
  const picked = signal(values.length - 1);
  const pick = (x: number, width: number) =>
    picked.set(Math.max(0, Math.min(values.length - 1, Math.round(((x - 20) / (width - 40)) * (values.length - 1)))));
  let chartWidth = 0;

  // The dial's angle is a native animated value: it turns without running `draw`.
  const angle = createAnimatedValue(0);
  const turns = signal(0);
  const spin = () => {
    turns.update((n) => n + 1);
    angle.timing(turns() * TAU, { duration: 900, easing: Easing.out(Easing.cubic) });
  };

  const wide = () => windowSize().width >= 700;

  return (
    <View style={{ flex: 1, backgroundColor: ui().page, padding: 20, paddingTop: 24, gap: 14 }}>
      <Text style={{ fontSize: 22, fontWeight: "700", color: ui().text }}>canvas</Text>
      <Text style={{ color: ui().muted }}>
        {platform.desktop ? "Drag across the chart with the mouse" : "Drag your finger across the chart"} · {months[picked()]}{" "}
        = {values[picked()]}
      </Text>

      <View style={{ flex: 1, flexDirection: wide() ? "row" : "column", gap: 14 }}>
        <Canvas
          style={{ ...ui().inset, flex: 1, minHeight: 200, borderRadius: 14 }}
          onLayout={({ bounds }) => (chartWidth = bounds.size.width)}
          onStartShouldSetResponder={() => true}
          onResponderGrant={(e) => {
            pick(e.locationX, chartWidth);
            return true;
          }}
          onResponderMove={(e) => pick(e.locationX, chartWidth)}
          draw={(cx, { width, height }) => {
            const pad = 20;
            const x = (i: number) => pad + (i / (values.length - 1)) * (width - 2 * pad);
            const y = (v: number) => height - pad - 16 - (v / 100) * (height - 2 * pad - 32);
            const line = () => {
              cx.beginPath();
              values.forEach((v, i) => (i === 0 ? cx.moveTo(x(i), y(v)) : cx.lineTo(x(i), y(v))));
            };

            // Grid lines, dashed.
            cx.strokeStyle = ui().border;
            cx.lineWidth = 1;
            cx.setLineDash([4, 4]);
            for (const v of [25, 50, 75]) {
              cx.beginPath();
              cx.moveTo(pad, y(v));
              cx.lineTo(width - pad, y(v));
              cx.stroke();
            }
            cx.setLineDash([]);

            // The area under the line: a path filled with a linear gradient.
            const area = cx.createLinearGradient(0, pad, 0, height - pad);
            area.addColorStop(0, tint(ui().accent, 0.32));
            area.addColorStop(1, tint(ui().accent, 0));
            line();
            cx.lineTo(x(values.length - 1), y(0));
            cx.lineTo(x(0), y(0));
            cx.closePath();
            cx.fillStyle = area;
            cx.fill();

            line();
            cx.strokeStyle = ui().accent;
            cx.lineWidth = 2.5;
            cx.lineJoin = "round";
            cx.stroke();

            // Month labels: text.
            cx.font = "11px system-ui";
            cx.textAlign = "center";
            cx.textBaseline = "alphabetic";
            values.forEach((_, i) => {
              cx.fillStyle = i === picked() ? ui().text : ui().faint;
              cx.fillText(months[i], x(i), height - 10);
            });

            // The picked point, its guide and a bubble with its value.
            const i = picked();
            const px = x(i);
            const py = y(values[i]);
            cx.strokeStyle = tint(ui().text, 0.25);
            cx.beginPath();
            cx.moveTo(px, pad);
            cx.lineTo(px, y(0));
            cx.stroke();
            cx.shadowColor = tint(ui().accent, 0.6);
            cx.shadowBlur = 10;
            cx.fillStyle = ui().accent;
            cx.beginPath();
            cx.arc(px, py, 6, 0, TAU);
            cx.fill();
            cx.shadowBlur = 0;
            const label = String(values[i]);
            cx.font = "600 13px system-ui";
            const w = cx.measureText(label).width + 16;
            const bx = Math.max(pad, Math.min(width - pad - w, px - w / 2));
            cx.fillStyle = ui().text;
            cx.beginPath();
            cx.roundRect(bx, py - 36, w, 22, 6);
            cx.fill();
            cx.fillStyle = ui().page;
            cx.textBaseline = "middle";
            cx.fillText(label, bx + w / 2, py - 25);
          }}
        />

        <View style={{ ...ui().card, borderRadius: 14, padding: 16, gap: 12, alignItems: "center", width: wide() ? 240 : undefined, alignSelf: wide() ? "flex-start" : undefined }}>
          <Canvas
            style={{ width: 120, height: 120 }}
            draw={(cx, { width, height }) => {
              const r = width / 2 - 6;
              const c = cx.createConicGradient(0, width / 2, height / 2);
              c.addColorStop(0, ui().info);
              c.addColorStop(0.5, ui().violet);
              c.addColorStop(1, ui().info);
              cx.fillStyle = c;
              cx.beginPath();
              cx.arc(width / 2, height / 2, r, 0, TAU);
              cx.fill();
              cx.translate(width / 2, height / 2);
              cx.rotate(angle); // animates natively
              cx.fillStyle = ui().page;
              cx.beginPath();
              cx.moveTo(0, -r + 10);
              cx.lineTo(8, 0);
              cx.lineTo(-8, 0);
              cx.closePath();
              cx.fill();
              cx.beginPath();
              cx.arc(0, 0, 10, 0, TAU);
              cx.fill();
            }}
          />
          <Text style={{ color: ui().muted, textAlign: "center" }}>Turns: {turns()} (a native animated value)</Text>
          <Button label="Spin" onPress={spin} />
        </View>
      </View>
    </View>
  );
}

mount(App);
use std::f32::consts::{FRAC_PI_2, TAU};

use nsh_core::{canvas::LineCap, prelude::*};

/// 一个进度圆环,120 点见方。
fn ring(progress: f32) -> impl IntoElement {
    let (center, radius) = (60.0, 50.0);
    canvas(
        Painter::new()
            .line_width(12.0)
            .line_cap(LineCap::Round)
            .stroke_color(rgb(0xe5e7eb))
            .begin_path()
            .arc(center, center, radius, 0.0, TAU)
            .stroke()
            .stroke_color(rgb(0x6366f1))
            .begin_path()
            .arc(center, center, radius, -FRAC_PI_2, -FRAC_PI_2 + progress * TAU)
            .stroke(),
    )
    .size(px(120.0))
}

在 TSX 中,Canvas 会创建原生画布视图、测量它的尺寸,再把上下文和尺寸传给你的 draw 函数(参见 Canvas API)。在 Rust 中,canvas(..) 接收一个 Painter,或返回 Painter 的闭包:闭包读取的内容变化时会重新绘制;绘制依赖尺寸时,尺寸来自 on_layout。

#属性

画布接受 view 的属性(样式、点按与手势属性、onLayout、无障碍属性、ref 等),另外还有:

属性Rust类型说明
drawcanvas(painter)(cx: CanvasRenderingContext2D, size: { width: number; height: number }) => void绘制画布。尺寸确定后执行一次,画布尺寸变化时、读取的 signal 变化时再次执行。

请通过样式给画布一个尺寸(宽 / 高、flex、宽高比):它的尺寸由样式决定。

#何时重绘

绘制会像 effect 一样被追踪:在里面读取某个 signal,绘制就会订阅它。

let values = signal(vec![12.0_f32, 40.0, 28.0, 64.0]);
let width = signal(0.0_f32);
let height = 160.0;

canvas(move || {
    let data = values.get(); // values 变化时重绘
    let step = width.get() / data.len() as f32;
    data.iter().enumerate().fold(Painter::new().fill_color(rgb(0x0969da)), |p, (i, v)| {
        p.fill_rect(i as f32 * step + 4.0, height - v, step - 8.0, *v)
    })
})
.h(px(height))
.on_layout(move |frame: &Bounds<Points>| width.set(frame.size.width.0))

数字和颜色也可以是原生动画值(CanvasNumber、CanvasPaint;在 Rust 中,凡是数字的位置都可以传 &AnimatedValue):这些值动画时,平台会自行重绘,每帧都不经过应用代码。

use std::f32::consts::TAU;

let angle = animated_value(0.0);
angle.timing(TAU, 1000.0, Easing::Linear);

canvas(
    Painter::new()
        .translate(40.0, 40.0)
        .rotate(&angle) // 在原生侧动画
        .fill_color(rgb(0xcf222e))
        .fill_rect(-20.0, -4.0, 40.0, 8.0),
)
.size(px(80.0))

#上下文

CanvasRenderingContext2D 是浏览器版本的一个子集,Painter 以 snake case 方法提供同样的操作(move_to、line_to、fill_rect、fill_text、stroke_color 等):状态栈(save、restore)、变换、路径(moveTo、lineTo、arc、arcTo、ellipse、rect、roundRect、贝塞尔曲线)、fill / stroke / clip(也可作用于 Path2D,后者接受 SVG 路径数据;Rust 中为 fill_svg / stroke_svg)、矩形、文字(fillText、strokeText、measureText)、线性 / 径向 / 锥形渐变、虚线、阴影、globalAlpha、globalCompositeOperation 以及 drawImage(图片可以是 URL 或资源)。所有成员见 Canvas API 参考;画布指南介绍了如何绘制图表和动画图形。

坐标单位是点,原点在左上角。measureText 是同步的,返回 width。Rust 的 Painter 也能做命中测试(is_point_in_path、is_point_in_stroke)。

上下文绘制矢量操作和图片:像素读写(getImageData / putImageData)、filter 和 SVG 图片不在其中。

#事件

与 view 的事件相同:onPress、onLayout、手势和触摸。如果要处理相对于画面的点击,可以在 onTouchEnd 中读取 locationX / locationY,或用 onResponderMove(Rust 中为 .on_responder_move(..),读取 e.location)跟踪拖动。

#ref 方法

没有自己的方法。