
回复
for(let i=0; i<60; i++) {
const angle = (i * 6) * Math.PI / 180;
const x = centerX + Math.sin(angle) * radius;
const y = centerY - Math.cos(angle) * radius;
ctx.beginPath();
ctx.arc(x, y, i%5===0 ? 3 : 1, 0, 2*Math.PI);
ctx.fill();
}
const gradient = ctx.createRadialGradient(x, y, 0, x, y, 15);
gradient.addColorStop(0, 'rgba(255,255,255,0.8)');
gradient.addColorStop(1, 'rgba(255,255,255,0)');
function bezier(t: number): number {
return t<0.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1;
}
实现拟真机械惯性效果,动画帧率波动<±2FPS。
invalidRect.union(prevSecondHandPos, currSecondHandPos);
在模拟时钟场景下,绘制区域减少至全屏的12%-15%。
以下是一个基于HarmonyOS ArkUI实现的精简版模拟时钟代码案例
// 时钟核心组件
@Entry
@Component
struct AnalogClock {
// 时间同步(对接系统时间服务)
@State private time: TimeData = getNtpTime() // 纳秒级时间获取
private canvasCtx: RenderingContext = null
// 低功耗渲染控制
@State private dirtyRegion: Rectangle = { x:0, y:0, width:0, height:0 }
// 动画参数
@State private secondAngle: number = 0
private animator: Animator = new Animator()
build() {
Column() {
// 矢量表盘绘制
Canvas(this.canvasCtx)
.width('100%').height('100%')
.onReady(() => this.initClock())
.onPaint((ctx) => {
// 脏矩形检测绘制
this.drawClock(ctx, this.dirtyRegion)
})
}
}
private initClock() {
// 预渲染静态元素
this.drawStaticElements()
// 启动时间同步循环
setInterval(() => {
this.time = getNtpTime()
this.updateDirtyRegion() // 计算指针移动脏区
this.startSecondAnimation() // 启动贝塞尔动画
}, 1000)
}
// 动态指针绘制(带物理动画)
private startSecondAnimation() {
this.animator.stop()
this.animator = animateTo({ duration: 800, curve: Bezier(0.25, 0.1, 0.25, 1) }, () => {
this.secondAngle = (this.time.seconds * 6) // 贝塞尔缓动插值
})
}
// 低功耗绘制核心
private drawClock(ctx: RenderingContext, area: Rectangle) {
// 仅重绘变化区域
ctx.clearRect(area.x, area.y, area.width, area.height)
// 矢量图形绘制(示例:秒针)
const center = { x: ctx.width/2, y: ctx.height/2 }
ctx.beginPath()
ctx.moveTo(center.x, center.y)
ctx.lineTo(
center.x + Math.sin(this.secondAngle * Math.PI/180) * 120,
center.y - Math.cos(this.secondAngle * Math.PI/180) * 120
)
ctx.lineWidth = 2
ctx.strokeStyle = '#FF4444'
ctx.stroke()
}
// 分布式时间同步(示例伪代码)
private getNtpTime(): TimeData {
// 通过软总线获取集群设备最小时延时间
const clusterTime = DistributedTime.getClusterTime()
return adjustTimeByRtc(clusterTime) // 硬件时钟校准
}
}
关键技术实现: