HTML5 Canvas not Aligned

So, I have the following code as HTML:

<canvas id='myCanvas'></canvas>
<span id='coords'></span>
<button class='clear'>clear</button>

The CSS to go with it:

#myCanvas{
  width: 278px;
  height: 100px;
  border-left: 2px solid black;
  border-bottom: 2px solid black;
}

And some Javascript:

var canvas = document.getElementById('myCanvas');
var context = canvas.getContext('2d');
var mouseClicked = false;

function writeMessage(canvas, message) {
  $('#coords').text(message);
}

function getMousePos(canvas, evt) {
  var rect = canvas.getBoundingClientRect();
  return {
    x: evt.clientX - rect.left,
    y: evt.clientY - rect.top
  };
}

$(document).on({
  'mousedown':function(){
    mouseClicked=true;
  },
  'mouseup':function(){
    mouseClicked=false;
  }
})

$('#myCanvas').on({
  'mousemove':function(evt){
    if(mouseClicked){
        var mousePos = getMousePos(canvas, evt);
        var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
        writeMessage(canvas, message);
      context.beginPath();
      context.rect(mousePos.x, mousePos.y, 1, 1);
      context.fillStyle = 'black';
      context.fill();
      context.lineWidth = 1;
      context.strokeStyle = 'black';
      context.stroke();
    }
  },
  'mousedown':function(evt){
    var mousePos = getMousePos(canvas, evt);
    var message = 'Mouse position: ' + mousePos.x + ',' + mousePos.y;
    writeMessage(canvas, message);
  }
});

// Clear canvas
$('.clear').click(function(){
  context.clearRect(0, 0, canvas.width, canvas.height);
});

// make other text non selectable
$('#coords').disableSelection();

The problem I’m having is when I draw on the canvas, the small squares I’m drawing don’t line up with where the cursor is currently at. It’s almost as if there’s some sort of vertical/horizontal scaling problem, but I’m not sure how to fix it.


Source: html5

Leave a Reply