鸿蒙 Canvas 实战:转盘扇区绘制、落点反算与 easeOutQuart 逐帧动画
想做一个「说停就停在指定格」的大转盘,Canvas 方案比一堆 Image 拼贴可靠得多。案例来自鸿蒙实践中心开源仓 harmony-practice-center/HarmonyOS-AtomSer-AdventureWheel(master 分支)的 WheelCanvas.ets,整块转盘就是一个 Canvas 加一个中心按钮,每一帧全量重画。先把骨架搭出来:
@Component
export struct WheelCanvas {
private settings: RenderingContextSettings = new RenderingContextSettings(true);
private ctx: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings);
// ……其余为 @Prop 任务列表 / 当前角度 / 三个定时器等实例字段,此处省略
build() {
Stack({ alignContent: Alignment.Center }) {
Canvas(this.ctx)
.width('100%')
.height('100%')
// 伪 3D 俯视角:绕 X 轴压 10 度,perspective 给景深
.rotate({ x: 1, y: 0, z: 0, angle: 10, perspective: 650 })
.hitTestBehavior(HitTestMode.None) // 画布不吃点击,点击都给中心按钮
.onReady(() => {
this.canvasWidth = this.ctx.width;
this.canvasHeight = this.ctx.height;
const size = Math.min(this.canvasWidth, this.canvasHeight);
this.wheelRadius = size * 0.39;
this.centerRadius = this.wheelRadius * 0.2;
this.cx = this.canvasWidth / 2;
this.cy = this.canvasHeight / 2 - 4;
this.drawWheel();
})
// Stack 里还有一个圆形中心按钮(开始/转动/选中三态),代码省略
}
}
}三个细节值得先记住:hitTestBehavior(HitTestMode.None) 让画布不拦截手势;rotate 挂在 Canvas 上做 10 度俯视倾角,扇区图形照平面画,立体感靠透视;转盘的「厚度」不是贴图,是连画 10 层错位圆:
for (let layer = 10; layer >= 1; layer--) {
this.ctx.beginPath();
this.ctx.arc(this.cx, this.cy + layer * 1.3, this.wheelRadius, 0, 2 * Math.PI);
this.ctx.fillStyle = layer % 2 === 0 ? '#4A1D29' : '#35151E';
this.ctx.fill();
}一、扇区绘制:从正上方起算,选中淡化靠 globalAlpha
扇区循环里最关键的一行是 - Math.PI / 2:Canvas 的 0 弧度指向正右方,而转盘习惯第 0 格在正上方,所以每个扇区的起始角都要先减 90 度。选中后其余扇区压暗,用 globalAlpha 一行搞定,比逐色调色省事:
const sectorAngle = (2 * Math.PI) / count;
for (let i = 0; i < count; i++) {
this.ctx.save();
if (this.selectedIndex >= 0 && i !== this.selectedIndex) {
this.ctx.globalAlpha = 0.42; // 未选中的扇区整体压暗
}
const start = this.toRadians(this.currentAngle) + i * sectorAngle - Math.PI / 2;
const end = start + sectorAngle;
this.ctx.beginPath();
this.ctx.moveTo(this.cx, this.cy);
this.ctx.arc(this.cx, this.cy, this.wheelRadius, start, end);
this.ctx.closePath();
// 填充色:完成态用灰色,否则取调色板;描边:选中格金色加粗
this.ctx.fill();
this.ctx.stroke();
// ……扇区文字的 translate/rotate 绘制在下面单独讲
this.ctx.restore();
}扇区里的文字要沿半径方向「躺」着排,做法是先 translate 到中点、再 rotate 中线角加 90 度。rotate 的参照系是 translate 后的原点,所以这两步必须包在 save/restore 里,否则下一格的坐标系就歪了:
const mid = start + sectorAngle / 2;
const labelRadius = this.wheelRadius * 0.66;
const x = this.cx + labelRadius * Math.cos(mid);
const y = this.cy + labelRadius * Math.sin(mid);
this.ctx.save();
this.ctx.translate(x, y);
this.ctx.rotate(mid + Math.PI / 2); // 文字沿半径方向排
this.ctx.font = `bold ${count > 12 ? 13 : 15}px "HarmonyOS Sans SC"`;
this.ctx.textAlign = 'center';
this.ctx.textBaseline = 'middle';
this.ctx.fillText(isCompleted ? `${number} 完成` : `${number} ${type}`, 0, 0);
this.ctx.restore();二、落点反算:指针不动,转的是盘面
指针固定在正上方(0 度),转的是盘面。判断当前指到第几格,取的是「旋转角的补角」落在哪个扇区里——这句话就是下面代码的全部含义:
private getResultIndex(): number {
if (this.tasks.length === 0) { return -1; }
const sectorAngle = 360 / this.tasks.length;
const pointerAngle = (360 - this.currentAngle % 360 + 360) % 360;
return Math.floor(pointerAngle / sectorAngle) % this.tasks.length;
}反过来的问题更实用:想让转盘停在第 N 格,目标角度是多少?把 N 格中心的「盘面角度」换算成「旋转角度」,再加一点抖动即可。抖动取半格宽的 36%,保证不像机械臂一样次次停在正中:
const sectorAngle = 360 / this.tasks.length;
const jitter = (Math.random() - 0.5) * sectorAngle * 0.36;
this.startAngle = this.currentAngle;
const currentNormalized = ((this.startAngle % 360) + 360) % 360;
// 第 i 格中心换算成旋转角:360 - (i + 0.5) * sectorAngle
const landingAngle = (360 - (targetIndex + 0.5) * sectorAngle + jitter + 360) % 360;
const landingDelta = (landingAngle - currentNormalized + 360) % 360;
this.targetAngle = this.startAngle + rotations * 360 + landingDelta;rotations 是随机的整数圈数,landingDelta 永远是 0~360 的正数,两者相加让目标角单调递增——动画永远朝一个方向转,不会倒抽。
三、逐帧动画:16ms 定时器 + easeOutQuart + 过格即响
不用动画库,一个 setInterval(..., 16) 加四次方缓动就够了。缓动函数决定「快出慢停」的体感;每帧重算当前角并全量重画;每滑过一格播一声 tick,随着角速度自然变疏:
private onAnimationFrame(): void {
const elapsed = Date.now() - this.animStartTime;
const progress = Math.min(elapsed / this.totalDuration, 1);
const eased = this.easeOutQuart(progress);
this.currentAngle = this.startAngle + (this.targetAngle - this.startAngle) * eased;
this.drawWheel();
const sectorIndex = this.getResultIndex();
if (sectorIndex !== this.lastSectorIndex) {
this.lastSectorIndex = sectorIndex;
SoundEngine.playTick();
}
if (progress >= 1) { this.stopSpin(); }
}
private easeOutQuart(value: number): number {
return 1 - Math.pow(1 - value, 4);
}停下那一刻还有个 120ms 的「指针回弹」:指针 y 偏移 6px 再归位,一个 setTimeout 的事。三个定时器(动画、回弹、出结果)全部登记在实例字段里,aboutToDisappear 和每次 @Watch 回调先 clearTimers()——页面退出后定时器还挂着往画布上重画,是 Canvas 组件最常见的内存与崩溃来源。
四、抽取规则:已完成的格不再参与
「本局已处理的格不再抽」的规则单独放进 WheelRoundState,画布只管画。随机数用前先夹到 [0, 0.999999],避免 Math.random() 恰好回 1 时越界,这是这类映射最省心的防御:
export class WheelRoundState {
static availableIndices(tasks: TaskItem[], completedTaskIds: string[]): number[] {
const indices: number[] = [];
tasks.forEach((task: TaskItem, index: number) => {
if (completedTaskIds.indexOf(task.id) < 0) {
indices.push(index);
}
});
return indices;
}
static pickAvailableIndex(tasks: TaskItem[], completedTaskIds: string[],
randomValue: number): number {
const indices = WheelRoundState.availableIndices(tasks, completedTaskIds);
if (indices.length === 0) { return -1; }
const normalized = Math.max(0, Math.min(randomValue, 0.999999));
return indices[Math.floor(normalized * indices.length)];
}
}候选池本身的洗牌在 TaskEngine 里,是标准 Fisher-Yates:从尾往头,每个位置和「含自己在内的前缀」随机交换,O(n) 且每个排列等概率。洗完取前 K 个,自定义任务占比封顶 50%,两池拼完再整体洗一次。
private shuffle<T>(array: T[]): T[] {
const result = [...array];
for (let i = result.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
const temp = result[i];
result[i] = result[j];
result[j] = temp;
}
return result;
}总结成三条可以直接抄的经验:其一,转盘类效果用「全量重画」而不是「增量擦除」,一帧一个由 save/restore 包住的完整场景,代码短且不会留残影;其二,落点数学先在纸上推一遍(指针角是旋转角的补角、目标角是中心角的补角),写进代码就是两行取模;其三,定时器生命周期和组件绑定,离开页面就清,别指望系统替你收。
- 点赞
- 收藏
- 关注作者
评论(0)