1

I need to change my mouse cursor to a custom image.

If possible I would like to do it on a spritesheet. I can't do it from the css because I'm using it in a game. I already know how to decide when etc.

What I need to know is how do I change the cursor to an image, and deciding the image position and size? Is there any easy solution similar to the drawImage's image position?

3
  • 2
    you can do it using css if you use javascript to modify the css... Commented Apr 3, 2012 at 5:00
  • I know I can do it in css, but if possible I rather dont, as I said in the post. Commented Apr 3, 2012 at 5:03
  • 1
    Setting the CSS for the cursor is the only way to hide it. Why would you not want to use CSS anyway? Commented Apr 3, 2012 at 5:06

2 Answers 2

2

You can set the CSS using javascript to hide the cursor:

your_canvas.style.cursor = "none"

You can then get the cursor's position (it's now hidden) with something like this:

your_canvas.addEventListener("mousemove", function (ev) {
    var mouseX = ev.pageX - GetTopLeft(your_canvas).Left;
    var mouseY = ev.pageX - GetTopLeft(your_canvas).Top;
});

Then you can modify your canvas to show your fancier cursor sprite at that location.

GetTopLeft is defined as follows:

function GetTopLeft(elm){

    var x, y = 0;

    //set x to elm’s offsetLeft
    x = elm.offsetLeft;

    //set y to elm’s offsetTop
    y = elm.offsetTop;

    //set elm to its offsetParent
    elm = elm.offsetParent;

    //use while loop to check if elm is null
    // if not then add current elm’s offsetLeft to x
    //offsetTop to y and set elm to its offsetParent

    while(elm != null)
    {

    x = parseInt(x) + parseInt(elm.offsetLeft);
    y = parseInt(y) + parseInt(elm.offsetTop);
    elm = elm.offsetParent;
    }

    //here is interesting thing
    //it return Object with two properties
    //Top and Left

    return {Top:y, Left: x};

}

Though I can't remember where I copied the GetTopLeft function from...

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah I have a function for mouse position on canvas allready, and just drawing the image as is as you and Mike Depies said was a very elegant solution to my problem
0

If you are using a canvas, just hide the cursor over the canvas and draw your own sprite on the canvas at mouse position.

2 Comments

this was a nice and simple solution I didn't think about. will use this approach.
No problem, best of luck with your development

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.