Skip to content

快速开始

基本接入方式

在组件里使用 tui-entine,通常会结合 t-canvas-engine 一起使用。

典型流程是:

  1. 模板中放一个 t-canvas-engine
  2. initFinished 中拿到引擎实例或 Canvas 上下文
  3. 使用 TuiEngine 创建节点
  4. 组装元素树
  5. 调用 draw(...) 完成首次绘制
  6. 在交互中调用 updateElement(...) 或重新绘制

模板示例

一个典型模板入口长这样:

vue
<template>
  <t-canvas-engine
    @initFinished="initFinished"
    @touchstart="touchstart"
    @touchmove="touchmove"
    @touchend="touchend"
  ></t-canvas-engine>
</template>

<script setup lang="uts">
import { TuiEngine } from "@/uni_modules/tui-entine";
import { ITuiEngine, ITuiElement } from "@/uni_modules/tui-entine/types";

let eng: ITuiEngine | null = null;

function initFinished(engine: ITuiEngine) {
  eng = engine;

  // 创建根容器
  const root = engine.createView();
  root.style.width = engine.width;
  root.style.height = engine.height;
  root.style.backgroundColor = "#ffffff";
  root.style.justifyContent = "center";
  root.style.alignItems = "center";

  // 创建文本元素
  const title = engine.createText();
  title.value = "Hello tui-entine";
  title.style.fontSize = 16;
  title.style.color = "#333333";

  // 组装元素树
  root.appendChild(title);

  // 绘制
  engine.draw(root, null);
}

function touchstart(e: any) {
  if (eng) {
    eng.handleTouchEvent(e);
  }
}

function touchmove(e: any) {
  if (eng) {
    eng.handleTouchEvent(e);
  }
}

function touchend(e: any) {
  if (eng) {
    eng.handleTouchEvent(e);
  }
}
</script>

项目结构

tui-entine 的核心文件结构:

  • uni_modules/tui-entine/index.uts - 引擎主文件
  • uni_modules/tui-entine/types/index.uts - 类型定义
  • uni_modules/tui-entine/components/ - 组件实现
    • view.uts - 视图组件
    • text.uts - 文本组件
    • image.uts - 图片组件
    • button.uts - 按钮组件
  • uni_modules/tui-entine/core/ - 核心功能
    • layout.uts - 布局计算
    • render.uts - 渲染逻辑
    • style.uts - 样式处理
    • util.uts - 工具函数

核心概念

  1. 引擎(Engine):负责整体的布局计算、渲染和事件处理
  2. 元素(Element):构建UI的基本单位,包括视图、文本、图片、按钮等
  3. 样式(Style):控制元素的外观和布局
  4. 事件(Event):处理用户交互
  5. 绘制(Draw):将元素树渲染到 Canvas 上

性能优化

  1. 局部更新:使用 updateElement 只更新需要变化的元素
  2. 缓存:合理使用 cached()clearCached() 方法
  3. 减少绘制:避免频繁的 draw 调用,尽量使用局部更新
  4. 优化布局:合理使用 Flex 布局,减少嵌套层级

常见问题

1. Canvas 尺寸问题

确保 Canvas 元素的尺寸与实际显示尺寸一致,避免拉伸或模糊。

2. 事件处理

确保正确传递触摸事件到引擎,否则元素的点击等交互将失效。

3. 性能问题

对于复杂场景,建议:

  • 使用局部更新而非全量重绘
  • 减少元素数量,合理使用容器
  • 避免在绘制过程中进行复杂计算