# Getting the mouses location on a world space canvas

I have a world space canvas in my scene and what im trying to do is when you click on the screen for it to return the mouses location in regards to the canvas width and height

so for example if i have a 512x512 canvas and i click in the bottom right of it it would return the value (512,512).

I have trying using ScreenPointToRay() but this was unsuccessful.

and help would be appreciated, im guessing there is just a function that will return the position you have clicked on that canvas but i cant find what this function would be

Thanks

// Make an abstract mathematical plane by picking any 3 pts on the canvas (in world space coordinate)
m_CanvasPlane = new Plane();
m_CanvasPlane.Set3Points (
m_Canvas.transform.TransformPoint (new Vector3 (0, 0)),
m_Canvas.transform.TransformPoint (new Vector3 (0, 1)),
m_Canvas.transform.TransformPoint (new Vector3 (1, 0))
);

``````// Raycast from the camera to the plane, to get the screen position on the canvas
Ray ray = m_Canvas.worldCamera.ScreenPointToRay (eventData.position);

float rayHitDistance;
if (m_CanvasPlane.Raycast (ray, out rayHitDistance)) {
//RESULT: Here is what you what (in world space coordinate)
Vector3 worldPosOnCanvas = ray.GetPoint (rayHitDistance);

}
``````

After doing a search, since no one has an answer to the problem. So I share my way here

That gets you the worldspace position at a given depth of a screen space coordinate

manage to figure it out in the end by converting the world to screen space to the canvas elements local space and then adding this to the center of the canvas element. There is likely a more optimal way of doing this, but here is my code if anyone else wants to look at it for a future thing/improve it.

`````` [SerializeField]
GameObject canvasElement;

Vector2 canvasCentre;

void Start()
{
GetCanvasCentre();
}

//finds the centre of the canvas
public void GetCanvasCentre()
{
canvasCentre = new Vector2(canvasElement.GetComponent<RectTransform>().sizeDelta.x/2,canvasElement.GetComponent<RectTransform>().sizeDelta.y/2);
}

public void GetRelativeMousePosition()
{
// print(EventSystem.current);
Vector2 hitLocation = new Vector2();

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;

if (Physics.Raycast(ray, out hit))
{
//convert the world position to a local position
var relativepoint = transform.InverseTransformPoint(hit.point);

hitLocation.x = canvasCentre.x + relativepoint.x;
hitLocation.y = canvasCentre.y + relativepoint.y;

//ensure the hit location never drops below 0 or above the canvas element size
hitLocation.x = Mathf.Clamp(hitLocation.x,0, canvasElement.GetComponent<RectTransform>().sizeDelta.x);
hitLocation.y = Mathf.Clamp(hitLocation.y,0,canvasElement.GetComponent<RectTransform>().sizeDelta.y);

print(hitLocation);
}
}
``````