Karoline
Karoline

Reputation: 125

How to move a picture to where a cursor clicked on the canvas

I have an image of a character and I want to be able to move it to the position of where my/the user's cursor is clicking on my canvas. for example-if the user clicked on the middle of the screen, I want his animal to walk there gradually, (at a certain speed). Does anyone know how I can achieve that?

Upvotes: 0

Views: 61

Answers (1)

Nico Zhu
Nico Zhu

Reputation: 32775

How to move a picture to where a cursor clicked on the canvas

For your requirement, you could create DoubleAnimation for image. You could get your cursor clicked position with PointerPressed event then pass the position X,Y value to DoubleAnimation ToProperty. I created the sample you could refer.

Code behind

public MainPage()
{
    this.InitializeComponent();
    RootCanvasLayout.PointerPressed += new PointerEventHandler(Pointer_Pressed);
}

private void Pointer_Pressed(object sender, PointerRoutedEventArgs e)
{
    Windows.UI.Input.PointerPoint currentPoint = e.GetCurrentPoint(RootCanvasLayout);
    CreateAnimation(currentPoint);
}
void CreateAnimation(PointerPoint point)
{  var duration = new Duration(TimeSpan.FromMilliseconds(1000));
    DoubleAnimation doubleAnimationX = new DoubleAnimation();
    DoubleAnimation doubleAnimationY = new DoubleAnimation();
    doubleAnimationX.To = point.Position.X-Pic.ActualWidth/2;
    doubleAnimationX.Duration = duration;
    doubleAnimationY.To = point.Position.Y-Pic.ActualHeight/2;
    doubleAnimationY.Duration = duration;
    var conStoryboard = new Storyboard();
    conStoryboard.Children.Add(doubleAnimationX);
    conStoryboard.Children.Add(doubleAnimationY);
    Storyboard.SetTarget(doubleAnimationX, Pic);
    Storyboard.SetTarget(doubleAnimationY, Pic);
    Storyboard.SetTargetProperty(doubleAnimationX, "(Canvas.Left)");
    Storyboard.SetTargetProperty(doubleAnimationY, "(Canvas.Top)");
    conStoryboard.Begin();
}

Xaml

<Canvas Name="RootCanvasLayout" Background="Ivory">
    <Image Name="Pic" Width="100" Height="100"
           Source="Assets/hello.png" 
           Canvas.Left="0"
           Canvas.Top = "0"/>
</Canvas>

Upvotes: 3

Related Questions