我正在嘗試使用 Blazor 為圓形 svg 制作動畫。我已經在俄羅斯方塊游戲中看到了這一點,所以我可能只是想不出如何讓它發揮作用。<svg width="600" height="400"> <Ball Height="@Ball.Height" Width="@Ball.Width" CurrentPosition="@Ball.CurrentPosition"></Ball></svg><button class="btn btn-primary" @onclick="@Bounce">bounce</button>成分@inherits BallModel;@using Blong.Client.Model<circle cx="@CurrentPosition.X" cy="@CurrentPosition.Y" r="@Radius" style="@Style" />退回代碼 void Bounce() { for (int i = 0; i < 1000; i++) { Task.Run(() => SetPosition(Ball.CurrentPosition.X, Ball.CurrentPosition.Y++, GameHeight)); } } public async Task<bool> SetPosition(int x, int y, int LastRow) { if (y <= LastRow) { Ball.CurrentPosition.Y++; Thread.Sleep(500); return true; } return false; }這確實有點工作。每次我按下按鈕時,我的球都會跳到新位置。有什么方法可以讓它在循環時重新加載嗎?我試圖看到我的球在屏幕上移動。
1 回答

慕沐林林
TA貢獻2016條經驗 獲得超9個贊
基本上通知Blazor在循環內更新 UI 就足夠了:
StateHasChanged();
但是東西很少。首先,該SetPosition方法不包含任何等待并將同步運行。
然后Bounce可以異步,而不是自己創建新任務,以防您不想阻塞主線程。
此外,GameHeight在當前 View 的狀態下,它看起來像是一個常量或靜態,因此我會在被調用的方法中直接引用它,而不是將它作為參數傳遞,但這只是個人意見。
另一件事是,確保在已經“彈跳”時不會多次調用彈跳。
而且我認為邏輯線圈可以簡化一點。
這是我的建議:
public async Task Bounce()
{
if(Bouncing) return;
Bouncing = true;
while(Ball.CurrentPosition.Y <= GameHeight)
{
Ball.CurrentPosition.Y++;
StateHasChanged();
await Task.Delay(500);
}
// in case View has been resized, make sure Ball is not out of boundaries
Ball.CurrentPosition.Y = GameHeight;
StateHasChanged();
Bouncing = false;
}
- 1 回答
- 0 關注
- 147 瀏覽
添加回答
舉報
0/150
提交
取消