@Entry
@Component
struct DynamicImageAnimation {
// 状态变量:当前坐标索引和图片位置
@State currentIndex: number = 0;
@State imageX: number = 0;
@State imageY: number = 0;
@State imagePath: Resource = $r('app.media.background'); // 默认占位图
// 加载JSON配置
async loadConfig() {
try {
const config = 传JSON数据
const jsonData = JSON.parse(config.toString());
this.imagePath = $rawfile(jsonData.imagePath); // 绑定图片路径
// 触发动画
this.startAnimation(jsonData.positions, jsonData.duration);
} catch (e) {
console.error('JSON加载失败:', e);
}
}
// 启动动态坐标动画
startAnimation(positions: Array<{x: number, y: number}>, duration: number) {
let index = 0;
const interval = setInterval(() => {
if (index >= positions.length) {
clearInterval(interval);
return;
}
animateTo({
duration: duration,
curve: Curve.EaseInOut
}, () => {
this.imageX = positions[index].x;
this.imageY = positions[index].y;
});
index++;
}, duration);
}
build() {
Stack({ alignContent: Alignment.TopStart }) {
// 动态图片组件
Image(this.imagePath)
.position({ x: this.imageX, y: this.imageY })
.size({ width: 50, height: 50 })
// 触发加载按钮
Button('启动动画')
.onClick(() => this.loadConfig())
.margin({ top: 400 })
}
.width('100%')
.height('100%')
}
}