Dragging UI while moving not working right

So, the canvas is in world space as a child of the camera.
The problem is that if I move or rotate the camera the UI goes all over the place, like this:
sparklinggrouchycarp

This is the code as of yet, I’m not sure how to fix it:

using UnityEngine;
using UnityEngine.EventSystems;

public class Draggable : MonoBehaviour, IDragHandler
{
    public Camera cam;

    public void OnDrag(PointerEventData data)
    {
        Vector3 mouseWorld = cam.ScreenToWorldPoint(new Vector3(MouseObject.screenPos.x, MouseObject.screenPos.y, transform.position.z));
        mouseWorld.z = transform.position.z;
        transform.position = mouseWorld;
    }
}

Thanks in advance

Solved it, the z part of the cam.ScreenToWorldPoint has to be a fixed number, as it is the distance from the camera