Search code examples
javascripthtmlcanvaspositionmouse

JavaScript canvas and mouse position


I'm trying to make a drawing board in HTML5 with JavaScript, but the tools (like pencil, brush etc..) position is different unlike I thought.

I found it is different because of bitmap(?) so I'm trying to fix it from other answers which persons already asked, but I failed..

How to find the correct position of the mouse?

images

Here is my HTML code (I use bootstrap)

<div class="col-sm-10">
    <canvas id="c" width="900" height="500"></canvas>
</div> 

This is js (pencil code is not mine, I found on the internet)

var el = document.getElementById('c'); //캔버스
var ctx = el.getContext('2d');  //붓

function pencil () {
    var pos = getMousePos(el, e);

    el.onmousedown = function() {
      isDrawing = true;
      ctx.moveTo(pos.X, pos.Y);
    };

    el.onmousemove = function() {
      if (isDrawing) {
        ctx.lineTo(pos.X, pos.Y);
        ctx.stroke();
      }
    };

    el.onmouseup = function() {
      isDrawing = false;
    };
}

Solution

  • I found the getMousePos function here and it looked like it would work with what you're doing. But, it accepts an argumente (an event) that won't be defined where you were using it. Try moving the call to getMousePos inside the event handler where the event is defined.

    Also, isDrawing wasn't defined.

    var el = document.getElementById('c');
    var ctx = el.getContext('2d');  //붓
    ctx.strokeStyle = "#FF0000";
    
    function pencil () {
      var isDrawing = false;
    
      el.onmousedown = function(e) {
        var pos = getMousePos(el, e);
        isDrawing = true;
        ctx.moveTo(pos.x, pos.y);
      };
    
      el.onmousemove = function(e) {
        var pos = getMousePos(el, e);
        if (isDrawing) {
          ctx.lineTo(pos.x, pos.y);
          ctx.stroke();
        }
      };
    
      el.onmouseup = function() {
        isDrawing = false;
      };
    }
    
    function getMousePos(canvas, evt) {
      var rect = canvas.getBoundingClientRect();
      return {
        x: evt.clientX - rect.left,
        y: evt.clientY - rect.top
      };
    }
    
    pencil()
    <div class="col-sm-10">
        <canvas id="c" width="900" height="500"></canvas>
    </div>