0

Hi, guys i am working on a way to draw with your mouse with Canvas. This is how far i am:

function drawdraw(){
    test = document.getElementById('test');
    ctx = test.getContext('2d');

    window.addEventListener("mousemove", drawing,false);
}

function drawing(e){
    ctx.clearRect(0,0,500,200);
    var xPos = e.pageX-test.offsetLeft;
    var yPos = e.pageY-test.offsetTop;
    ctx.fillRect(xPos, yPos,30,30);
}
window.addEventListener("load", drawdraw,false);

My current problem is that I do not have the right cursor coordinates. I tried e.clientX , e.clientX and the example above.

I want to be able to move my canvas dynamicly, and I want the coordinates of the mouse to be 0,0 at top left of the canvas, and 500,200 at the bottom right of the canvas. In other words I just want my coordinates to be within the canvas, and not coordinates of the page. Anyone? :)

Btw. I am interested in a javascript solution, so if I can, I want to avoid jQuery.

Dilip Manek
  • 9,095
  • 5
  • 44
  • 56
Kristian Daugaard
  • 185
  • 1
  • 3
  • 11

1 Answers1

1

test is a local variable of function drawdraw and you are using it also in drawing function. You need to declare it as global variable.

Muhammad Talha Akbar
  • 9,952
  • 6
  • 38
  • 62
  • thats true, i fixed that, but still no result – Kristian Daugaard Feb 16 '13 at 14:57
  • my current result is that it registres my mouse events at about 200px from the top, and 0px from the left. this is relative to the body tag or html tag if you will. But i need it to be relative to the canvas, i just do not know the code – Kristian Daugaard Feb 16 '13 at 15:00
  • @KristianDaugaard `e.pageX` / `e.pageY` gives you values of cursor position from html document. You can subtract canvas `top` / `left` position from `e.pageX` / `e.pageY` and it will give you relative to canvas. – Muhammad Talha Akbar Feb 16 '13 at 15:01
  • @Aspring Aqib i am aware, then what i am asking, instead of e.page / e.client What gives you the values of cursor position from another object? does such thing not exist? – Kristian Daugaard Feb 16 '13 at 15:04
  • Ahh, IDTS! but i give a try on it ;) – Muhammad Talha Akbar Feb 16 '13 at 15:07
  • It happens so that my canvas element is inside a wrapper that has a margin of auto, for resolution compability. That is why i asked so specific as i did, in regards to getting the coordinates of only the canvas. so topleft canvas = 0,0 and bottomright = 500,200 – Kristian Daugaard Feb 16 '13 at 15:09
  • http://stackoverflow.com/questions/2614461/javascipt-get-mouse-position-relative-to-parent-element . – Muhammad Talha Akbar Feb 16 '13 at 15:10
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/24625/discussion-between-aspiring-aqib-and-kristian-daugaard) – Muhammad Talha Akbar Feb 16 '13 at 15:11