在 OpenHarmony(ArkUI,eTS/ArkTS) 中,图表的“动画”通常有两种实现思路:
下面分别说明。
@ohos/arkui.charts)OpenHarmony 提供了 图表组件(Chart),如:
LineChartBarChartPieChart这些组件 默认支持进场动画。
示例(柱状图动画):
import { BarChart, BarData, BarChartModel } from '@ohos/arkui.charts'
@Entry
@Component
struct ChartExample {
private model: BarChartModel = new BarChartModel()
aboutToAppear() {
let data: BarData[] = [
{ value: 10 },
{ value: 20 },
{ value: 30 }
]
this.model.setData(data)
}
build() {
Column() {
BarChart({ model: this.model })
.width('100%')
.height(300)
}
}
}
✅ 特点:
适合:
animateTo@Entry
@Component
struct AnimChart {
@State heightList: number[] = [50, 100, 150]
build() {
Column() {
Button('更新数据')
.onClick(() => {
animateTo({ duration: 800 }, () => {
this.heightList = [120, 80, 200]
})
})
Row() {
ForEach(this.heightList, (h: number) => {
Column()
.width(40)
.height(h)
.backgroundColor(Color.Blue)
})
}
}
}
}
✅ 适用于:
适合复杂图表动画(折线、曲线、实时数据)。
@Entry
@Component
struct CanvasChart {
private ctx: CanvasRenderingContext2D | null = null
@State progress: number = 0
aboutToAppear() {
let last = Date.now()
const loop = () => {
const now = Date.now()
this.progress += (now - last) / 1000
last = now
this.draw()
if (this.progress < 1) {
requestAnimationFrame(loop)
}
}
requestAnimationFrame(loop)
}
draw() {
if (!this.ctx) return
this.ctx.clearRect(0, 0, 300, 300)
this.ctx.fillStyle = '#007DFF'
this.ctx.fillRect(0, 300 - this.progress * 200, 50, this.progress * 200)
}
build() {
Canvas(this.ctx ? this.ctx : (this.ctx = new CanvasRenderingContext2D()))
.width(300)
.height(300)
}
}
| 图表类型 | 推荐方式 |
|---|---|
| 柱状图 | Chart 组件 / animateTo |
| 折线图 | Canvas + RAF |
| 饼图 | Chart 组件 |
| 实时数据 | Canvas + RAF |
| 简单过渡 | animateTo |
✅ 优先使用官方图表组件
✅ 动画时长控制在 300–800ms
✅ 避免频繁 setState 导致卡顿
✅ 复杂动画用 Canvas,不用组件堆叠
如果你能告诉我:
我可以给你一份 可直接运行的完整示例代码。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。