現象描述:
快應用中通過setinterval周期函數來循環觸發canvas繪制代碼,在華為手機上繪制的動畫會很卡頓,不流暢。
問題代碼如下:
click0() {
this.speed = 0.3
let ctx = this.$element('canvas').getContext('2d')
setInterval(() => {
this.num0 += 2
this.noise = Math.min(0.5, 1) * this.MAX
this._draw(ctx)
this.MAX <= 200 && (this.MAX += 4)
}, 20)
},
_draw(ctx) {
this.phase = (this.phase + this.speed) % (Math.PI * 64)
ctx.clearRect(0, 0, this.width, this.height)
this._drawLine(ctx, -2, 'rgba(0, 194, 255, 0.2)')
this._drawLine(ctx, -6, 'rgba(0, 194, 255, 0.4)')
this._drawLine(ctx, 4, 'rgba(0, 194, 255, 0.6)')
this._drawLine(ctx, 2, 'rgba(0, 194, 255, 0.8)')
this._drawLine(ctx, 1, 'rgba(0, 194, 255, 1)', 4)
},
問題分析:
this._draw()方法中的canvas繪制操作時間長,最低需要100ms的繪制時間,而代碼中周期時間只有20ms,華為快應用引擎會執行這個周期內的操作,然后才能執行下一個周期。所以設置為20ms時的效果會看起來比較慢。
解決方法:
開發者可以先根據設備信息接口獲取下設備信息中的引擎的提供商判斷是否是華為的快應用引擎,如果是華為快應用引擎則設置間隔時間大於100ms,不是則可以設置小於100ms,可解決華為快應用引擎和快應用聯盟引擎差異問題。代碼如下(紅色部分):
onShow: function () {
var that = this
device.getInfo({
success: function (ret) {
console.log("handling success:", JSON.stringify(ret));
that.engineProvider = ret.engineProvider;
},
fail: function (erromsg, errocode) {
console.log("message:", erromsg, errocode);
}
})
},
click0() {
var that = this
this.speed = 0.3
console.log(that.engineProvider)
let ctx = this.$element('canvas').getContext('2d')
if (that.engineProvider === "huawei") {
setInterval(() => {
this.num0 += 2
this.noise = Math.min(0.5, 1) * this.MAX
this._draw(ctx)
this.MAX <= 200 && (this.MAX += 4)
}, 120)
} else {
setInterval(() => {
this.num0 += 2
this.noise = Math.min(0.5, 1) * this.MAX
this._draw(ctx)
this.MAX <= 200 && (this.MAX += 4)
}, 20)
}
},
_draw(ctx) {
this.phase = (this.phase + this.speed) % (Math.PI * 64)
ctx.clearRect(0, 0, this.width, this.height)
this._drawLine(ctx, -2, 'rgba(0, 194, 255, 0.2)')
this._drawLine(ctx, -6, 'rgba(0, 194, 255, 0.4)')
this._drawLine(ctx, 4, 'rgba(0, 194, 255, 0.6)')
this._drawLine(ctx, 2, 'rgba(0, 194, 255, 0.8)')
this._drawLine(ctx, 1, 'rgba(0, 194, 255, 1)', 4)
},
_drawLine(ctx, attenuation, color, width) {
ctx.save()
ctx.moveTo(0, 0);
ctx.beginPath();
ctx.strokeStyle = color;
ctx.lineWidth = width || 1;
var x, y;
for (var i = -this.K; i <= this.K; i += 0.01) {
x = this.width * ((i + this.K) / (this.K * 2))
y = this.height / 2 + this.noise * this._globalAttenuationFn(i) * (1 / attenuation) * Math.sin(this.F * i - this.phase)
ctx.lineTo(x, y)
}
ctx.stroke()
ctx.restore()
},
欲了解更多詳情,請參閱:
canvas接口介紹:
https://developer.huawei.com/consumer/cn/doc/development/quickApp-References/quickapp-api-canvas
快應用開發指導文檔:https://developer.huawei.com/consumer/cn/doc/development/quickApp-Guides/quickapp-whitepaper
原文鏈接:https://developer.huawei.com/consumer/cn/forum/topic/0204404988672310224?fid=18
原作者:Mayism