1
votes

I have simple code to "draw" in canvas element:

function doFirst(){
var x = document.getElementById('canvas');
canvas = x.getContext('2d');
window.addEventListener("mousemove", rys, false);
}

function rys(e){

var xPos = e.clientX;
var yPos = e.clientY;

canvas.fillStyle="#000";
canvas.beginPath();
canvas.arc(xPos-7,yPos-7,10,0,Math.PI*2,true);
canvas.closePath();
canvas.fill();

}
window.addEventListener("load", doFirst, false);

As you can see, the function is working only when the mouse is over the canvas element. Now i want to make it "draw" when the mouse is clicked (just like in paint). Can someone tell me how to do it (with code)? Thx for help

1
I was thinkinh about jQuery mousedown() but I don't know how to use it correctlyAmay

1 Answers

3
votes

You need to keep track of the current mouse button state (pressed or not pressed) independently of the mouse movements.

You can do this by attaching event handlers to the "mousedown" and "mouseup" events, similar to how you attached to the "mousemove" event.

In these event handlers, you could keep track of the current state of the first mouse button by updating a global variable indicating whether or not the button is currently pressed. Then, in your "mousemove" handler, you can check this global variable and determine whether or not to paint when the mouse is moved.

When using the "mouseup" and "mousedown" events, you may want to limit your handling to only when the first mouse button is pressed. You can do this by checking that the event property "button" is 0. Note, that you can check for other buttons and keep track of them, also.

You can see a working example of this here: http://jsfiddle.net/mQtKz/