0

I wrote a very simple JavaScript that uses the HTML5 canvas. When the user clicks their mouse on the canvas the script gets their mouse coordinates, then when they move their mouse while holding it down it draws a line, this repeats until they let up on the mouse. But it does not work and I have no idea why? Thanks in advance for your help.

<body>
<canvas id="myCanvas" width="500" height="500" style="border:1px solid #000000;">
</canvas>

<script>
// Canvas link
var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');

// Variables
var x1;
var y2;
var isPressed = false;

// Event listeners
context.addEventListener('mousedown', functionMouseDown, false);
context.addEventListener('mousemove', functionMouseMove, false);
context.addEventListener('mouseup', functionMouseUp, false);


function functionMouseDown() {
    // Get coordinates
    x1 = mousePos.x;
    y1 = mousePos.y;

    isPressed = true;
}

function functionMouseMove() {
     // If mouse is down and moved start drawing line
     if (isPressed == true) {
        drawLine();
     }
}

function functionMouseUp() {
    // Stop drawing line
    isPressed = false;
}

function drawLine() {
// Draw line
context.moveTo(x1,y1);
context.lineTo(x,y);
context.stroke();

// Set start coordinates to current coordinates
x1 = x;
y1 = y;
}
</script>
</body>
</html>
2
  • 1
    What is mousePos.x / y and x / y? Commented Dec 2, 2012 at 5:39
  • I started with an ActionScript and tired to convert it to JavaScript. Commented Dec 2, 2012 at 5:40

1 Answer 1

3

There are several problems here. You need to get the mouse position, which is not simply stored in mousePos.x/y. You get through the mouse move event, passed as the first param to the function which is added as the listener for mousemove, mousedown, mouseup. Here is how I fixed it

  function functionMouseDown(e) {
      // Get coordinates
      x1 = e.clientX
      y1 = e.clientY;

      isPressed = true;
  }

  function functionMouseMove(e) {
       // If mouse is down and moved start drawing line
       if (isPressed == true) {
          drawLine(e);
       }
  }

  function functionMouseUp() {
      // Stop drawing line
      isPressed = false;
  }

  function drawLine(e) {
  // Draw line
  var x = e.clientX;
  var y = e.clientY;
  context.moveTo(x1,y1);
  context.lineTo(x,y);
  context.stroke();

  // Set start coordinates to current coordinates
  x1 = x;
  y1 = y;
  }
Sign up to request clarification or add additional context in comments.

Comments

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.