如何通过鼠标拖动图像

时间:2019-08-01 09:44:18

标签: c# blazor

当我尝试使用Blazor用鼠标拖动图像时遇到一个问题。第一次,我想它可以由OnMouseMove,OnMouseDown和OnMouseUp实现。但是我发现在单击鼠标然后移动指针后无法触发MouseMove事件,从而触发了OnDrag事件。但是,当我按下鼠标单击时,再次触发了OnDrag事件,但ScreenX / ClientX / ScreenY / ClientY的值为0。

<div style="position:relative; width:1000px; height:800px;"
     @onmousedown="@OnMouseDown"
     @onmouseup="@OnMouseUp"
     @onmousemove="@OnMouseMove">

    <img src="https://www.devexpress.com/products/i/news/devexpress-blazor-razor-thumbnail-hd.png"
         style="position:absolute; top: @(offsetY)px; right: @(offsetX)px;" />
</div>
@code{

    double x, y, offsetX, offsetY;
    bool isDragging;


    void OnDrag(UIDragEventArgs args)
    {
        Console.WriteLine("OnDrag");
        if (!isDragging) return;

        var endX = args.ClientX;
        var endY = args.ClientY;
        var dx = endX - x;
        var dy = endY - y;

        offsetX += dx;
        offsetY += dy;

        x = args.ClientX;
        y = args.ClientY;

        StateHasChanged();
    }

    void OnMouseMove(UIMouseEventArgs args)
    {
        Console.WriteLine("OnMouseMove");
        if (!isDragging) return;

        var endX = args.ClientX;
        var endY = args.ClientY;
        var dx = endX - x;
        var dy = endY - y;

        offsetX += dx;
        offsetY += dy;

        x = args.ClientX;
        y = args.ClientY;

        StateHasChanged();
    }

    void OnMouseDown(UIMouseEventArgs args)
    {
        x = args.ClientX;
        y = args.ClientY;
        isDragging = true;
    }

    void OnMouseUp(UIMouseEventArgs args)
    {
        isDragging = false;
    }
}

1 个答案:

答案 0 :(得分:2)

这有点粗糙,但这似乎可行(注意左边:):

<div style="position:relative; width:1000px; height:800px;" draggable="true"
     @ondragend="OnDragEnd"
     @ondragstart="@OnDragStart">

    <img src="https://www.devexpress.com/products/i/news/devexpress-blazor-razor-thumbnail-hd.png"
         style="position:absolute; top: @(offsetY)px; left: @(offsetX)px;" />
</div>

@code
{
    double startX, startY, offsetX, offsetY;

    void OnDragStart(DragEventArgs args)
    {
        startX = args.ClientX;
        startY = args.ClientY;
    }

    void OnDragEnd(DragEventArgs args)
    {
        offsetX += args.ClientX - startX;
        offsetY += args.ClientY - startY;
    }

}