我正在尝试使用canvas API(与html5中使用的相同)在qml中制作一个计时器。我需要每隔一秒左右重绘一次屏幕。是否有任何功能可以使用新输入的参数更新屏幕?例如,我使用 arc 函数指定要绘制的时钟弧的角度:
ctx.arc(150, 150, 95, 0,1.57,false);
在这种情况下,角度将每隔一秒左右改变一次。
你不能setTimeout()
在 QML 中使用,它只能在浏览器的 JS 中使用,在 Qml 中你必须认为是声明性的:
导入 QtQuick 2.0
Canvas {
id: canvas;
width: 360;
height: 360;
contextType: "2d";
renderStrategy: Canvas.Threaded;
renderTarget: Canvas.Image;
antialiasing: true;
smooth: true;
onPaint: {
if (context) {
context.clearRect (0, 0, width, height);
context.beginPath ();
context.moveTo (width / 2, height / 2);
context.arc (width / 2,
height / 2,
50,
0,
angle * Math.PI / 180,
false);
context.closePath ();
context.fillStyle = "red";
context.fill ();
}
}
property real angle : 0;
Timer {
interval: 1000;
repeat: true;
running: true;
onTriggered: {
// update your angle property as you want
canvas.angle = (canvas.angle < 360 ? canvas.angle +6 : 0);
// repaint
canvas.requestPaint ();
}
}
}
我冒昧地为 Canvas 设置了最佳设置,以使您获得最佳渲染效果!
你可以使用 setTimeOut 吗?
setTimeout(update, 1000);
function update() {
ctx.clearRect(0, 0, width, height);
ctx.arc(150, 150, 95, 0,1.57,false);
}
如果需要传入变量,则需要使用匿名函数,本文对此进行了说明:如何将参数传递给 setTimeout() 回调?或查看下面的代码示例。
setTimeout(function() {
update(topicId);
}, 1000)