重载圆圈组件

我正在尝试使用 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;


    }

这确实有点工作。每次我按下按钮时,我的球都会跳到新位置。有什么方法可以让它在循环时重新加载吗?我试图看到我的球在屏幕上移动。


精慕HU
浏览 101回答 1
1回答

慕沐林林

基本上通知Blazor在循环内更新 UI 就足够了:StateHasChanged();但是东西很少。首先,该SetPosition方法不包含任何等待并将同步运行。然后Bounce可以异步,而不是自己创建新任务,以防您不想阻塞主线程。此外,GameHeight在当前 View 的状态下,它看起来像是一个常量或静态,因此我会在被调用的方法中直接引用它,而不是将它作为参数传递,但这只是个人意见。另一件事是,确保在已经“弹跳”时不会多次调用弹跳。而且我认为逻辑线圈可以简化一点。这是我的建议:public async Task Bounce(){&nbsp; if(Bouncing) return;&nbsp; Bouncing = true;&nbsp; while(Ball.CurrentPosition.Y <= GameHeight)&nbsp; {&nbsp; &nbsp; Ball.CurrentPosition.Y++;&nbsp; &nbsp; StateHasChanged();&nbsp; &nbsp; await Task.Delay(500);&nbsp; }// in case View has been resized, make sure Ball is not out of boundaries&nbsp; Ball.CurrentPosition.Y = GameHeight;&nbsp; StateHasChanged();&nbsp; Bouncing = false;}
打开App,查看更多内容
随时随地看视频慕课网APP