3

I have a canvas where you can draw and I would like the user to see the size of the point he is drawing. So I need to draw a custom cursor as 10x10 pixel square on the canvas. Of course I would not like to paint over the image while the user is just moving the mouse.

My ideas how I could do this:

  1. I could somehow backup the original image and paint it all over every time
  2. I could move a with the cursor. But I would need to forward every click and make it invisible if the cursor left the canvas.
  3. I could create a layered canvas with a second canvas on top of mine just for drawing the cursor.

What would be the best to do this?

Update

Sorry, I did not explain myself very well. The cursor will need to change color and snap to a grid, so I really need to paint it myself. I know about css cursor:url(...) that does not work for me.

Community
  • 1
  • 1
PiTheNumber
  • 22,828
  • 17
  • 107
  • 180
  • Check this: http://www.w3schools.com/cssref/pr_class_cursor.asp – David Starkey May 06 '13 at 15:28
  • Why don't you just use the CSS3 cursor style? http://www.htmlgoodies.com/beyond/css/create-custom-cursors-with-javascript-and-css3.html#fbid=KOKvRhvi51V – PitaJ May 06 '13 at 15:31
  • @DavidStarkey Thank you, but does not work for me. I need a black square in a custom color. Also the square can not move freely but need to jump in the given grid. – PiTheNumber May 06 '13 at 15:31
  • 1
    You can use an image for the cursor, so really you can make it whatever you want: http://www.w3schools.com/cssref/playit.asp?filename=playcss_cursor&preval=url%28smiley.gif%29,url%28myBall.cur%29,auto – David Starkey May 06 '13 at 15:32

2 Answers2

2

CSS3:

#canvas1 {
    cursor: url(./myCursor.cur), none;
}
PitaJ
  • 12,969
  • 6
  • 36
  • 55
2

Checkmark+1 to PitaJ and David Starkey--they are correct.

The simplest/most efficient solution is to modify the cursor itself. As mentioned, you can even do custom images for the cursor to do your color changes.

But if you absolutely need snap-to-grid then you have to go with something like the layered cursor canvas. There's no way to force a user's cursor into grid alignment. (Think of the pranks that would result!)

Both number 1 and 3 would work. I would go with number 3 myself. "Best" however is up to you.

markE
  • 102,905
  • 11
  • 164
  • 176
  • i agree fully, i would go with implementing 3. Considering you have a drawing application, you should build it using a rendering engine, and not event based (like typical webapps) IE you should have a program loop that runs at a specific interval. This program loop should tell the context of your canvas what to draw and where. The program loop will allow you to handle animations; which is technically how you get the mouse cursor to snap. As you need to check at specific intervals (typically 1000 / fps) to update the current coordinates of the mouse. You would use x and y on a modulus – 1-14x0r May 21 '13 at 19:26