t-canvas
Canvas 画布
组件介绍
t-canvas 是一个统一的 Canvas 画布组件,简化了 Canvas 的初始化配置,增加了 PC 端对 touchmove 事件的支持,通过事件返回绘制对象,使 Canvas 的使用更加简单。组件的 API 使用方法与原生 Canvas 一致,适用于各种需要绘制图形、动画、图表等场景。
平台兼容
| Harmony | H5 | Android | iOS | 小程序 | UTS |
|---|---|---|---|---|---|
| ✅ | ✅ | ✅ | ✅ | ✅ | ✅ |
基础用法
基础用法参考 demo/canvas/canvas.uvue,通过 initFinished 事件获取 Canvas 上下文进行绘制。
vue
<template>
<t-canvas ref="canvasRef" class="twh-500-300 bg-#fff r-20" @initFinished="canvasInit"></t-canvas>
</template>
<script setup>
const canvasRef = ref<any>(null);
function canvasInit(context) {
const ctx = context.getContext('2d');
// 绘制矩形
ctx.fillStyle = '#2979ff';
ctx.fillRect(50, 50, 100, 100);
// 绘制圆形
ctx.beginPath();
ctx.arc(250, 150, 50, 0, 2 * Math.PI);
ctx.fillStyle = '#4caf50';
ctx.fill();
// 绘制文本
ctx.font = '20px Arial';
ctx.fillStyle = '#333';
ctx.textAlign = 'center';
ctx.fillText('Hello Canvas', 250, 250);
}
// 导出 Canvas 为图片
async function exportImage() {
const imageUrl = await canvasRef.value.toDataURL();
console.log('Image URL:', imageUrl);
}
</script>Props
| 属性名 | 说明 | 类型 | 默认值 |
|---|---|---|---|
path | 点击组件后跳转的页面路径;为空时仅响应事件 | string | '' |
hover | 是否启用点击效果 | boolean | false |
type | 组件主题类型,可选 info、primary、error、warning、success | string | '' |
disabled | 是否禁用 | boolean | false |
effect | 组件显示主题,可选 normal、dark、light、plain | string | '' |
size | 组件尺寸,可选 large、medium、small、mini | string | '' |
Events
| 事件名 | 说明 | 回调参数 |
|---|---|---|
click | 点击时触发 | UniPointerEvent |
initFinished | 组件初始化完成时触发,返回 Canvas 上下文 | CanvasContext |
touchstart | 触摸开始时触发 | UniTouchEvent |
touchend | 触摸结束时触发 | UniTouchEvent |
touchmove | 触摸移动时触发 | UniTouchEvent |
touchcancel | 触摸取消时触发 | UniTouchEvent |
transitionend | 动画结束时触发 | - |
Methods
| 方法名 | 说明 | 返回值 |
|---|---|---|
toDataURL | 将 Canvas 内容导出为图片 | Promise<string>,图片地址 |